简体   繁体   中英

Get the ID of a marker on click in Mapbox

I have an angular view in which I bring data from some points from an api, I use a method to place the markers depending on the coordinates that the api gives me. In addition to the coordinates, the data has an ID. I need that when I click on the marker in addition to showing me the information to take the ID in some way and save it in a variable to be able to perform functions with that specific point. So far I have this.

map: Mapboxgl.Map; // THE MAP
marker: Mapboxgl.Marker; // THE MARKER
// THE METHOD TO CREATE THE MARKERS ON THE MAP
creteGeoJSON(data) {
        data.forEach((element) => {
            const el: HTMLElement = document.createElement('div');
            el.className = 'marker';
            el.style.backgroundImage = 'url(../../../../assets/img/icon.png)';
            el.style.width = '30px';
            el.style.height = '30px';
            el.style.cursor = 'pointer';
            el.style.backgroundSize = 'cover';
            this.marker = new Mapboxgl.Marker(el)
              .setLngLat(
                element.coor
                  .split(',')
                  .reverse()
                  .map((x) => +x)
              )
              .setPopup(
                new Mapboxgl.Popup({ offset: 25 }) // add popups
                  .setHTML(
                    `<h2>ID: ${element.id} </h2>`
                  )
              )
              .addTo(this.map);
            this.currentMarkers.push(this.marker);
        });
 }

// THE FUNCTION TO GET THE LAT AND LONG
getCoords(e) {
    this.map.getCanvas().style.cursor = 'pointer';
    this.map.on('click', (e) => {
      const lat = e.lngLat.lat;
      const lng = e.lngLat.lng;
      // GET SOME ID 
    });
}

If you want to do something when the user clicks on a marker, you should add the click event to the marker, not to the map.

A marker contains an HTML element, so you can just do:

marker = new Mapboxgl.Marker(el)
//...
.addTo(map);

el.addEventListener('click', () => {
  // in here you have access to the `element` object that contains your data
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM