用绘图管理器绘制多边形&在Google地图中显示Infowindow的区域*坐标

时间:2015-08-08 13:29:38

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

我正在尝试创建一个可以绘制多边形的地图。展示它的区域& infowindow中的坐标。

以下是我所拥有的,我被困在显示区域和&在信息系统内部进行协调。

链接到code

代码段



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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

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

此代码将顶点编译为<ol>,然后添加下面的区域。