Creating a menu for displaying groups of objects
YMapsML is a language for describing geographical objects.
In YMapsML, each geographical object is associated with a geometric shape and a geo object that is used for displaying this shape on the map. The shape definitions and their anchors to geographical coordinates are set in corresponding YMapsML elements. The gml:Point element is designated for the "point" shape.
The visual appearance of displayed objects is set in the repr:Representation element. For detailed instructions on setting styles for displayed objects, see the documentation.
Use the geoXml.load function for loading YMapsML data. After data is loaded, the function converts it to GeoObjectCollection and passes it to the handler function as a parameter.
<!DOCTYPE html>
<html>
<head>
<title>
YMapsML examples. Creating a menu for displaying groups of
objects.
</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="https://yandex.st/jquery/2.2.3/jquery.min.js"
type="text/javascript"
></script>
<script src="ymapsml_menu.js" type="text/javascript"></script>
<style type="text/css">
html,
body,
#map {
width: 400px;
height: 300px;
padding: 0;
margin: 0;
}
/* Menu style (start)*/
#menu {
list-style: none;
margin: 0;
padding: 0;
}
#menu a {
text-decoration: none;
border-bottom: dashed 1px;
}
a.active {
color: #000;
}
/* Menu style (end)*/
</style>
</head>
<body>
<div>
<ul id="menu"></ul>
</div>
<div id="map"></div>
</body>
</html>
ymaps.ready(init);
function init() {
// Creating an instance of the map.
var myMap = new ymaps.Map("map", {
center: [50.443705, 30.530946],
zoom: 12,
controls: [],
});
// Loading a YMapsML file.
ymaps.geoXml.load("data.xml").then(
function (res) {
res.geoObjects.each(function (item) {
addMenuItem(item, myMap);
});
},
// Called if loading the YMapsML file was unsuccessful.
function (error) {
alert(
"When loading the YMapsML file, the following error occurred: " +
error
);
}
);
// Adding an element to the list.
function addMenuItem(group, map) {
// Showing/hiding a group of geo objects on the map.
$(
'<a class="title" href="#">' +
group.properties.get("name") +
"</a>"
)
.bind("click", function () {
var link = $(this);
/**
* If the menu item is "inactive," we add the group to the map.
* Otherwise, we delete it from the map.
*/
if (link.hasClass("active")) {
map.geoObjects.remove(group);
} else {
map.geoObjects.add(group);
}
// Changing the "active" state of the menu item.
link.toggleClass("active");
return false;
})
// Adding a new menu item to the list.
.appendTo($("<li></li>").appendTo($("#menu")));
}
}