Highlighting objects
You can highlight various objects on the map, such as buildings, roads, and others. To do that, call the setSelectedObjects() method and pass an array of IDs of the objects that you want to highlight.
map.setSelectedObjects([id1, id2]);
You can get the object ID, for example, by adding a click listener to the map and catching the MapPointerEvent:
map.on('click', (e) => {
if (!e.target) {
return;
}
const { id } = e.target;
alert('Object ID is ' + id);
});
To disable highlighting, call the setSelectedObjects()
without arguments:
map.setSelectedObjects();
You can find a demonstration example below. Click on a map object to highlight it. Click on it again to remove the highlight.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>2GIS Map API</title>
<meta name="description" content="An object selection example" />
<style>
html,
body,
#container {
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
}
</style>
</head>
<body>
<div id="container"></div>
<script src="https://mapgl.2gis.com/api/js/v1"></script>
<script>
const map = new mapgl.Map('container', {
center: [55.308, 25.237],
zoom: 18,
key: 'Your API access key',
});
let selectedIds = [];
map.on('click', (e) => {
if (!e.target) {
return;
}
const { id } = e.target;
if (selectedIds.includes(id)) {
selectedIds = selectedIds.filter((i) => i !== id);
} else {
selectedIds.push(id);
}
map.setSelectedObjects(selectedIds);
});
</script>
</body>
</html>