【问题标题】:How to clear shapes after the map is redrawn in Google maps?谷歌地图重绘地图后如何清除形状?
【发布时间】:2015-03-24 13:56:32
【问题描述】:

我想在使用 JSON 字符串重绘后清除谷歌地图叠加形状,但在使用 Json 字符串重绘地图后它不会清除。

  1. 当我绘制形状并单击 save raw(IO.IN(shapes,false)) 之后,如果我单击清除按钮,它会清除所有形状。
  2. 如果我点击恢复(IO.OUT(数组,地图))按钮保存形状后,所有形状都会恢复,如果我想在那一刻清除所有形状并再次单击清除按钮,它不会清除形状为什么?? 或者换句话说,我想在恢复形状后清除地图,但它不清除地图,为什么? 任何人都可以帮忙。提前致谢。

我的谷歌地图代码如下:

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。

【问题讨论】:

  • 发布的代码有 javascript 错误。或者,也许我只是不知道您希望如何使用它...
  • 什么错误??你能告诉我吗?
  • 我想在绘制形状并按下清除按钮时使用它,它会清除所有形状,当我按下恢复按钮时,所有形状都会恢复并再次按下清除按钮。不清楚为什么??
  • 我也更新了我的问题。请帮助我..如果你不清楚,请告诉我,我会尽可能地解决它。
  • 重新调整形状后我想清除地图但它没有清除

标签: javascript json google-maps-api-3 overlay shape


【解决方案1】:

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);
});

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • all_shapes[i].setMap(null); ?
    • 我已经这样做了,但它不起作用,请参阅我的清晰按钮代码: if(this.shapes){ for(var i=0;i
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-03
    • 2023-03-22
    • 1970-01-01
    • 2016-02-21
    • 2012-12-10
    • 2016-10-18
    • 1970-01-01
    相关资源
    最近更新 更多