Search code examples
javascriptonclickcoordinatesmapboxmapbox-gl-js

Display Lat Lng Coordinates on click on Mapbox GL JS


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!


Solution

  • 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