2

In Leaflet, I want all my markers to be hidden at the same time and show on the click of a checkbox.

Here is my code:

var cordnt=this.coordinates;
var overlayMarker = {};
 console.log("testing coodinates", cordnt)
var layerGroup = L.layerGroup().addTo(map)
for (i = 0; i < cordnt.length; i++) {
  newMarker = new L.marker([cordnt[i][0], cordnt[i][1]]).bindPopup(notation.desc);
  newMarker.openPopup()
   layerGroup.addLayer([newMarker])
  Object.assign(overlayMarker, {'Markers': layerGroup});
}

console.log("testing latlong",layerGroup)
L.control.layers(null, overlayMarker).addTo(map);

How can I achieve this?

  • Welcome to GSE ! I've reformated your question and your code, and add a clear question. Please edit your post for add details, code with comments, leaflet version and which navigator used, etc. – J. Monticolo Apr 24 at 11:30
  • The title of a question should not be the only non-code. In fact, the title should be brief summary of what the question is about, no more. The body requires details of the versions of software, the purpose, the data, and the problem encountered. "Wall of code" posts are downvoted and closed. – Vince Apr 24 at 11:37
  • Can you explain meaning of the title "Map container is already initialized"? It sounds like an error message. At which step it appears? – TomazicM Apr 24 at 12:01
3

Sounds like you want to read a file and create markers, and these markers should be in a layergroup so Leaflet handles them as one layer. Here is something similar to your code that I used.

$.getJSON(url, function(data) {
    for (i = 0; i < data.length; i++) { 
        var lng = data[i].coordinates[0];
        var lat = data[i].coordinates[1];
        var Line1 = data[i].addressLine1;
        var Line2 = data[i].addressLine2;
        MCDs = L.marker([lat,lng]).bindPopup("<b>Address: </b>" + Line1 + "<br />Region: " + Line2);
        mcd.addLayer(MCDs);
    } 
});

//mcd.addTo(map);  //uncomment if you want to layergroup drawn when the map draws, //leave commented if you want it unchecked in the layer control.

var overlayMaps = {
    "JSON Layer Group":mcd 
};  

//Add layer control
var layerControl = L.control.layers(baseMaps, overlayMaps).addTo(map);  
  • Thank you Bill i really appreciate your help thanks a lot – Rajan rek Apr 25 at 5:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.