gpt4 book ai didi

javascript - 获取多边形的边界(JS)

转载 作者:行者123 更新时间:2023-11-28 17:38:29 26 4
gpt4 key购买 nike

我在 map 上绘制多边形。

这是drawingManager的函数

 drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControlOptions: {
drawingModes: [
google.maps.drawing.OverlayType.RECTANGLE,
google.maps.drawing.OverlayType.POLYGON

]
},
polygonOptions: {
fillColor: 'green',
fillOpacity: 0.4,
strokeWeight: 1,
clickable: true,
zIndex: 1,
editable: false
}
});

我需要计算多边形的边界。我读到,我不能像使用 square 那样通过 .getBounds 来做到这一点。

所以我在这里找到了answer

我尝试了其中一个答案。

现在我的代码如下所示。

drawingManager.addListener('polygoncomplete', function (polygon) {
var bounds = new google.maps.LatLngBounds();

polygon.forEach(function (feature) {
if (feature.getGeometry().getType() === 'Polygon') {
feature.getGeometry().forEachLatLng(function (latlng) {
bounds.extend(latlng);
});
}
});
console.dir(bounds);
});

在控制台中我收到此错误。

Index.js:1673 Uncaught TypeError: polygon.forEach is not a function

在这一行polygon.forEach(function (feature) {

问题出在哪里以及如何解决?

最佳答案

参见the documentation :

多边形有一个 .getPaths() 方法,该方法返回 LatLng 对象的 MVCArray。

drawingManager.addListener('polygoncomplete', function(polygon) {
var bounds = new google.maps.LatLngBounds();
polygon.getPaths().forEach(function(path) {
path.forEach(function(latlng) {
bounds.extend(latlng);
map.fitBounds(bounds);
});
});
});

proof of concept fiddle

代码片段:

function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var drawingManager = new google.maps.drawing.DrawingManager({
map: map,
drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
drawingControlOptions: {
drawingModes: [
google.maps.drawing.OverlayType.RECTANGLE,
google.maps.drawing.OverlayType.POLYGON

]
},
polygonOptions: {
fillColor: 'green',
fillOpacity: 0.4,
strokeWeight: 1,
clickable: true,
zIndex: 1,
editable: false
}
});
drawingManager.addListener('polygoncomplete', function(polygon) {
var bounds = new google.maps.LatLngBounds();


polygon.getPaths().forEach(function(path) {
path.forEach(function(latlng) {
bounds.extend(latlng);
map.fitBounds(bounds);
});
});
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry,drawing&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

关于javascript - 获取多边形的边界(JS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48520363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com