简体   繁体   English

使用回调功能在Google地图上放置多个标记

[英]Place multiple markers on google map with callback function

I want to implement a functionality on Gmap API, that if the zoom is more than 17, show all the markers(otherwise, just hide them). 我想在Gmap API上实现一项功能,即如果缩放比例大于17,则显示所有标记(否则将其隐藏)。 However, when I write code like the following, it just does not work. 但是,当我编写如下代码时,它根本无法工作。

PS: the code might not be exactly correct in syntax and arrangement, but it express what I mean PS:该代码的语法和排列方式可能并不完全正确,但它表达了我的意思

// @latlong is an array of tuple (latitude , longtitude)
// @myMap is the google map object passed to the function
function placeMarker( myMap , latlon)
{
  for(var i = 0 ; i < latlon.length ; i ++)
  {
     myMarker = new google.maps.Marker( {
        position: new google.maps.LatLng(latlon[i][0], latlon[i][1])
     });

     google.maps.event.addListener(myMap, 'zoom_changed', function() {
      zoomLevel = myMap.getZoom()       
      if(zoomLevel >= 17)
      {
        myMarker.setMap(myMap)
      }
      else
      {
        myMarker.setMap(null)
      }
  });


}
}

And I just change my code to: 我只是将代码更改为:

function placeMarker( myMap , latlon)
{
  for(var i = 0 ; i < latlon.length ; i ++)
  {
     myMarker = new google.maps.Marker( {
        position: new google.maps.LatLng(latlon[i][0], latlon[i][1])
     });

     (function(myMarker_copy){
         google.maps.event.addListener(myMap, 'zoom_changed', function() {
          zoomLevel = myMap.getZoom()       
          if(zoomLevel >= 17)
          {
            myMarker_copy.setMap(myMap)
          }
          else
          {
            myMarker_copy.setMap(null)
          }
      });
      }(myMarker));


}
}

And the second version works. 第二个版本有效。 I know how to make it work, however, I really do not know why it work and why the other does not. 我知道如何使它起作用,但是,我真的不知道为什么它起作用,而另一个为什么不起作用。 Maybe this has something to do with the function closure or parameter passing principle of JS(I have checked a lot references, but some of them just hold different ideas). 也许这与JS的函数闭包或参数传递原理有关(我检查了很多引用,但是其中一些引用持有不同的想法)。 Could anybody give me a help? 有人可以帮我吗?

really appreciate it. 非常感谢。

The first example which doesn't work: There is one global variable myMarker and many event listeners which at the end all operate on one marker and that is the one created the last in the loop. 第一个无效的示例:有一个全局变量myMarker和许多事件侦听器,它们最后都对一个标记进行操作,而这是在循环中最后创建一个标记。

The second example which does work: because of closure each event listener receive its own local copy of marker variable. 第二个有效的示例:由于关闭,每个事件侦听器都收到自己的标记变量本地副本。 So, when event listener is called it has correct marker value. 因此,在调用事件侦听器时,它具有正确的标记值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM