js Google Maps Api маркеры

У меня готовый код, которые показывает маркеры на карте. Маркеры меняются по средствам вкладок, при выборе определенной вкладки(tab), маркеры на карте меняются. Но есть ошибка?! У меня маркеры 2х цветов для каждой вкладки. (синий и желтый маркер)

  • При нажатие на желтый маркер, он становится оранжевый как активный. Но почему то меняются цвета всех маркеров на желтый цвет(даже если эти маркеры другой вкладки). Тоже самое происходит с синим маркером, при нажатие на выбранный синий маркер - он меняется на зеленый, но почему-то все меняются на синий, хотя первоначально желтый доджен оставаться желтым, так как он из другой вкладки.

Надеюсь не запутано, и сможет кто оптимизировать мое творение, спасибо

#map {
    width: 100%;
    height: 400px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"></script>


<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>


<ul class="nav">
    <li class="nav-item">
      <a class="nav-link" data-map-trigger="1" data-bs-toggle="tab" data-bs-target="#tab-01" role="tab" >mytitle</a>
    </li>
    <li class="nav-item">
      <a class="nav-link" data-map-trigger="2" data-bs-toggle="tab" data-bs-target="#tab-02" role="tab" >mytitle2</a>
    </li>
</ul>

<div class="container-fluid px-0 block-maps">
    <div id="map"></div>
</div>
<!-- BLOCK 8 MAPS END -->




<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBHJxzPHD_egYnhxntqcvfem35YRjruzAg&callback=initialize"></script>
<script type="text/javascript">
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 4,
        styles: [],
        center: new google.maps.LatLng(46.623082, 23.830545),
        disableDefaultUI: true,
    });
    var markers = [];
    var map;
    var infowindow = new google.maps.InfoWindow();
    var marker, i;
</script>

<div class="tab-content">

    <!--Для показа выбранных товаров-->
    <script type="text/javascript">
        var collectionMap = {}

        $(document).on('click', '[data-map-trigger]', function(event) {
            event.preventDefault();
            window.location.hash = $(this).attr('href')

            var collectionId = $(this).data('map-trigger');
            loadMarker(collectionId)
        });

        function loadMarker(collectionId) {
            _.forEach(markers, (item, i) => {
                item.setMap(null);
            });

            renderMarker(collectionMap[collectionId])
        }

        $(function() {
            var hash = window.location.hash;
            hash && $('ul.nav a[href="' + hash + '"]').tab('show');

            if (hash) {
                var $activeMap = $('[data-map-trigger][href="' + hash + '"]');
                if ($activeMap.lenght) {
                    var collectionId = $activeMap.data('map-trigger');
                    loadMarker(collectionId)
                }
            }

            $('.nav-tabs a').click(function(e) {
                $(this).tab('show');
            });
        });
    </script>

    <div class="tab-pane" id="tab-01">
        <script type="text/javascript">
            collectionMap[1] = [
                    {
                      id: "214451020",
                      title: "mytitle",
                      coord1: "41.877274",
                      coord2: "12.454967"
                    },
                    {
                      id: "123",
                      title: "abc",
                      coord1: "31.877274",
                      coord2: "22.454967"
                    }
            ];
        </script>

        <!-- 1 -->
        <script type="text/javascript">

            renderMarker(collectionMap[1])

            function renderMarker(locationProducts) {
                _.forEach(locationProducts, (currentProduct, i) => {
                    marker = new google.maps.Marker({
                        position: new google.maps.LatLng(currentProduct.coord1, currentProduct.coord2),
                        map: map,
                        icon: 'http://first.synapsepro.site/point-blue.svg',
                        animation: google.maps.Animation.DROP,
                    });

                    google.maps.event.addListener(marker, 'click', (function(marker, i) {
                        return function() {
                            infowindow.setContent(currentProduct.title, [currentProduct.coord1, currentProduct.coord2]);
                            infowindow.open(map, marker);
                            for (var j = 0; j < markers.length; j++) {
                                markers[j].setIcon("http://first.synapsepro.site/point-blue.svg");
                            }
                            marker.setIcon("http://first.synapsepro.site/point-blue-active.svg");
                        };

                    })(marker, i));
                    markers.push(marker);
                });

            }
        </script>
    </div>


    <div class="tab-pane" id="tab-02">
        <script type="text/javascript">
            collectionMap[2] = [
                    {
                      id: "qwe3",
                      title: "ABCDEF",
                      coord1: "41.877274",
                      coord2: "32.454967"
                    }
            ];
        </script>

        <!-- 3 -->
        <script type="text/javascript">

            renderMarker(collectionMap[2])

            function renderMarker(locationProducts) {
                _.forEach(locationProducts, (currentProduct, i) => {
                    marker = new google.maps.Marker({
                        position: new google.maps.LatLng(currentProduct.coord1, currentProduct.coord2),
                        map: map,
                        icon: 'http://first.synapsepro.site/point-yellow.svg',
                        animation: google.maps.Animation.DROP,
                    });

                    google.maps.event.addListener(marker, 'click', (function(marker, i) {
                        return function() {
                            infowindow.setContent(currentProduct.title);
                            infowindow.open(map, marker);
                            for (var j = 0; j < markers.length; j++) {
                                markers[j].setIcon("http://first.synapsepro.site/point-yellow.svg");
                            }
                            marker.setIcon("http://first.synapsepro.site/point-yellow-active.svg");
                        };

                    })(marker, i));
                    markers.push(marker);
                });

            }
        </script>
    </div>
</div>

Так же код в jsfiddle: https://jsfiddle.net/synapse3/02kq1w45/47/


Ответы (0 шт):