计算多边形的面积

时间:2012-05-26 11:02:32

标签: google-maps-api-3

我需要在地图中获取多边形的区域。我找了一个new google.maps.geometry.spherical.computeArea的例子,但我不能让它工作,我不知道为什么。

function dibuV(area){
  var i;
  var a = new Array();
  for(i=0; i<area.length; i++){
    var uno = area[i].split(",");
    a[i] = new google.maps.LatLng(uno[0],uno[1]);
  }
  poligon = new google.maps.Polygon({
    paths: a,
    strokeColor: "#22B14C",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#22B14C",  
    fillOpacity: 0.35  
  })  
  poligon.setMap(map);//until here is ok 
  var z = new google.maps.geometry.spherical.computeArea(poligon.getPath());
  alert(z); //this is not working
}

3 个答案:

答案 0 :(得分:15)

您的代码为您提供的错误:google.maps.geometry is undefined

Google Maps v3 API documentation开始,几何函数是默认情况下未加载的库的一部分:

  

本文档中的概念仅指可用的功能   在google.maps.geometry库中。此库未加载   加载Maps Javascript API时的默认值,但必须明确   通过使用库引导参数指定。

为了加载和使用页面中的几何函数,您需要通过包含libraries=geometry

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>

这将加载几何库,您的z变量将包含一个对象。

带有工作代码的测试页面:

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
      html, body, #map_canvas {
        margin: 0;
        padding: 0;
        height: 100%;
      }
    </style>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=false"></script>
<script type="text/javascript">
    var map;
    function initialize()
    {
        var myOptions = {
          zoom: 8,
          center: new google.maps.LatLng(-34.397, 150.644),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
    }

    google.maps.event.addDomListener(window, 'load', initialize);
    </script>
<script>
function test()
{
var arr = new Array()
arr.push('51.5001524,-0.1262362');
arr.push('52.5001524,-1.1262362');
arr.push('53.5001524,-2.1262362');
arr.push('54.5001524,-3.1262362');
dibuV(arr);
}
function dibuV(area)
{
var a = new Array();

for(var i=0; i<area.length; i++)
{
    var uno = area[i].split(",");
    a[i] = new google.maps.LatLng(uno[0],uno[1]);
}

poligon = new google.maps.Polygon({
    paths: a,
    strokeColor: "#22B14C",
    strokeOpacity: 0.8,
    strokeWeight: 2,
    fillColor: "#22B14C",   
    fillOpacity: 0.35   
})  

poligon.setMap(map);//until here is ok 
var z = new google.maps.geometry.spherical.computeArea(poligon.getPath());
alert(z); //this is not working
}
</script>
</head>
<body onload="test();">
    <div id="map_canvas"></div>
</body>
</html>

答案 1 :(得分:6)

这不起作用,因为您使用“new”来使用computeArea方法。 使用“google.maps.geometry.spherical.computeArea”而不使用“new”。 示例:

var z = google.maps.geometry.spherical.computeArea(myPolyline.getPath().getArray());
alert(z);

这样可行。

答案 2 :(得分:0)

请看下面的代码

var z = google.maps.geometry.spherical.computeArea(poligon.getPath());
相关问题