-1

我目前有一个gmarker对象数组,并且对于相同的位置(经度和纬度)有重复的gmarker,但具有不同的信息窗口。这很好,但我想使用标记集群并只代表这些位置一次。循环访问gmarker对象数组并仅保留唯一位置?

有没有办法循环访问数组,并可能创建另一个只包含唯一位置的数组? (纬度,经度)

我是想这样的事情:

  var size = 0; 
      var uniqueCustomers = [] 
      for (var i = 0; i < gmarkers.length; i++) { 
       if (uniqueCustomers.indexOf(gmarkers[i]) < 0) { 
        uniqueCustomers[size] = gmarkers[i]; 
        size = size + 1; 
       } 
      } 

回答

0

有多种方式做到这一点,但其中一人是刚刚创建一个基于每个标记的经纬度信息的“钥匙”,检查你的新对象(不是数组)uniqueCustomers是否已经设置了密钥,如果不是,则添加标记到uniqueCustomers。

var gmarkers = [] ; 
 

 
var coords = [ 
 
    {lat : 42.1, lng:3.4}, 
 
    {lat : 42.2, lng:3.4}, 
 
    {lat : 42.3, lng:3.4}, 
 
    {lat : 42.4, lng:3.4}, 
 
    {lat : 42.1, lng:3.4}, 
 
    {lat : 42.2, lng:3.4} 
 
] ; 
 

 
for (var i in coords) 
 
{ 
 
    gmarkers.push(new google.maps.Marker({ 
 
     position:coords[i] 
 
    })) ; 
 
} 
 

 
var size = 0; 
 
var uniqueCustomers = {} ; 
 

 
// Loop on the 6 markers 
 
for (var i = 0; i < gmarkers.length; i++) { 
 
    // Create a key to identify tje position of the marker 
 
    var key = gmarkers[i].position.lat() + ',' + gmarkers[i].position.lng() ; 
 
    
 
    // If this key is not already on uniqueCustomers, then we add the marker with this key to uniqueCustomers, so at the next loops if it exists we don't add it another time 
 
    if (typeof uniqueCustomers[key] == 'undefined') 
 
    uniqueCustomers[key] = gmarkers[i] ; 
 
} 
 

 
console.log('gmarkers.length',gmarkers.length) ; // 6 
 
console.log('uniqueCustomers.length',Object.keys(uniqueCustomers).length) ; // 4 
 
console.log('uniqueCustomers',Object.keys(uniqueCustomers)) ; // Display only uniques
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="https://maps.googleapis.com/maps/api/js"></script>

+0

非常感谢!这工作完美! – Olis

+0

不客气;)请考虑检查这个答案,因为有同样问题的人很容易看到这就是答案。 –

+0

在那里,再次感谢:) – Olis