有标签过滤,但是当您单击按钮时它不会缩放到该标签,如何实现?
const categoriesData = {
category1: [{
lat: 53.442131071027305,
lon: 58.99983849999995,
name: 'Северный переход, 20а1',
caption: 'Северный переход, 20а',
},
],
category2: [{
lat: 53.426321310730245,
lon: 58.9609671588954,
name: 'ул. Советская, 20а',
caption: 'ул. Советская, 20а'
},
],
category3: [{
lat: 53.35935432593927,
lon: 59.007853228836,
name: 'ул. Коробова, 20',
caption: 'ул. Коробова, 20'
},
],
};
const init = () => {
const map = new ymaps.Map('YMapsID-1', {
center: [53.442131071027305,58.99983849999995],
zoom: 14,
});
let activeCategory = "category1";
const showCategory = (category) => {
map.geoObjects.removeAll();
categoriesData[category].forEach((item) => {
const placemark = new ymaps.Placemark([item.lat, item.lon], {
iconColor: '#1d79d3',
hintContent: item.name,
balloonContent: item.name,
iconCaption: item.caption,
});
map.geoObjects.add(placemark);
});
activeCategory = category;
}
const categoryButtons = document.querySelectorAll('.category-button');
categoryButtons.forEach((button) => {
button.addEventListener('click', (e) => {
const category = e.currentTarget.dataset.category;
showCategory(category);
});
});
showCategory(activeCategory);
};
ymaps.ready(init);
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://api-maps.yandex.ru/2.1/?lang=ru_RU" type="text/javascript"></script>
</head>
<body>
<!-- Создаём контейнер для карты -->
<div class="container">
<div class="container__wrapper">
<button class=" category-button" data-category="category1">
<p>Северный переход, 20а</p>
</button>
<button class=" category-button" data-category="category2">
<p>ул. Советская, 20а</p>
</button>
<button class=" category-button" data-category="category3">
<p>ул. Коробова, 20</p>
</button>
</div>
<div id="YMapsID-1" style="width: 500px; height: 400px"></div>
</div>
您可以处理div元素上的单击并将地图置于标签上的中心,并在单击后使用Map.setCenter()更改缩放。