2

Created some markers using an array of GeoJSON data:

$.getJSON("GetLocationsServlet", function(data) {
    L.geoJSON(data, {
        onEachFeature: onEachFeature
    }).addTo(mymap);
});

The GeoJSON data is like this:

[
{ "type": "Feature", "properties": { "name": "Riverway Sport Complex", "amenity": "GYM", "popupContent": "Riverway Sport Complex" }, "geometry": { "type": "Point", "coordinates": [-123.002846, 49.205036] },"id" : "1"} ,
{ "type": "Feature", "properties": { "name": "Imperial@Patterson", "amenity": "GYM", "popupContent": "Imperial@Patterson" }, "geometry": { "type": "Point", "coordinates": [-123.01249, 49.22193] },"id" : "2"} 
]

The markers were successfully created and showed on the map. At some point later, I needed to iterate through all Markers, so I used eachLayer function:

    var mymap = L.map('mapid').locate({setView: true, maxZoom: 15});

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png? '
    access_token=..., {
    maxZoom: 25,
    attribution: 
    id: 'mapbox.streets',
    }).addTo(mymap);

    .......
    $.getJSON( L.geoJSON()... )        
    .......

    mymap.eachLayer(function(layer) {
        alert (layer.options.id); 
       // Above alert successfully print out the tileLayer ID
        if (layer instanceof L.Marker) {
            alert("Marker [" + layer.options.title + "]");
        }
    });

However, it only looped through the main map tileLayer and stopped. Am I using the eachLayer method correctly? Marker is also a subclass of Layer?

Thanks,

user1941319
  • 375
  • 3
  • 19
  • Where is your `eachLayer` code executed compared to `$.getJSON`? – ghybs May 15 '18 at 16:24
  • The .$getGeoJSON code section is after the factory method and before the eachLayer() code. – user1941319 May 15 '18 at 16:28
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – ghybs May 15 '18 at 16:34
  • 1
    The `$.getJSON` is asynchronous so when you run the `mymap.eachLayer` in your example, the `getJSON` has not yet completed and has not yet added the additional layers to your map. – Gabriele Petrioli May 15 '18 at 16:47
  • Thanks for the replay. How can I miss this? ghybs and Gabriele – user1941319 May 15 '18 at 17:22
  • You should really use a `FeatureGroup()` instead of adding all to your map. It will be easier to iterate without the need to make you condition : `if (layer instanceof L.Marker) { }` – Baptiste May 16 '18 at 07:26
  • @Baptiste, Thanks for the reply. I don't want to use FeaturGroup in this situation because I actually need to treat each Marker as individual and handle differently to user interactions. – user1941319 May 16 '18 at 19:48

0 Answers0