leaflet

How to get all markers on Leaflet


I have a listener that will detect changes of the location of objects on databases. It will pass all the information of the object that is being changed.

I want to get all markers from the current map and find the marker that is affected. Once found, update the location.

But, I am still looking for the best ways to get all markers from the map and then I can update the location.

var map = L.map('map').setView([37.78541,-122.40787], 13);
var markers = new L.FeatureGroup();
var mapLink =
    '<a href="http://openstreetmap.org">OpenStreetMap</a>';
L.tileLayer(
    'https://{s}.tiles.mapbox.com/v4/examples.map-i87786ca/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoiZ2Vja29iIiwiYSI6IndzVjRGN0kifQ.lToORsjE0lkt-VQ2SXOb-Q', {
        attribution: '&copy; ' + mapLink + ' Contributors',
        maxZoom: 18,
    }).addTo(map);

var marker = createCircleMarker([44.977368, -93.232659]);
marker._id = "69"; // Id of the marker
map.addLayer(marker);
var socket = io();

socket.on('update location', function(obj) {
     // Get all markers and find markers with attribute obj.name to 
     // update the location to [obj.lat,obj.lon]

});

Solution

  • Use eachLayer method on L.map. Like

    map.eachLayer(function (layer) { 
        if (layer.options.name === 'XXXXX') {
            layer.setLatLng([newLat,newLon])
        } 
    });
    

    Documentation at http://leafletjs.com/reference-1.2.0.html#map-eachlayer