Google张地图重绘后如何清除形状?

How to clear shapes after the map is redrawn in Google maps?

我想在使用 JSON 字符串重新绘制后清除 google 地图覆盖形状,但在使用 Json 字符串重新绘制地图后它不会清除。

  1. 当我绘制形状并单击 save raw(IO.IN(shapes,false)) 之后,如果我单击清除按钮,它会清除所有形状。
  2. 保存形状后,如果我单击恢复(IO.OUT(array,map)) 按钮,所有形状都将恢复,如果我想立即清除所有形状并再次单击清除按钮它不明确的形状为什么? 或者换句话说,我想在恢复形状后清除地图,但为什么不清除地图? 谁能帮忙。提前致谢。

我的Google地图代码给出如下:

function initialize()
{   
    var goo             = google.maps,
        map_in          = new goo.Map(document.getElementById('map_in'), 
                                      { zoom: 12, 
                                        center: new goo.LatLng(32.344, 51.048)
                                      }),

        shapes          = [],
        selected_shape  = null,
        drawman         = new goo.drawing.DrawingManager({map:map_in}),
        byId            = function(s){return document.getElementById(s)},
        clearSelection  = function(){
                            if(selected_shape){
                              selected_shape.set((selected_shape.type
                                                  ===
                                                  google.maps.drawing.OverlayType.MARKER
                                                 )?'draggable':'editable',false);
                              selected_shape = null;
                            }
                          },
        setSelection    = function(shape){
                            clearSelection();
                            selected_shape=shape;

                              selected_shape.set((selected_shape.type
                                                  ===
                                                  google.maps.drawing.OverlayType.MARKER
                                                 )?'draggable':'editable',true);

                          },
        clearShapes     = function(){
                            for(var i=0;i<shapes.length;++i){
                              shapes[i].setMap(null);
                            }
                            shapes=[];
                          };

    goo.event.addListener(drawman, 'overlaycomplete', function(e) {
        var shape   = e.overlay;
        shape.type  = e.type;
        goo.event.addListener(shape, 'click', function() {
          setSelection(this);
        });
        setSelection(shape);
        shapes.push(shape);
      });

    goo.event.addListener(map_in, 'click',clearSelection);
    goo.event.addDomListener(byId('clear_shapes'), 'click', clearShapes);
     goo.event.addDomListener(byId('clear'), 'click', function() {
                   // clearShapes();
                    alert("clear or not");

                    this.shapes = IO.OUT(JSON.parse(byId('data').value), map_in);
if(this.shapes){
        for(var i=0;i<this.shapes.length;++i){
              this.shapes[i].setMap(null);
        }
}

                });
    goo.event.addDomListener(byId('save_encoded'), 'click', function(){
      var data=IO.IN(shapes,true);byId('data').value=JSON.stringify(data);});
    goo.event.addDomListener(byId('save_raw'), 'click', function(){
      var data=IO.IN(shapes,false);byId('data').value=JSON.stringify(data);});
    goo.event.addDomListener(byId('restore'), 'click', function(){
      if(this.shapes){
        for(var i=0;i<this.shapes.length;++i){
              this.shapes[i].setMap(null);
        }
      }
      this.shapes=IO.OUT(JSON.parse(byId('data').value),map_in);
    });

}


var IO={
  //returns array with storable google.maps.Overlay-definitions
  IN:function(arr,//array with google.maps.Overlays
              encoded//boolean indicating whether pathes should be stored encoded
              ){
      var shapes     = [],
          goo=google.maps,
          shape,tmp;

      for(var i = 0; i < arr.length; i++)
      {   
        shape=arr[i];
        tmp={type:this.t_(shape.type),id:shape.id||null};


        switch(tmp.type){
           case 'CIRCLE':
              tmp.radius=shape.getRadius();
              tmp.geometry=this.p_(shape.getCenter());
            break;
           case 'MARKER': 
              tmp.geometry=this.p_(shape.getPosition());   
            break;  
           case 'RECTANGLE': 
              tmp.geometry=this.b_(shape.getBounds()); 
             break;   
           case 'POLYLINE': 
              tmp.geometry=this.l_(shape.getPath(),encoded);
             break;   
           case 'POLYGON': 
              tmp.geometry=this.m_(shape.getPaths(),encoded);

             break;   
       }
       shapes.push(tmp);
    }

    return shapes;
  },
  //returns array with google.maps.Overlays
  OUT:function(arr,//array containg the stored shape-definitions
               map//map where to draw the shapes
               ){
      var shapes     = [],
          goo=google.maps,
          map=map||null,
          shape,tmp;

      for(var i = 0; i < arr.length; i++)
      {   
        shape=arr[i];       

        switch(shape.type){
           case 'CIRCLE':
              tmp=new goo.Circle({radius:Number(shape.radius),center:this.pp_.apply(this,shape.geometry)});
            break;
           case 'MARKER': 
              tmp=new goo.Marker({position:this.pp_.apply(this,shape.geometry)});
            break;  
           case 'RECTANGLE': 
              tmp=new goo.Rectangle({bounds:this.bb_.apply(this,shape.geometry)});
             break;   
           case 'POLYLINE': 
              tmp=new goo.Polyline({path:this.ll_(shape.geometry)});
             break;   
           case 'POLYGON': 
              tmp=new goo.Polygon({paths:this.mm_(shape.geometry)});

             break;   
       }
       tmp.setValues({map:map,id:shape.id})
       shapes.push(tmp);
    }
    return shapes;
  },
  l_:function(path,e){
    path=(path.getArray)?path.getArray():path;
    if(e){
      return google.maps.geometry.encoding.encodePath(path);
    }else{
      var r=[];
      for(var i=0;i<path.length;++i){
        r.push(this.p_(path[i]));
      }
      return r;
    }
  },
  ll_:function(path){
    if(typeof path==='string'){
      return google.maps.geometry.encoding.decodePath(path);
    }
    else{
      var r=[];
      for(var i=0;i<path.length;++i){
        r.push(this.pp_.apply(this,path[i]));
      }
      return r;
    }
  },

  m_:function(paths,e){
    var r=[];
    paths=(paths.getArray)?paths.getArray():paths;
    for(var i=0;i<paths.length;++i){
        r.push(this.l_(paths[i],e));
      }
     return r;
  },
  mm_:function(paths){
    var r=[];
    for(var i=0;i<paths.length;++i){
        r.push(this.ll_.call(this,paths[i]));

      }
     return r;
  },
  p_:function(latLng){
    return([latLng.lat(),latLng.lng()]);
  },
  pp_:function(lat,lng){
    return new google.maps.LatLng(lat,lng);
  },
  b_:function(bounds){
    return([this.p_(bounds.getSouthWest()),
            this.p_(bounds.getNorthEast())]);
  },
  bb_:function(sw,ne){
    return new google.maps.LatLngBounds(this.pp_.apply(this,sw),
                                        this.pp_.apply(this,ne));
  },
  t_:function(s){
    var t=['CIRCLE','MARKER','RECTANGLE','POLYLINE','POLYGON'];
    for(var i=0;i<t.length;++i){
       if(s===google.maps.drawing.OverlayType[t[i]]){
         return t[i];
       }
    }
  }

}
google.maps.event.addDomListener(window, 'load', initialize);

HTML给出代码如下:

<div class="map" id="map_in"></div>
<div style="text-align:center">
   <input id="clear_shapes" value="clear shapes"    type="button"  />
  <input id="save_encoded" value="save encoded(IO.IN(shapes,true))"    type="button" />
  <input id="save_raw"     value="save raw(IO.IN(shapes,false))"        type="button" />
  <input id="data"         value=""                style="width:100%" readonly/>
  <input id="restore"      value="restore(IO.OUT(array,map))"         type="button" />
                      <input  id="clear"     name="clear"  value="clear" type="button" />

</div>

在哪里以及如何清除在地图上创建的形状。所有形状都保存在 var all_shapes = [];大批。我要使用 JSP.

这应该从地图中删除 all_shapes 数组中的所有形状:

for (var i=0; i<all_shapes.length; i++) {
   all_shapes.setMap(null);
}

original implementation 使用了 2 个不同的映射,您实现中的问题位于恢复函数中:

goo.event.addDomListener(byId('restore'), 'click', function(){
  if(this.shapes){
    for(var i=0;i<this.shapes.length;++i){
          this.shapes[i].setMap(null);
    }
  }
  this.shapes=IO.OUT(JSON.parse(byId('data').value),map_in);
});
这里的

this指的是被点击的按钮,所以this.shapes不会影响initialize中声明的shapes数组,但是必须修改这个数组。

改用这个:

goo.event.addDomListener(byId('restore'), 'click', function(){
  while(shapes.length){
    //hides the shape and removes it from the shapes-array
    shapes.pop.setMap(null);
  }
  shapes=IO.OUT(JSON.parse(byId('data').value),map_in);
});