有人可以帮我用原生JavaScript填空吗?
function getHeading(lat1, lon1, lat2, lon2) {
// Do cool things with math here
return heading; // Should be a number between 0 and 360
}
我已经搞乱了很长一段时间,似乎无法使我的代码正常工作.
解决方法:
Chris Veness在Calculate distance, bearing and more between Latitude/Longitude points下的Bearings标题下有一个非常好的JavaScript实现.
您可能更喜欢使用getHeading方法扩充Google的LatLng原型,如下所示(使用v3 API):
Number.prototype.toRad = function() {
return this * Math.PI / 180;
}
Number.prototype.toDeg = function() {
return this * 180 / Math.PI;
}
google.maps.LatLng.prototype.getHeading = function(point) {
var lat1 = this.lat().toRad(), lat2 = point.lat().toRad();
var dLon = (point.lng() - this.lng()).toRad();
var y = Math.sin(dLon) * Math.cos(lat2);
var x = Math.cos(lat1) * Math.sin(lat2) -
Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
var brng = Math.atan2(y, x);
return ((brng.toDeg() + 360) % 360);
}
然后可以这样使用:
var pointA = new google.maps.LatLng(40.70, -74.00);
var pointB = new google.maps.LatLng(40.70, -75.00);
pointA.getHeading(pointB); // Returns 270 degrees
否则,如果您更喜欢全局函数而不是扩充Google的LatLng,则可以按如下方式执行:
function getHeading(lat1, lon1, lat2, lon2) {
var lat1 = lat1 * Math.PI / 180;
var lat2 = lat2 * Math.PI / 180;
var dLon = (lon2 - lon1) * Math.PI / 180;
var y = Math.sin(dLon) * Math.cos(lat2);
var x = Math.cos(lat1) * Math.sin(lat2) -
Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
var brng = Math.atan2(y, x);
return (((brng * 180 / Math.PI) + 360) % 360);
}
用法:
getHeading(40.70, -74.00, 40.70, -75.00); // Returns 270 degrees