0

код в песочницеНужно сделать фильтр, по нажатию на кнопку удалить все точки на карте и добавить те которые имеют нужный дата лист, сейчас по нажатию удаляется те у которых нужный даталист

ymaps.ready(init);

var placemarks = [
    {

ymaps.ready(init);

var placemarks = [
    {
        dataSlide: ['ALL','PARKS'],
        coordinates: [59.97,30.31],
        hintContent: '<div class="map__hint">ул. Литераторов, д. 19</div>',
        balloonContent: [
            '<div class="map__balloon">',
            '<img class="map__burger-img" src="/local/img/hotel_poster.png" alt=""/>',
            'Самые удобные отели. Заходите по адресу: ул. Литераторов, д. 19',
            '</div>'
        ]
    },
    {
        dataSlide: ['ALL','EDUCATION'],
        coordinates: [59.94,30.25],
        hintContent: '<div class="map__hint">Малый проспект В О, д 64</div>',
        balloonContent: [
            '<div class="map__balloon">',
            '<img class="map__burger-img" src="/local/img/hotel_poster.png" alt=""/>',
            'Самые удобные отели. Заходите по адресу: Малый проспект В О, д 64',
            '</div>'
        ]
    },
    {
        dataSlide: ['ALL','SPORT'],
        coordinates: [59.93,30.34],
        hintContent: '<div class="map__hint">наб. реки Фонтанки, д. 56</div>',
        balloonContent: [
            '<div class="map__balloon">',
            '<img class="map__burger-img" src="/local/img/hotel_poster.png" alt=""/>',
            'Самые удобные отели. Заходите по адресу: наб. реки Фонтанки, д. 56',
            '</div>'
        ]
    },
    {
        dataSlide: ['ALL','SHOPS'],
        coordinates: [59.95,30.24],
        hintContent: '<div class="map__hint">наб. реки Фонтанки, д. 56</div>',
        balloonContent: [
            '<div class="map__balloon">',
            '<img class="map__burger-img" src="/local/img/hotel_poster.png" alt=""/>',
            'Самые удобные отели. Заходите по адресу: наб. реки Фонтанки, д. 56',
            '</div>'
        ]
    },
    {
        dataSlide: ['ALL','ENTERTAINMENT'],
        coordinates: [59.94,30.27],
        hintContent: '<div class="map__hint">наб. реки Фонтанки, д. 56</div>',
        balloonContent: [
            '<div class="map__balloon">',
            '<img class="map__burger-img" src="/local/img/hotel_poster.png" alt=""/>',
            'Самые удобные отели. Заходите по адресу: наб. реки Фонтанки, д. 56',
            '</div>'
        ]
    },
    {
        dataSlide: ['ALL','RESTAURANTS'],
        coordinates: [59.99,30.44],
        hintContent: '<div class="map__hint">наб. реки Фонтанки, д. 56</div>',
        balloonContent: 
            '<div class="map__balloon">'+
            '<img class="map__balloon-img" src="/local/img/hotel_poster.png" alt=""/>'+
            'Самые удобные отели. Заходите по адресу: наб. реки Фонтанки, д. 56'+
            '</div>'
        
    }
]

function init() {
    var map = new ymaps.Map('map', {
        center: [59.94, 30.32],
        zoom: 12,
        controls: ['zoomControl'],
        behaviors: ['drag']
    });
    function mapCreateMarkers(coordinates, hintContent, balloonContent){
       return new ymaps.Placemark(coordinates, { hintContent, balloonContent },
            {
                iconLayout: 'default#image',
                iconImageHref: '/local/img/location.png',
                iconImageSize: [48, 48],
                iconImageOffset: [-23, -57],
            });
    }
    let clearAll = () => {
        map.geoObjects.removeAll();
    }
    let addMarkers = (markers) => {
        map.geoObjects.removeAll();
        map.geoObjects.add(clusterer);
        clusterer.add(markers);
    }
    let geoObjects = placemarks.map((placemark)=>{ 
        let {coordinates, hintContent, balloonContent} = placemark
        return mapCreateMarkers(coordinates, hintContent, balloonContent)
        
    })
    console.log(geoObjects)
    var clusterer = new ymaps.Clusterer({
        clusterIcons: [
            {
                href: 'img/burger.png',
                size: [100, 100],
                offset: [-50, -50]
            }
        ],
        clusterIconContentLayout: null
    });

    addMarkers(geoObjects)
    var swapButtons = document.querySelectorAll('.map__button__swap')
    swapButtons.forEach(function(item) {
        item.addEventListener('click', (e) => {
            var marButtonActive = document.querySelector('.map__button__swap.active')
            marButtonActive.classList.remove('active')
            item.classList.add('active')
            var data = e.target.dataset.slide
            let geoObjectsFilter = placemarks.filter((placemark) => placemark.dataSlide.includes(data))
            let geoObjects1 = geoObjectsFilter.map((placemark)=>{ 
                let {coordinates, hintContent, balloonContent} = placemark
                return mapCreateMarkers(coordinates, hintContent, balloonContent)
                
            })
            addMarkers(geoObjects1)
        })
    })
}
.map
    background-color: $main-color
    color: $tertiary-color
    font-weight: 400
    width: 100%
    height: 100%
    &__address
        font-family: San Francisco Pro Display
        font-size: 14px
    &__description
        display: flex
        justify-content: space-between
        margin-bottom: 70px
    &__title
        color: #fff
        font-weight: 300
        width: 100%
    &__wrap__text
        display: flex
        justify-content: space-between
    &__text
        width: 45%
    &__maps
        height: 100%
        margin-bottom: 30px 
    &__map
        height: 500px
    &__buttons
        display: flex
        justify-content: space-between
        margin-bottom: 30px 
    &__button__swap
        font-weight: 500
        cursor: pointer
        color: $tertiary-color
        transition: 0.4s
        border: 1px solid transparent
        padding-bottom: 6px
        &.active
            color: #fff
            border-bottom: 1px solid #fff
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
     <section class="map main__padding">
        <div class="container">
            <div class="map__address">
                St. Salova, 61.
            </div>
            <div class="map__description">
                <h2 class="map__title title">
                    SPB, Frunzensky District.
                </h2>
                <div class="map__wrap__text">
                    <div class="map__text text">
                        Saint-Petesburg, World Trade Center, theaters, museums, best restaurants — center of SPB — center attraction of success, inspiration & strength.
                    </div>
                    <div class="map__text text">Perfect location in Tihov Lane provides a sense of clubbing and privacy the owners of the Valo 
                        Hotel City Club.
                    </div>
                </div>    
            </div>
            <div class="map__maps">
                <div id="map" class="map__map"></div>
            </div>
            .map
            <div class="map__buttons">
                <div class="map__button__swap js-slide-map-button active" data-slide = 'ALL'>ALL</div>
                <div class="map__button__swap js-slide-map-button" data-slide = 'RESTAURANTS'>RESTAURANTS</div>
                <div class="map__button__swap js-slide-map-button" data-slide ='ENTERTAINMENT'>ENTERTAINMENT</div>
                <div class="map__button__swap js-slide-map-button" data-slide ='SHOPS'>SHOPS</div>
                <div class="map__button__swap js-slide-map-button" data-slide ='SPORT'>SPORT</div>
                <div class="map__button__swap js-slide-map-button" data-slide ='EDUCATION'>EDUCATION</div>
                <div class="map__button__swap js-slide-map-button" data-slide ='PARKS'>PARKS</div>
            </div>
        </div>
    </section>
</body>
</html>
dataSlide: ['ALL','PARKS'], coordinates: [59.97,30.31], hintContent: '<div class="map__hint">ул. Литераторов, д. 19</div>', balloonContent: [ '<div class="map__balloon">', '<img class="map__burger-img" src="/local/img/hotel_poster.png" alt=""/>', 'Самые удобные отели. Заходите по адресу: ул. Литераторов, д. 19', '</div>' ] }, { dataSlide: ['ALL','EDUCATION'], coordinates: [59.94,30.25], hintContent: '<div class="map__hint">Малый проспект В О, д 64</div>', balloonContent: [ '<div class="map__balloon">', '<img class="map__burger-img" src="/local/img/hotel_poster.png" alt=""/>', 'Самые удобные отели. Заходите по адресу: Малый проспект В О, д 64', '</div>' ] }, { dataSlide: ['ALL','SPORT'], coordinates: [59.93,30.34], hintContent: '<div class="map__hint">наб. реки Фонтанки, д. 56</div>', balloonContent: [ '<div class="map__balloon">', '<img class="map__burger-img" src="/local/img/hotel_poster.png" alt=""/>', 'Самые удобные отели. Заходите по адресу: наб. реки Фонтанки, д. 56', '</div>' ] }, { dataSlide: ['ALL','SHOPS'], coordinates: [59.95,30.24], hintContent: '<div class="map__hint">наб. реки Фонтанки, д. 56</div>', balloonContent: [ '<div class="map__balloon">', '<img class="map__burger-img" src="/local/img/hotel_poster.png" alt=""/>', 'Самые удобные отели. Заходите по адресу: наб. реки Фонтанки, д. 56', '</div>' ] }, { dataSlide: ['ALL','ENTERTAINMENT'], coordinates: [59.94,30.27], hintContent: '<div class="map__hint">наб. реки Фонтанки, д. 56</div>', balloonContent: [ '<div class="map__balloon">', '<img class="map__burger-img" src="/local/img/hotel_poster.png" alt=""/>', 'Самые удобные отели. Заходите по адресу: наб. реки Фонтанки, д. 56', '</div>' ] }, { dataSlide: ['ALL','RESTAURANTS'], coordinates: [59.99,30.44], hintContent: '<div class="map__hint">наб. реки Фонтанки, д. 56</div>', balloonContent: '<div class="map__balloon">'+ '<img class="map__balloon-img" src="/local/img/hotel_poster.png" alt=""/>'+ 'Самые удобные отели. Заходите по адресу: наб. реки Фонтанки, д. 56'+ '</div>' } ] function init() { var map = new ymaps.Map('map', { center: [59.94, 30.32], zoom: 12, controls: ['zoomControl'], behaviors: ['drag'] }); function mapCreateMarkers(coordinates, hintContent, balloonContent){ return new ymaps.Placemark(coordinates, { hintContent, balloonContent }, { iconLayout: 'default#image', iconImageHref: '/local/img/location.png', iconImageSize: [48, 48], iconImageOffset: [-23, -57], }); } let clearAll = () => { map.geoObjects.removeAll(); } let addMarkers = (markers) => { map.geoObjects.removeAll(); map.geoObjects.add(clusterer); clusterer.add(markers); } let geoObjects = placemarks.map((placemark)=>{ let {coordinates, hintContent, balloonContent} = placemark return mapCreateMarkers(coordinates, hintContent, balloonContent) }) console.log(geoObjects) var clusterer = new ymaps.Clusterer({ clusterIcons: [ { href: 'img/burger.png', size: [100, 100], offset: [-50, -50] } ], clusterIconContentLayout: null }); addMarkers(geoObjects) var swapButtons = document.querySelectorAll('.map__button__swap') swapButtons.forEach(function(item) { item.addEventListener('click', (e) => { var marButtonActive = document.querySelector('.map__button__swap.active') marButtonActive.classList.remove('active') item.classList.add('active') var data = e.target.dataset.slide let geoObjectsFilter = placemarks.filter((placemark) => placemark.dataSlide.includes(data)) let geoObjects1 = geoObjectsFilter.map((placemark)=>{ let {coordinates, hintContent, balloonContent} = placemark return mapCreateMarkers(coordinates, hintContent, balloonContent) }) addMarkers(geoObjects1) }) }) }
2
  • А сможете собрать минимальный рабочий пример на jsbin.com или в любой другой песочнице? Чтобы "руками потрогать" скрипт, а не только перебирать глазами без связи с html-кодом.
    – YaCor'
    23 мар 2022 в 19:29
  • я добавил в песочницу все что нужно как я думаю но теперь точки не добавляются буду благодарен если укажите на ошибку jsbin.com/pawucuxemi/1/edit?html,js,output 24 мар 2022 в 7:28

1 ответ 1

1

нашел ошибку clusterer инициализировался 1 раз и после нажатия на кнопки не менялся что вызывало баг поместил его addMarkers перед удалением точек и добавлением новых

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.