2

Trying to add an array of points to a map with a Leaflet with .forEach.

I thought this should work, but alas, it does not:

var jsonData = [
  {
    "LNG":-75.16472099534634,
    "LAT":40.034508187448395,
    "NAME": "Resto1"
  },
  {
    "LNG":-75.17898120530263,
    "LAT":40.06738292573648,
    "NAME": "Resto2"
  }]


var addMarkers = function(point) {
      L.marker([point.LAT, point.LNG])
        .addTo(map)
        .bindPopup(point.NAME);
};

jsonData.forEach(addMarkers);

I understand I can do it like this:

var addMarkers = function(map) {
  for (var point in jsonData) {
     L.marker([jsonData[point].LAT, jsonData[point].LNG])
        .addTo(map)

But was hoping to do it more functionally. Any hints?

  • Have you seen this topic Loop through Leaflet Map layers. It was suggested to made jsonData.forEach(addMarkers); break on return false. – Taras Feb 4 at 5:29
  • 2
    I'm not sure what was going on when I first posted this. But my own solution jsonData.forEach(addMarkers); appears to be working when I try again. I think I just had some leakage going on. – user2740509 Feb 5 at 13:24
  • 1
    (But thanks for the tip @Taras) – user2740509 Feb 5 at 13:25

Your Answer

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

Browse other questions tagged or ask your own question.