gpt4 book ai didi

javascript - LatLng 是否在多边形内

转载 作者:数据小太阳 更新时间:2023-10-29 05:55:28 26 4
gpt4 key购买 nike

我在带有一些 latLng 的谷歌地图上设置了一个典型的多边形:

var bermudaTriangle = new google.maps.Polygon({
paths: [
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.75737),
]
});
bermudaTriangle.setMap(map);

这些是谷歌文档中的百慕大三 Angular 坐标。我也有一些随机坐标,saaay:

var coord1 = new new google.maps.LatLng(26.194876675795218,-69.8291015625)
var coord2 = new new google.maps.LatLng(33.194876675795218,-63.8291015625)

第一个恰好在三 Angular 形内部,第二个恰好在三 Angular 形外部。不过,这些只是示例,我需要的是一种方法来确定所提供的坐标(不仅仅是这两个坐标中的一个,任何坐标)是在多边形内部还是外部(而且,并不总是百慕大三 Angular ,甚至不是三 Angular 形- 多边形可以有任意数量的经纬度)。我查看了 Google Maps API 文档,但找不到任何提供的功能这个问题的答案。

最佳答案

使用 containsLocation(point:LatLng, polygon:Polygon)方法。

containsLocation(point:LatLng, polygon:Polygon) boolean Computes whether the given point lies inside the specified polygon.

proof of concept fiddle

代码片段:

function checkInPolygon(marker, polygon) {
var infowindow = new google.maps.InfoWindow();
var html = "";
if (google.maps.geometry.poly.containsLocation(marker.getPosition(), polygon)) {
html = "inside polygon";
} else {
html = "outside polygon";
}
infowindow.setContent(html);
infowindow.open(map, marker);
}

var map;
var coord1 = new google.maps.LatLng(26.194876675795218, -69.8291015625);
var coord2 = new google.maps.LatLng(33.194876675795218, -63.8291015625);

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
});
bermudaTriangle.setMap(map);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < bermudaTriangle.getPath().getLength(); i++) {
bounds.extend(bermudaTriangle.getPath().getAt(i));
}
bounds.extend(coord1);
bounds.extend(coord2);
var marker1 = new google.maps.Marker({
map: map,
position: coord1
});
var marker2 = new google.maps.Marker({
map: map,
position: coord2,
});
map.setCenter(bounds.getCenter());
map.setZoom(3);
checkInPolygon(marker1, bermudaTriangle);
checkInPolygon(marker2, bermudaTriangle);
}
google.maps.event.addDomListener(window, "load", initialize);

var bermudaTriangle = new google.maps.Polygon({
paths: [
new google.maps.LatLng(25.774252, -80.190262),
new google.maps.LatLng(18.466465, -66.118292),
new google.maps.LatLng(32.321384, -64.75737),
]
});
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas"></div>

关于javascript - LatLng 是否在多边形内,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15097464/

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