4

If I have a object containing lats and longs how can i plot them in Leaflet using the marker constructor I tried looping through them

for(key in obj){
            var val = obj[key];
            var markers = new L.Marker([val.lat, val.long]);
            map.addLayer(markers);
        }

but its not showing up in the map

var obj ={
 0 : {
        lat: 15.606562000000000
        long: 32.513681000000000
    },
1 : {
        lat: -12.09137
        long: 34.7182
    }
}

2 Answers 2

2

No, you're not using the L.Marker constructor.

Constructor: L.Marker( <LatLng> latlng, <Marker options> options? )

And a L.LatLng is:

Constructor: L.LatLng( <Number> latitude, <Number> longitude)

So:

var markers = new L.Marker(new L.LatLng(val.lat, val.long));

Additional JS tips:

  1. markers should be marker, as it is a reference to a single marker.
  2. If your indices are incremental numbers, you should consider making obj an array, and use a for loop instead of a for-in. If not, use hasOwnProperty to avoid nasty surprises.
1
  • And an additional tip: Don't use the global variable var for a variable that is only being used inside the loop. Better use let (for a variable that is reassigned inside the block scope) or const (for a constant that is not reassigned - like val or marker). Commented Dec 28, 2018 at 10:42
1
var locations = [
       ["Locations 1", 6.625117, 39.145004],
       ["Locations 2", -6.5767859, 39.1304557],
       ["Locations 3", -6.8667841, 39.2530337],
       ["Locations 4", -6.7787336, 39.2273218],
       ["Locations 5", -6.7576158, 39.2768276],
];

for (var i = 0; i < locations.length; i++) {
    marker = new L.marker([locations[i][1], locations[i][2]])
             .bindPopup(locations[i][0])
             .addTo(mymap);
}
2
  • 1
    I did just like Shedrack showed, the only difference is I have my map in script tag in HTML and array is made in JavaScript. How can I display the points on map using that array? Commented Sep 15, 2021 at 13:37
  • @HalfSparrow, you will need to reference the array from the JavaScript file into the HTML file. Then you should be able to use it as seen above.
    – Umar Yusuf
    Commented Oct 18, 2021 at 7:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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