1

所以我的地图上有两层多边形。这些多边形取决于缩放级别。

当我放大时,我想隐藏第一级多边形(或删除它们的侦听器并使它们透明),当我缩小时,我需要隐藏第二级多边形并显示第一级多边形。

我目前的策略是让多边形最初是透明的,听者会在必要时让它们变得不透明。为了实现我的多边形切换,我会在缩放变化时添加和删除侦听器。

所以我有一个 level1 多边形数组和一个 level2 多边形数组,但我似乎无法切换它们。

这怎么行不通?addListener 不应该与 removeListener 完全相反吗?

function zoomedout(map) {

$.each(level2Listeners, function(k,v) {
   google.maps.event.removeListener(v);
});



$.each(level1Listeners, function(k,v) {
   google.maps.event.addListener(v);
});

}

还有其他更合理的策略来实现切换吗?

4

2 回答 2

1

You've asked for another reasonable approach, I had a similar task some month's ago (toggle about 5000 overlays depending on the zoom) and came across another solution.

A Polygon is a MVCObject, you can bind a property of a MVCObject to the property of another MVCObject.

I've created new properties for the Map-Instance(which also is an MVCObject), and updated these properties on the zoom_changed-event.

The workflow:

  1. set the properties on zoom_changed
    google.maps.event.addListener(map,'zoom_changed',function(){
    
       var z=this.getZoom();
    
        //set map.prop1 to Map-instance when zoom<=5,otherwise to null
       var p1=(z<=5)?this:null;if(this.get('prop1')!==p1){this.set('prop1',p1);}
    
        //set map.prop2 to Map-instance when zoom>5,otherwise to null
       var p2=(z>5)?this:null;if(this.get('prop2')!==p2){this.set('prop2',p2);}
    });
  2. bind the map-property of the overlay to the desired property:
    //this polygon will only be displayed at a zoom up to 5
    somePolygon.bindTo('map',map,'prop1');
  3. trigger the zoom_changed-event to initialize the properties:
    google.maps.event.trigger(map, 'zoom_changed');

A simple demo with 4 circles: http://jsfiddle.net/doktormolle/FPvLx/

于 2013-07-03T00:51:15.090 回答
1

实现图层的最简单方法是遍历 map zoom_changed 侦听器中的数组,适当地设置多边形的“map”属性。下面的代码假定您的 google.maps.Map 对象是“地图”和全局的(或至少在侦听器范围内可用)。

google.maps.event.addListener(map, "zoom_changed", function() {
  if (map.getZoom() > zoomThreshold) {
      for (var i = 0; i<level1polys.length; i++) {
         // hide the level1 polygons
         if (level1polys[i].getMap() != null) level1polys[i].setMap(null);
      }
      for (var i=0; i<level2polys.length; i++) {
         // show the level2 polygons
         if (level2polys[i].getMap() == null) level2polys[i].setMap(map);
      }
  else {
      for (var i = 0; i<level1polys.length; i++) {
         // show the level1 polygons
         if (level1polys[i].getMap() == null) level1polys[i].setMap(map);
      }
      for (var i=0; i<level2polys.length; i++) {
         // hide the level2 polygons
         if (level2polys[i].getMap() != null) level2polys[i].setMap(null);
      }
  }
});

您可能想要添加状态,这样您就不必为每次缩放级别的更改处理所有多边形,只有在缩放更改超过阈值时才这样做。

于 2013-07-02T12:57:25.237 回答