<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://tiles.locationiq.com/v3/libs/openlayers/8.2.0/ol.css" type="text/css">
<script src="https://tiles.locationiq.com/v3/libs/openlayers/8.2.0/ol.js"></script>
<style>
body { margin:0px; padding:0px; }
#map { position:absolute; top:0px; bottom:0px; width:100%; }
</style>
<script src="https://tiles.locationiq.com/v3/libs/olms/12.0.0/olms.js" type="text/javascript"></script>
<title>Map Click Listener</title>
</head>
<body>
<style>
.marker {
display: block;
border: none;
cursor: pointer;
padding: 0;
}
.coordinates {
background: rgba(0, 0, 0, 0.7);
color: #fff;
position: absolute;
bottom: 40px;
left: 10px;
padding: 5px 10px;
margin: 0;
font-size: 14px;
line-height: 18px;
border-radius: 3px;
display: none;
}
</style>
<div id="map"></div>
<pre id="coordinates" class="coordinates"></pre>
<script type="text/javascript">
var coordinates = document.getElementById('coordinates');
var key = 'pk.aa7f5d0539c5675b7f3429402939d8fa'; //Insert your LocationIQ access token here
var styleJson = 'https://tiles-staging.locationiq.com/v3/streets/vector.json?key=' + key;
const map = new ol.Map({
target: 'map',
view: new ol.View({
center: ol.proj.fromLonLat([-122.42, 37.779]),
zoom: 12
})
});
//to create a marker
var marker1 = new ol.Feature({
geometry: new ol.geom.Point(
ol.proj.fromLonLat([-122.444733, 37.767443])
),
});
//to enhance style and add icon to the map
marker1.setStyle(new ol.style.Style({
image: new ol.style.Icon({
scale: 0.5, //scale to adjust the proportion of the icon
src: 'https://tiles.locationiq.com/static/images/marker.png', //link of the icon
})
}));
//Let’s include the markers and create a vector source with it
var vectorSource = new ol.source.Vector({
features: [marker1]
});
//Let’s create a vector layer, with a source created above
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
zIndex: 1
});
map.addLayer(vectorLayer);
var translate1 = new ol.interaction.Translate({
features: new ol.Collection([marker1])
});
map.addInteraction(translate1);
// After the mouse click the following function is executed which updates the displayed lat and long
map.on('click', function(e) {
console.log(e.coordinate);
var coordinate = e.coordinate;
var lngLat = ol.proj.toLonLat(coordinate);
marker1.setGeometry(new ol.geom.Point(ol.proj.fromLonLat(lngLat)));
coordinates.style.display = 'block';
coordinates.innerHTML = 'Latitude: ' + lngLat[1] + '<br />Longitude: ' + lngLat[0];
});
olms.apply(map, styleJson);
</script>
</body>
</html>