【问题标题】:Draw polygon with drawing manager & show area * co-ordinates in Infowindow in google maps使用绘图管理器和显示区域绘制多边形 * 谷歌地图信息窗口中的坐标
【发布时间】:2015-08-08 13:29:37
【问题描述】:

我正在尝试创建一个地图,我可以在其中绘制多边形并在信息窗口中显示它的区域和坐标。

以下是我所拥有的,我卡在信息窗口内显示区域和坐标。

链接到code

代码 sn-p:

var map, infoWindow, drawingManager;

function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(-34.397, 150.644),
    zoom: 8
  };

  map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);
  infoWindow = new google.maps.InfoWindow();

  drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.POLYGON,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: [
        google.maps.drawing.OverlayType.POLYGON
      ]
    },
    polygonOptions: {
      fillColor: '#ffff00',
      fillOpacity: 1,
      strokeWeight: 5,
      clickable: false,
      editable: true,
      zIndex: 1
    }
  });
  drawingManager.setMap(map);
  google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
    openInfoWindowPolygon(polygon);
  });
}

function openInfoWindowPolygon(polygon) {

  var vertices = polygon.getPath();

  var contents = "z";
  var bounds = new google.maps.LatLngBounds();
  vertices.forEach(function(xy, i) {
    bounds.extend(xy);
  });
  infoWindow.setContent(contents);
  infoWindow.setPosition(bounds.getCenter());
  drawingManager.setDrawingMode(null);
  infoWindow.open(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=drawing"></script>
<div id="map-canvas"></div>

【问题讨论】:

    标签: google-maps google-maps-api-3 maps polygon


    【解决方案1】:

    使用Google Maps Geometry Library,有一些函数可以计算面积。

    function openInfoWindowPolygon(polygon) {
    
        var vertices = polygon.getPath();
    
        var contents = "<b>Vertices:</b><ol>";
        vertices.forEach(function(vert, index){contents += "<li>"+vert.toString()+"</li>"});
        contents += "</ol><b>Area:</b>"+google.maps.geometry.spherical.computeArea(vertices);
        infoWindow.setContent(contents);
    
        var bounds = new google.maps.LatLngBounds();
        vertices.forEach(function(xy,i){
            bounds.extend(xy);
        });
        infoWindow.setPosition(bounds.getCenter());
        drawingManager.setDrawingMode(null);
        infoWindow.open(map);
    }
    

    这段代码将顶点编译成&lt;ol&gt;,然后添加下面的区域。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-23
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多