Google Maps API 多边形区域

Mar*_*tin 0 javascript geometry google-maps-api-3

我正在尝试求多边形的面积。这发生在加载多边形时并将在函数中使用。这是我的代码:

  map.data.forEach(function(feature) {
    if (feature.getGeometry().getType() == "Polygon") {
        var bounds=[];
        feature.getGeometry().forEachLatLng(function(path) {
          var temp = new google.maps.LatLng(path.lat,path.lng);
          bounds.push(temp);

        });
        console.log(bounds);
        console.log(google.maps.geometry.spherical.computeArea(bounds));

    }
});
Run Code Online (Sandbox Code Playgroud)

如果加载的对象是多边形,它会创建一个 LatLng 数组,然后应该使用computeArea 函数。我不断收到返回的 NaN 。我查看了帮助文档,计算区域采用 latLngs 区域,这就是边界。

边界显示正确,所以我不确定为什么没有计算面积。

geo*_*zip 5

.forEachLatLng函数返回一个google.maps.LatLng. 它没有.lat.lng属性(并且您不需要将其转换为 a google.maps.LatLng,它已经是一个),这些是Functions

这对我有用:

map.data.forEach(function(feature) {
    if (feature.getGeometry().getType() == "Polygon") {
        var bounds=[];
        feature.getGeometry().forEachLatLng(function(path) {
          bounds.push(path);
        });
        console.log(bounds);
        console.log(google.maps.geometry.spherical.computeArea(bounds));
    }
});
Run Code Online (Sandbox Code Playgroud)

概念证明小提琴

代码片段:

map.data.forEach(function(feature) {
    if (feature.getGeometry().getType() == "Polygon") {
        var bounds=[];
        feature.getGeometry().forEachLatLng(function(path) {
          bounds.push(path);
        });
        console.log(bounds);
        console.log(google.maps.geometry.spherical.computeArea(bounds));
    }
});
Run Code Online (Sandbox Code Playgroud)
function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      zoom: 4,
      center: {
        lat: -28,
        lng: 137
      },
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  map.data.loadGeoJson(
    'https://storage.googleapis.com/mapsdevsite/json/google.json', {},
    function(features) {

      map.data.forEach(function(feature) {
        if (feature.getGeometry().getType() == "Polygon") {
          var bounds = [];
          var polyBnds = new google.maps.LatLngBounds();

          feature.getGeometry().forEachLatLng(function(path) {
            bounds.push(path);
            polyBnds.extend(path);
          });
          console.log(bounds);
          var area = google.maps.geometry.spherical.computeArea(bounds);
          console.log(area);
          var iW = new google.maps.InfoWindow({
            content: area.toFixed(2) + " sq meters",
            position: polyBnds.getCenter()
          });
          iW.open(map);
        }
      });
    });
}
google.maps.event.addDomListener(window, "load", initialize);
Run Code Online (Sandbox Code Playgroud)
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
Run Code Online (Sandbox Code Playgroud)