在googlemaps api中保存绘制的多边形

时间:2017-09-10 22:10:41

标签: javascript google-maps

大家好我试着从谷歌地图api中保存一个绘制的多边形,我不知道怎么做。我想保存多边形(坐标或路径并将它们作为一个表格发送。这就是什么我到现在为止,我试图阅读文档,但我无法理解。

<script>
    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: 46.435812, lng: 27.639917},
            zoom: 17,
            mapTypeId: 'hybrid'});

       var drawingManager = new google.maps.drawing.DrawingManager({
           drawingMode: google.maps.drawing.OverlayType.MARKER,
           drawingControl: true,
           drawingControlOptions: {
               position: google.maps.ControlPosition.TOP_CENTER,
               drawingModes: ['polygon']
           },
       });

       drawingManager.setMap(map);
    };
</script>

编辑:

<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBR0YEEOUbWC8qYTig79dMHfOzXR44wX5w&libraries=geometry,drawing&callback=initMap"></script>

1 个答案:

答案 0 :(得分:1)

对于多边形,执行与类似问题相同的操作:Saving coordinates and data from Google maps in a database,只需对多边形(polygoncomplete)使用适当的事件并处理整个路径,添加所有坐标到适当的表格字段:

google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
  var coordStr = "";
  for (var i = 0; i < polygon.getPath().getLength(); i++) {
    coordStr += polygon.getPath().getAt(i).toUrlValue(6) + ";";
    console.log(coordStr);
    document.getElementById('coords').value = coordStr;
  }
});

proof of concept fiddle

代码段

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 46.435812,
      lng: 27.639917
    },
    zoom: 17,
    mapTypeId: 'hybrid'
  });

  var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYGON,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: ['polygon']
    },
  });
  google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
    var coordStr = "";
    for (var i = 0; i < polygon.getPath().getLength(); i++) {
      coordStr += polygon.getPath().getAt(i).toUrlValue(6) + ";";
    }
    document.getElementById('coords').value = coordStr;
  });
  drawingManager.setMap(map);
};
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing"></script>
<input id="coords" style="width:600px" />
<div id="map"></div>