使用谷歌地图计算绘制多边形面积的最简单方法

时间:2018-01-17 10:55:24

标签: javascript html google-maps area

Javascript / google地图初学者在这里。 我正在寻找一种简单的方法来计算用户在地图上绘制的多边形的面积。 代码段:



function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 53,
      lng: 0
    },
    zoom: 13
  });
  var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.MARKER,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: ['polygon']
    },
    circleOptions: {
      fillColor: '#ffff00',
      fillOpacity: 1,
      strokeWeight: 5,
      clickable: false,
      editable: true,
      zIndex: 1
    }
  });
  drawingManager.setMap(map);
}

<div>
  <div id="map" style="width: 100%; height: 500px;"></div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

使用google.maps.geometry.spherical.computeArea方法

var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
  var area = google.maps.geometry.spherical.computeArea(polygon.getPath());
  infowindow.setContent("polygon area="+area.toFixed(2)+" sq meters");
  infowindow.setPosition(polygon.getPath().getAt(0));
  infowindow.open(map);
 });

proof of concept fiddle

screenshot of resulting map

代码段

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {
      lat: 53.000581,
      lng: -0.005
    },
    zoom: 19
  });
  var infowindow = new google.maps.InfoWindow();
  var polygon = new google.maps.Polygon({
    path: [{lat: 53.000842,lng: -0.004903},
           {lat: 53.000823,lng: -0.004798},
           {lat: 53.000779,lng: -0.004823},
           {lat: 53.000799,lng: -0.004935}],
    map: map
  });
  var area = google.maps.geometry.spherical.computeArea(polygon.getPath());

  infowindow.setContent("polygon area=" + area.toFixed(2) + " sq meters");
  infowindow.setPosition(polygon.getPath().getAt(0));
  infowindow.open(map);
  var drawingManager = new google.maps.drawing.DrawingManager({
    drawingMode: google.maps.drawing.OverlayType.MARKER,
    drawingControl: true,
    drawingControlOptions: {
      position: google.maps.ControlPosition.TOP_CENTER,
      drawingModes: ['polygon']
    },
    drawingMode: null
  });

  google.maps.event.addListener(drawingManager, 'polygoncomplete', function(polygon) {
    var area = google.maps.geometry.spherical.computeArea(polygon.getPath());
    infowindow.setContent("polygon area=" + area.toFixed(2) + " sq meters");
    infowindow.setPosition(polygon.getPath().getAt(0));
    infowindow.open(map);
  });
  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=geometry,drawing"></script>
<div id="map"></div>