我们需要一个方法,当给定方位角和从源点出发的距离时,返回目标点。幸运的是,Chris Veness在
计算纬度/经度点之间距离、方位角等的优秀JavaScript实现中提供了非常好的解决方案。
以下内容已经适配为使用
google.maps.LatLng
类:
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
}
google.maps.LatLng.prototype.destinationPoint = function(brng, dist) {
dist = dist / 6371;
brng = brng.toRad();
var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) +
Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
Math.cos(lat1),
Math.cos(dist) - Math.sin(lat1) *
Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
您可以简单地按以下方式使用它:
var pointA = new google.maps.LatLng(25.48, -71.26);
var radiusInKm = 10;
var pointB = pointA.destinationPoint(90, radiusInKm);
以下是一个完整的示例,使用Google Maps API v3:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Geometry</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
}
google.maps.LatLng.prototype.destinationPoint = function(brng, dist) {
dist = dist / 6371;
brng = brng.toRad();
var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();
var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) +
Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));
var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
Math.cos(lat1),
Math.cos(dist) - Math.sin(lat1) *
Math.sin(lat2));
if (isNaN(lat2) || isNaN(lon2)) return null;
return new google.maps.LatLng(lat2.toDeg(), lon2.toDeg());
}
var pointA = new google.maps.LatLng(40.70, -74.00);
var radius = 10;
var mapOpt = {
mapTypeId: google.maps.MapTypeId.TERRAIN,
center: pointA,
zoom: 10
};
var map = new google.maps.Map(document.getElementById("map"), mapOpt);
new google.maps.Circle({
center: pointA,
radius: radius * 1000,
fillColor: '#FF0000',
fillOpacity: 0.2,
map: map
});
new google.maps.Marker({
position: pointA,
map: map
});
new google.maps.Marker({
position: pointA.destinationPoint(90, radius),
map: map
});
</script>
</body>
</html>
截图:
![Google Maps Geometry](https://i.imgur.com/IgXd59o.png)
更新:
回复Paul的评论,当圆环绕其中一个极点时会发生什么。
绘制pointA
位于北极附近,半径为1,000公里:
var pointA = new google.maps.LatLng(85, 0)
var radius = 1000
pointA.destinationPoint(90, radius)
的屏幕截图:
![靠近北极](https://i.imgur.com/EorwQPJ.png)
GLatLng
替换google.maps.LatLng
即可。如果你遇到任何困难,请告诉我。 - Daniel Vassallo