Display Lat Lng Coordinates on click on Mapbox GL JS
Asked Answered
L

1

7

I'm trying to get my mapbox to display coordinates like this Google Map example, with a popup of lat lng coordinates on click. The closest I have gotten is getting a draggable marker which displays the coordinates at the bottom left of the map, if I tried an onclick function, the map just goes blank. How could I get the coordinates to appear as a popup on click?

var marker = new mapboxgl.Marker({
        draggable: true
    })
    .setLngLat([101.967, 35.431])
    .addTo(map);

function onDragEnd() {
    var lngLat = marker.getLngLat();

    coordinates.style.display = 'block';
    coordinates.innerHTML =
        'Longitude: ' + lngLat.lng + '<br />Latitude: ' + lngLat.lat;
}

marker.on('dragend', onDragEnd);

And I have css styles for .coordinates for them to display at the bottom left of the screen when the marker is dragged around. I know this is a simple question, but I'm totally new to mapbox and coding in general. Would appreciate any help! Thank you!

Legacy answered 29/7, 2020 at 16:59 Comment(0)
D
16

I think what you are looking for is a Mapbox Popup

I have drafted a quick fiddle on how to create a popup with the coordinates clicked, and here you have the relevant js code:

mapboxgl.accessToken = 'PUT HERE YOUR TOKEN';
var map = new mapboxgl.Map({
  container: 'map',
  style: 'mapbox://styles/mapbox/streets-v11',
  center: [-122.486052, 37.830348],
  zoom: 14
});
map.on('style.load', function() {
  map.on('click', function(e) {
    var coordinates = e.lngLat;
    new mapboxgl.Popup()
      .setLngLat(coordinates)
      .setHTML('you clicked here: <br/>' + coordinates)
      .addTo(map);
  });
});

enter image description here

Defamatory answered 29/7, 2020 at 17:19 Comment(7)
This is great! Worked like a charm, thank you so much!Legacy
Glad to help! if it solved your issue, please mark it as answer accepted in that way it will also help other users with the same issue to know it was the right solutionDefamatory
Very good. And how do i put these coordinates inside an input form? For example, in the Lat input, insert the latitude values ​​and in the Lng input, insert the longitude values ​​when clicked on the map?Witwatersrand
@MichelXavier I'd recommend you to open a new question on that topic as it's definitely a different one.Defamatory
@jscastro, thanks for your feedback. Actually i opened a question similar with this one. I'm just try to find some similar doubt related with my question. if you can help me, I appreciate :) ..... #63274512 .... thanks.Witwatersrand
@MichelXavier, I just replied to your question.Defamatory
@jscastro, i saw your solution and works for me. Thanks a lot :)Witwatersrand

© 2022 - 2024 — McMap. All rights reserved.