在JavaScript中使用Google Maps API计算多边形面积可以通过以下步骤实现:
- 确保您已经在页面中加载了Google Maps API。
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
- 创建一个多边形,并获取其顶点坐标。
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);
- 使用Google Maps API提供的
computeArea
方法计算多边形的面积。var area = google.maps.geometry.spherical.computeArea(polygon.getPath()); console.log("Area: ", area, " square meters");
- 请注意,
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的浏览器中正常工作,并且会计算并输出多边形的面积(单位为平方米)。