-->

Google Maps Api v3 - Legend Duplication

2019-09-20 15:23发布

问题:

I have embed a google maps in Klipfolio, however the legend's items are duplicating themselves from time to time when you refresh the page. screenshot of the legend duplicated and codes

the body includes the 2 tags for the map canvas and the legend

    <div id="map_canvas"></div>
    <div id="legend"></div> 

and this is how i populate the legend as per google maps api documentation in the script.

// setting the legend
var iconBase = 'https://i.imgur.com/';
var icons = {
    mine_site: {
       name: 'Mine Site',
       icon: iconBase + 'JCSVR5C.png'
    },
    mine_depot: {
       name: 'Mine Depot',
       icon: iconBase + 'XkWP909.png'
    },
    warehouse: {
       name: 'Exporter Warehouse',
       icon: iconBase + 'W7u6wR3.png'
   }
};

var legend = document.getElementById('legend');
for (var key in icons) {
   var type = icons[key];
   var name = type.name;
   var icon = type.icon;
   var div = document.createElement('div');
   div.innerHTML = '<img src="' + icon + '"> ' + name;
   legend.appendChild(div);
}

map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(legend);

I even used a counter to append to the legend only for a number of times equal to the length of the legend items, but to no avail.

I am wondering if it might not be due to some compatibility with klipfolio. Has anyone met this issue? Is there something I am doing wrong? Or how can I be sure that it is because of the compatibility issue? Meanwhile, I do not get any warning or errors when those duplicates occur.

回答1:

For whoever else that will meet this error, I solved this by a work-around. Just remove values that repeat themselves by using their css class. An example can be found here.

<html>
<div class = "test">Window</div>
<div class = "test">Table</div>
<div class = "test">Chaise</div>
<div class = "test">Window</div>
<div class = "test">Chaise</div>
</html>
<script>
$('.test').each(function () {
  $('.test:contains("' + $(this).text() + '"):gt(0)').remove();  
});
</script>

Refer to the previous comments I made about js making duplicates when it is being loaded from the body.