在JavaScript中使用Google Maps API计算多边形面积

在JavaScript中使用Google Maps API计算多边形面积可以通过以下步骤实现:

  1. 确保您已经在页面中加载了Google Maps API。
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
    
  2. 创建一个多边形,并获取其顶点坐标。
    var polygon = new google.maps.Polygon({
      paths: [
        new google.maps.LatLng(25.774, -80.19),
        new google.maps.LatLng(18.466, -66.118),
        new google.maps.LatLng(32.321, -64.757),
        new google.maps.LatLng(25.774, -80.19)
      ],
      strokeColor: '#FF0000',
      strokeOpacity: 0.8,
      strokeWeight: 2,
      fillColor: '#FF0000',
      fillOpacity: 0.35
    });
    polygon.setMap(map);
    
  3. 使用Google Maps API提供的computeArea方法计算多边形的面积。
    var area = google.maps.geometry.spherical.computeArea(polygon.getPath());
    console.log("Area: ", area, " square meters");
    

  4. 请注意,computeArea方法需要geometry库,所以在加载Google Maps API时需要包含libraries=geometry参数。
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry"></script>
    

完整的示例代码如下::

<!DOCTYPE html>
<html>
  <head>
    <title>Google Maps API</title>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry"></script>
    <style>
      #map {
        height: 400px;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <script>
      var map;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 5,
          center: {lat: 25.774, lng: -80.19}
        });

        var polygon = new google.maps.Polygon({
          paths: [
            new google.maps.LatLng(25.774, -80.19),
            new google.maps.LatLng(18.466, -66.118),
            new google.maps.LatLng(32.321, -64.757),
            new google.maps.LatLng(25.774, -80.19)
          ],
          strokeColor: '#FF0000',
          strokeOpacity: 0.8,
          strokeWeight: 2,
          fillColor: '#FF0000',
          fillOpacity: 0.35
        });
        polygon.setMap(map);

        var area = google.maps.geometry.spherical.computeArea(polygon.getPath());
        console.log("Area: ", area, " square meters");
      }

      initMap();
    </script>
  </body>
</html>

请确保将YOUR_API_KEY替换为您的Google Maps API密钥。这个示例代码应该在支持Google Maps API的浏览器中正常工作,并且会计算并输出多边形的面积(单位为平方米)。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值