Search code examples
javascriptjsongeojsonmapbox-gl-js

Mapbox GL - Adding a marker with a specific id


I have an array of markers and I want each marker to have a specific id so that I can call each one and animate it on its own.

I have this to add them to the map:

map.addSource('markers', {
    "type": "geojson",
     "data": geojson
});

map.addLayer({
    "id": "markers",
     "type": "symbol",
     "source":"markers",
     "layout": {
         "icon-image": "airport-15",
         "text-field": "{title}",
         "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
          "text-offset": [0, 0.6],
          "text-anchor": "top"
       }
});

And the data is from this geojson, which am filling from a file in a function and it is working:

var geojson = {
    type: 'FeatureCollection',
    features: []
};

Each marker is of this format:

var marker = {
      type: 'Feature',
       geometry: {
           type: 'Point',
           coordinates: coordinate
       },
       properties: {
            title: key,
            description: '',
       }
 }

Solution

  • Basically I added all GeoJSON data to a dictionary I called:

    markers = {}
    

    Then, I filled this dictionary with all the marker data, giving a unique id as key for each. This will spare me the use of two for loops in order to check WHICH marker was updated (meaning it is in the original array and in the updated marker array) and also makes it easier to update the values (to complete an animation of the markers from the original position to the updated one.

    geojson.features = Object.values(markers);
    map.getSource('markers').setData(geojson);
    

    If you find another way to easily locate objects in a GeoJSON array please share!