Adding geo objects to a collection
Geo objects can be grouped into collections. You can create collections for group operations on geo objects. For example, you can subscribe to events of objects or set their options.
index.html
geo_object_collection.js
<!DOCTYPE html>
<html>
<head>
<title>Examples. Adding geo objects to a collection</title>
<meta
http-equiv="Content-Type"
content="text/html; charset=UTF-8"
/>
<!--
Set your own API-key. Testing key is not valid for other web-sites and services.
Get your API-key on the Developer Dashboard: https://developer.tech.yandex.ru/keys/
-->
<script
src="https://api-maps.yandex.ru/2.1/?lang=en_RU&apikey=<your API-key>"
type="text/javascript"
></script>
<script
src="geo_object_collection.js"
type="text/javascript"
></script>
<style>
html,
body,
#map {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div id="map"></div>
</body>
</html>
ymaps.ready(init);
function init() {
var myMap = new ymaps.Map(
"map",
{
center: [55.73, 37.75],
zoom: 9,
},
{
searchControlProvider: "yandex#search",
}
),
yellowCollection = new ymaps.GeoObjectCollection(null, {
preset: "islands#yellowIcon",
}),
blueCollection = new ymaps.GeoObjectCollection(null, {
preset: "islands#blueIcon",
}),
yellowCoords = [
[55.73, 37.75],
[55.81, 37.75],
],
blueCoords = [
[55.73, 37.65],
[55.81, 37.65],
];
for (var i = 0, l = yellowCoords.length; i < l; i++) {
yellowCollection.add(new ymaps.Placemark(yellowCoords[i]));
}
for (var i = 0, l = blueCoords.length; i < l; i++) {
blueCollection.add(new ymaps.Placemark(blueCoords[i]));
}
myMap.geoObjects.add(yellowCollection).add(blueCollection);
// You can subscribe to events of child elements through collections.
yellowCollection.events.add("click", function () {
alert("Yellow placemark clicked");
});
blueCollection.events.add("click", function () {
alert("Blue placemark clicked");
});
// You can set options of child elements through collections.
blueCollection.options.set("preset", "islands#blueDotIcon");
}