谷歌地图API v3如何获取所有形状的坐标 [英] google map API v3 how to get coordinates of all shapes

查看:103
本文介绍了谷歌地图API v3如何获取所有形状的坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个可以创建形状和删除形状的Google脚本,但没有太多有关保存形状的信息。



我查了一下互联网,知道我可以访问通过getlays()内的路径坐标overlaycomplete我也可以将坐标推入一个数组,收集所有的形状。但是,如果用户删除一个形状呢?或更新它?



我的问题是我不知道如何识别已删除的形状,以便相应地更新形状集合数组。

第二个问题是我不知道如何识别用户是否更新了形状和更新了哪个形状。因此无法更新形状集合数组。



我需要一个解决方案,点击保存按钮。我可以获取地图上存在的所有形状的坐标。所以我不必关心更新或删除的内容。我现在的代码如下:

 <!DOCTYPE html> 
< html>
< head>
< script src =http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing,geometry,places>< / script>
< style>
#map,html,body {
height:100%;
保证金:0;
padding:0;
}
#delete-button,#save-button {
margin-top:5px;
位置:绝对;
z-index:999;
右侧:6%;
top:3%;
}
#save-button {
right:1%;
}
< / style>
< / head>
< body>
< div id =map>< / div>
< button id =delete-buttonclass =btn>删除选择的形状< / button>
< button id =save-buttonclass =btnonclick =save();>全部保存< / button>

< script>
var drawingManager;
var selectedShape;
var shapeCollection = [];


function save(){
console.log(shapeCollection);


函数clearSelection(){
if(selectedShape){
selectedShape.setEditable(false);
selectedShape = null;
}
}
函数setSelection(shape){
clearSelection();
selectedShape = shape;
shape.setEditable(true);
}
函数deleteSelectedShape(){
if(selectedShape){
selectedShape.setMap(null);


函数initialize(){
var map = new google.maps.Map(document.getElementById('map'),{
zoom:10 ,
center:new google.maps.LatLng(22.344,114.048),
mapTypeId:google.maps.MapTypeId.ROADMAP,
});

var polyOptions = {
strokeWeight:3,
fillOpacity:0.2,
editable:true,
draggable:true
};
//创建附加到地图的绘图管理器,允许用户绘制
//标记,线条和形状。
drawingManager = new google.maps.drawing.DrawingManager({
drawingControl:true,
drawingControlOptions:{
drawingModes:[google.maps.drawing.OverlayType.POLYGON]
},
drawingMode:google.maps.drawing.OverlayType.POLYGON,
polygonOptions:polyOptions,
map:map
});

google.maps.event.addListener(drawingManager,'overlaycomplete',function(e){

drawingManager.setDrawingMode(null);

//添加一个事件侦听器,当用户
//将鼠标拖放到它上面时,选择新绘制的形状
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape,'click',function(){
setSelection(newShape);
});
setSelection(newShape);

});

// polygonPoints将是数组,并且该数组的索引将是订单
//在绘图模式更改时清除当前选择,或者当
//地图被点击。
google.maps.event.addListener(drawingManager,'drawingmode_changed',clearSelection);
google.maps.event.addListener(地图,'click',clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'),'click',deleteSelectedShape);

}

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

< / script>

< / body>
< / html>


解决方案

为形状创建一个唯一的属性将形状存储在一个对象中(使用ID作为键)。



当你想删除一个形状时,你可以使用 delete

您不必关心用户的更新,当您将形状(引用)存储到集合中,它们将自动更新。



演示:

  function initialize(){var map = new google.maps.Map(document.getElementById('map'),{zoom:10,center:new google.maps.LatLng(22.344,114.048),mapTypeId:google。 maps.MapTypeId.ROADMAP,noClear:true}); map.controls [google.maps.ControlPosition.RIGHT_BOTTOM] .push(document.getElementById('save-button')); map.controls [google.maps.ControlPosition.RIGHT_BOTTOM] .push(document.getElementById('delete-button')); var polyOptions = {strokeWeight:3,fillOpacity:0.2}; var shapes = {collection:{},selectedShape:null,add:function(e){var shape = e.overlay,that = this; shape.type = e.type; shape.id = new Date()。getTime()+'_'+ Math.floor(Math.random()* 1000); this.collection [shape.id] =形状; this.setSelection(形状); google.maps.event.addListener(shape,'click',function(){that.setSelection(this);}); },setSelection:function(shape){if(this.selectedShape!== shape){this.clearSelection(); this.selectedShape = shape; shape.set(可拖动,TRUE); shape.set(编辑,TRUE); }},deleteSelected:function(){if(this.selectedShape){var shape = this.selectedShape; this.clearSelection(); shape.setMap(NULL);删除this.collection [shape.id]; }},clearSelection:function(){if(this.selectedShape){this.selectedShape.set('draggable',false); this.selectedShape.set(编辑,假); this.selectedShape = NULL;保存:function(){var collection = [];}} for(var this.collection){var shape = this.collection [k],types = google.maps.drawing.OverlayType; switch(shape.type){case types.POLYGON:collection.push({type:shape.type,path:google.maps.geometry.encoding .encodePath(shape.getPath())});打破;默认值:alert('为'+ shape.type实现一个存储方法)}} //集合是结果console.log(collection); }}; var drawingManager = new google.maps.drawing.DrawingManager({drawingControl:true,drawingControlOptions:{drawingModes:[google.maps.drawing.OverlayType.POLYGON]},drawingMode:google.maps.drawing.OverlayType.POLYGON,polygonOptions:polyOptions ,map:map}); google.maps.event.addListener(drawingManager,'overlaycomplete',function(e){drawingManager.setDrawingMode(null); shapes.add(e);}); google.maps.event.addListener(drawingManager,'drawingmode_changed',function(){shapes.clearSelection();}); google.maps.event.addListener(map,'click',function(){shapes.clearSelection();}); google.maps.event.addDomListener(document.getElementById('delete-button'),'click',function(){shapes.deleteSelected();}); google.maps.event.addDomListener(document.getElementById('save-button'),'click',function(){shapes.save();}); }   

#map,html,body {height:100% ;余量:0;填充:0; }

< div id =map> < button id =delete-buttonclass =btn>删除选定的形状< / button> < button id =save-buttonclass =btn>全部保存< / button>< / div>< script src =http://maps.googleapis.com/maps/api/js?传感器=假安培;库=图中,几何形状,位置和安培; v = 3及回调=初始化>< /脚本>



演示包括加载 - 自动加载形状的方法:

 function initialize(){var map = new google.maps.Map(document.getElementById('map'),{zoom:9,center:new google.maps.LatLng(22.344, 114.048),mapTypeId:google.maps.MapTypeId.ROADMAP,noClear:true}); map.controls [google.maps.ControlPosition.RIGHT_BOTTOM] .push(document.getElementById('save-button')); map.controls [google.maps.ControlPosition.RIGHT_BOTTOM] .push(document.getElementById('delete-button')); var polyOptions = {strokeWeight:3,fillOpacity:0.2}; var shapes = {collection:{},selectedShape:null,add:function(e,s){var shape = e.overlay,that = this; shape.type = e.type; shape.id = new Date()。getTime()+'_'+ Math.floor(Math.random()* 1000); this.collection [shape.id] =形状;如果this.setSelection(形状)(S!); google.maps.event.addListener(shape,'click',function(){that.setSelection(this);}); },setSelection:function(shape){if(this.selectedShape!== shape){this.clearSelection(); this.selectedShape = shape; shape.set(可拖动,TRUE); shape.set(编辑,TRUE); }},deleteSelected:function(){if(this.selectedShape){var shape = this.selectedShape; this.clearSelection(); shape.setMap(NULL);删除this.collection [shape.id]; }},clearSelection:function(){if(this.selectedShape){this.selectedShape.set('draggable',false); this.selectedShape.set(编辑,假); this.selectedShape = NULL;保存:function(){var collection = [];}} for(var this.collection){var shape = this.collection [k],types = google.maps.drawing.OverlayType; switch(shape.type){case types.POLYGON:collection.push({type:shape.type,path:google.maps.geometry.encoding .encodePath(shape.getPath())});打破;默认:alert('为'+ shape.type实现存储方法)}} //集合是结果console.log(JSON.stringify(collection));返回集合; },load:function(arr){var types = google.maps.drawing.OverlayType; for(var i = 0; i< arr.length; ++ i){switch(arr [i] .type){case types.POLYGON:var shape = new google.maps.Polygon(polyOptions); shape.setOptions({map:map,path:google.maps.geometry.encoding .decodePath(arr [i] .path)}); shapes.add({type:types.POLYGON,overlay:shape},true)break;默认值:alert('实现'+ arr [i] .type的加载方法)}}}}; //最初加载一些形状shapes.load([{type:polygon,path:_} sgCamyuT〜ee @ eP | FkdEskn @ nr @ rdH`wM},{type:polygon , 路径: ?mnngCchxvTý{DylG {{d〜tFihCng_ @ v {öwiVymDdPzNblLah\\i} LksLngJ}]); var drawingManager = new google.maps.drawing.DrawingManager({drawingControl:true,drawingControlOptions:{drawingModes:[google.maps.drawing.OverlayType.POLYGON]},drawingMode:google.maps.drawing.OverlayType.POLYGON,polygonOptions:polyOptions ,map:map}); google.maps.event.addListener(drawingManager,'overlaycomplete',function(e){drawingManager.setDrawingMode(null); shapes.add(e);}); google.maps.event.addListener(drawingManager,'drawingmode_changed',function(){shapes.clearSelection();}); google.maps.event.addListener(map,'click',function(){shapes.clearSelection();}); google.maps.event.addDomListener(document.getElementById('delete-button'),'click',function(){shapes.deleteSelected();}); google.maps.event.addDomListener(document.getElementById('save-button'),'click',function(){shapes.save();}); }   

#map,html,body {height:100% ;余量:0;填充:0; }

< div id =map> < button id =delete-buttonclass =btn>删除选定的形状< / button> < button id =save-buttonclass =btn>全部保存< / button>< / div>< script src =http://maps.googleapis.com/maps/api/js?传感器=假安培;库=图中,几何形状,位置和安培; v = 3及回调=初始化>< /脚本>


I have this google script that can create shape and delete shape but nothing much about saving the shapes.

I looked up the internet and know that I can access the paths coordinates via getpaths() within the overlaycomplete And I can also push the coordinates into an array which collects all the shapes. However, what if user delete a shape? or update it?

My problem is I have no idea how to identify the deleted shape so that I can update the shape collection array accordingly

The second problem is I have no idea how to identify if user updated the shape and which shape got updated. Therefore can't update the shape collection array.

I will need a solution that, when click save button. I can get all the coordinates of the shapes that exist on the map. So I would not have to care about what got updated or deleted. My current code is as below:

 <!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing,geometry,places"></script>
<style>
    #map,html,body{
        height:100%;
        margin:0;
        padding:0;
    }
      #delete-button, #save-button {
        margin-top: 5px;
        position:absolute;
        z-index:999;
        right:6%;
        top:3%;
      }
      #save-button{
        right:1%;
      }
</style>
</head>
<body>
<div id="map"></div>
<button id="delete-button" class="btn">Delete seleted shape</button>
<button id="save-button" class="btn" onclick="save();">Save all</button>

<script>
    var drawingManager;
    var selectedShape;
    var shapeCollection = [];


    function save(){
        console.log(shapeCollection);
    }

    function clearSelection() {
        if (selectedShape) {
            selectedShape.setEditable(false);
            selectedShape = null;
        }
    }
    function setSelection(shape) {
        clearSelection();
        selectedShape = shape;
        shape.setEditable(true);
    }
    function deleteSelectedShape() {
        if (selectedShape) {
            selectedShape.setMap(null);
        }
    }
    function initialize() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom:10,
            center: new google.maps.LatLng(22.344, 114.048),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
        });

        var polyOptions = {
            strokeWeight: 3,
            fillOpacity: 0.2,
            editable: true,
            draggable: true
        };
        // Creates a drawing manager attached to the map that allows the user to draw
        // markers, lines, and shapes.
        drawingManager = new google.maps.drawing.DrawingManager({
            drawingControl: true,
            drawingControlOptions: {
                drawingModes: [google.maps.drawing.OverlayType.POLYGON]
            },
            drawingMode: google.maps.drawing.OverlayType.POLYGON,
            polygonOptions: polyOptions,
            map: map
        });

        google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {

            drawingManager.setDrawingMode(null);

            // Add an event listener that selects the newly-drawn shape when the user
            // mouses down on it.
            var newShape = e.overlay;
            newShape.type = e.type;
            google.maps.event.addListener(newShape, 'click', function() {
                setSelection(newShape);
            });
            setSelection(newShape);

        });

        //polygonPoints will be the array and index of the array will be the order
        // Clear the current selection when the drawing mode is changed, or when the
        // map is clicked.
        google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
        google.maps.event.addListener(map, 'click', clearSelection);
        google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);

    }

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

</script>

</body>
</html>

解决方案

Create a unique property(ID) for the shapes and store the shapes in an object(use the ID as key).

When you want to delete a shape you may use delete to remove the shape from the collection(based on the ID of the shape).

You don't have to care about updates by the user, when you store the shapes(references) in the collection they will be updated automatically.

Demo:

function initialize() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom:10,
            center: new google.maps.LatLng(22.344, 114.048),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            noClear:true
        });
        map.controls[google.maps.ControlPosition.RIGHT_BOTTOM]
          .push(document.getElementById('save-button'));
        map.controls[google.maps.ControlPosition.RIGHT_BOTTOM]
          .push(document.getElementById('delete-button'));
        var polyOptions = {
            strokeWeight: 3,
            fillOpacity: 0.2
        };
        
        var shapes={
          collection:{},
          selectedShape:null,
          add:function(e){
            var shape=e.overlay,
                that=this;
            shape.type=e.type;
            shape.id=new Date().getTime()+'_'+Math.floor(Math.random()*1000);
            this.collection[shape.id]=shape;
            this.setSelection(shape);
            google.maps.event.addListener(shape,'click',function(){
              that.setSelection(this);
            });
          },
          setSelection:function(shape){
            if(this.selectedShape!==shape){
              this.clearSelection();
              this.selectedShape = shape;
              shape.set('draggable',true);
              shape.set('editable',true);
            }
          },
          deleteSelected:function(){
          
            if(this.selectedShape){
              var shape= this.selectedShape;
              this.clearSelection();
              shape.setMap(null);
              delete this.collection[shape.id];
            }
           },
          
          
          clearSelection:function(){
            if(this.selectedShape){
              this.selectedShape.set('draggable',false);
              this.selectedShape.set('editable',false);
              this.selectedShape=null;
            }
          },
          save:function(){
            var collection=[];
            for(var k in this.collection){
              var shape=this.collection[k],
                  types=google.maps.drawing.OverlayType;
              switch(shape.type){
                case types.POLYGON:
                   collection.push({ type:shape.type,
                                     path:google.maps.geometry.encoding
                                      .encodePath(shape.getPath())});
                  break;
                default:
                  alert('implement a storage-method for '+shape.type)
              }
            }
            //collection is the result
            console.log(collection);
          }
        };
        
         var drawingManager = new google.maps.drawing.DrawingManager({
            drawingControl: true,
            drawingControlOptions: {
                drawingModes: [google.maps.drawing.OverlayType.POLYGON]
            },
            drawingMode: google.maps.drawing.OverlayType.POLYGON,
            polygonOptions: polyOptions,
            map: map
        });

        google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
            drawingManager.setDrawingMode(null);
            shapes.add(e);
        });


        google.maps.event.addListener(drawingManager, 
                                      'drawingmode_changed', 
                                      function(){shapes.clearSelection();});
        google.maps.event.addListener(map, 
                                      'click', 
                                      function(){shapes.clearSelection();});
        google.maps.event.addDomListener(document.getElementById('delete-button'), 
                                      'click', 
                                      function(){shapes.deleteSelected();});
        google.maps.event.addDomListener(document.getElementById('save-button'), 
                                      'click', 
                                      function(){shapes.save();});

    }

#map,html,body{
        height:100%;
        margin:0;
        padding:0;
    }

<div id="map">
  <button id="delete-button" class="btn">Delete selected shape</button>
  <button id="save-button" class="btn">Save all</button>
</div>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing,geometry,places&v=3&callback=initialize"></script>

Demo including a load-method for automatically loading of shapes:

function initialize() {
        var map = new google.maps.Map(document.getElementById('map'), {
            zoom:9,
            center: new google.maps.LatLng(22.344, 114.048),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            noClear:true
        });
        map.controls[google.maps.ControlPosition.RIGHT_BOTTOM]
          .push(document.getElementById('save-button'));
        map.controls[google.maps.ControlPosition.RIGHT_BOTTOM]
          .push(document.getElementById('delete-button'));
        var polyOptions = {
            strokeWeight: 3,
            fillOpacity: 0.2
        };
        
        var shapes={
          collection:{},
          selectedShape:null,
          add:function(e,s){
            var shape=e.overlay,
                that=this;
            shape.type=e.type;
            shape.id=new Date().getTime()+'_'+Math.floor(Math.random()*1000);
            this.collection[shape.id]=shape;
            if(!s)this.setSelection(shape);
            google.maps.event.addListener(shape,'click',function(){
              that.setSelection(this);
            });
          },
          setSelection:function(shape){
            if(this.selectedShape!==shape){
              this.clearSelection();
              this.selectedShape = shape;
              shape.set('draggable',true);
              shape.set('editable',true);
            }
          },
          deleteSelected:function(){
          
            if(this.selectedShape){
              var shape= this.selectedShape;
              this.clearSelection();
              shape.setMap(null);
              delete this.collection[shape.id];
            }
           },
          
          
          clearSelection:function(){
            if(this.selectedShape){
              this.selectedShape.set('draggable',false);
              this.selectedShape.set('editable',false);
              this.selectedShape=null;
            }
          },
          save:function(){
            var collection=[];
            for(var k in this.collection){
              var shape=this.collection[k],
                  types=google.maps.drawing.OverlayType;
              switch(shape.type){
                case types.POLYGON:
                   collection.push({ type:shape.type,
                                     path:google.maps.geometry.encoding
                                      .encodePath(shape.getPath())});
                  break;
                default:
                  alert('implement a storage-method for '+shape.type)
              }
            }
            //collection is the result
            console.log(JSON.stringify(collection));
            return collection;
          },
          load:function(arr){
            var types=google.maps.drawing.OverlayType;
            for(var i=0;i<arr.length;++i){
              switch(arr[i].type){
                 case types.POLYGON:
                   var shape=new google.maps.Polygon(polyOptions);
                   shape.setOptions({map:map,
                                     path:google.maps.geometry.encoding
                                            .decodePath(arr[i].path)});
                   shapes.add({type:types.POLYGON,overlay:shape},true)
                  break;
                default:
                  alert('implement a loading-method for '+arr[i].type)
              }
            }
          }
        };
        
        //initially load some shapes
        shapes.load([{"type":"polygon","path":"_}sgCamyuT~ee@eP|FkdEskn@nr@rdH`wM"},
                     {"type":"polygon","path":"mnngCchxvT?y{DylG{{D~tFihCng_@v{O?wiVymDdPzNblLah\\i}LksLngJ"}]);
         var drawingManager = new google.maps.drawing.DrawingManager({
            drawingControl: true,
            drawingControlOptions: {
                drawingModes: [google.maps.drawing.OverlayType.POLYGON]
            },
            drawingMode: google.maps.drawing.OverlayType.POLYGON,
            polygonOptions: polyOptions,
            map: map
        });

        google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
            drawingManager.setDrawingMode(null);
            shapes.add(e);
        });


        google.maps.event.addListener(drawingManager, 
                                      'drawingmode_changed', 
                                      function(){shapes.clearSelection();});
        google.maps.event.addListener(map, 
                                      'click', 
                                      function(){shapes.clearSelection();});
        google.maps.event.addDomListener(document.getElementById('delete-button'), 
                                      'click', 
                                      function(){shapes.deleteSelected();});
        google.maps.event.addDomListener(document.getElementById('save-button'), 
                                      'click', 
                                      function(){shapes.save();});

    }

#map,html,body{
        height:100%;
        margin:0;
        padding:0;
    }

<div id="map">
  <button id="delete-button" class="btn">Delete selected shape</button>
  <button id="save-button" class="btn">Save all</button>
</div>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing,geometry,places&v=3&callback=initialize"></script>

这篇关于谷歌地图API v3如何获取所有形状的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆