ak47rtt
ak47rtt

Reputation: 13

Yandex Maps API: add multiple placemarks

I understand how to create a single placemark and if I need to create more than one I do it like that:

ymaps.ready(init);

function init() {   

  var map = new ymaps.Map('map', {
    center: [55.76, 37.64], // lat, long
    zoom: 5,
    controls: ['zoomControl', 'fullscreenControl']
  });

  var data = [
    {
      name: 'Moskow',
      coordinates: [55.684758, 37.738521]
    },
    {
      name: 'Saint Petersburg',
      coordinates: [59.939095, 30.315868]
    },
  ];

  for (var i = 0; i < data.length; i++) {
    map.geoObjects.add(new ymaps.Placemark([data[i]['coordinates'][0], data[i]['coordinates'][1]], {
        balloonContent: data[i]['name']
    }));
  }

}

But is there a better way to add bunch of data to the map without a cycle?

Upvotes: 1

Views: 3393

Answers (1)

blues911
blues911

Reputation: 910

Yes, use Object Manager and organize your data into objects collection. Yandex Maps API provides convenient way for that case.

Here is the simple example according to your data:

ymaps.ready(init);

function init() {

  var map = new ymaps.Map('map', {
    center: [55.76, 37.64], // lat, long
    zoom: 5,
    controls: ['zoomControl', 'fullscreenControl']
  });

  // Objects collection
  var collection = {
    type: "FeatureCollection",
    features: [
      {
        type: "Feature",
        id: 0,
        geometry: {
          type: "Point",
          coordinates: [55.684758, 37.738521]
        },
        properties: {
          balloonContent: "Moskow"
        }
      },
      {
        type: "Feature",
        id: 1,
        geometry: {
          type: "Point",
          coordinates: [59.939095, 30.315868]
        },
        properties: {
          balloonContent: "Saint Petersburg"
        }
      }
    ]
  };

  // Object Manager
  objectManager = new ymaps.ObjectManager({ clusterize: true });
  objectManager.add(collection);

  map.geoObjects.add(objectManager);

}

Read about Object Manager. There you can find more examples.

Upvotes: 1

Related Questions