我有这些坐标:
(45.463688, 9.18814)
(46.0438317, 9.75936230000002)
我需要通过Google API V3(我想)获取这2个点之间的距离,单位为米。我该怎么做?
(45.463688, 9.18814)
(46.0438317, 9.75936230000002)
我需要通过Google API V3(我想)获取这2个点之间的距离,单位为米。我该怎么做?
&libraries=geometry
。<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>
<script>
var p1 = new google.maps.LatLng(45.463688, 9.18814);
var p2 = new google.maps.LatLng(46.0438317, 9.75936230000002);
alert(calcDistance(p1, p2));
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
</script>
calcDistance
函数提供了字符串。请尝试修改为 console.log(calcDistance(45.463688, 9.18814, 46.0438317, 9.75936230000002));
。 - Nishant Nawarkhede我认为您可以不使用任何特定的API,而是使用纯JavaScript计算距离:
这个网站提供了有关地理计算和JavaScript距离计算示例的良好信息。
好的,快速查看Google API页面,似乎您可以通过以下方式实现:
试试这个
CLLocationCoordinate2D coord1;
coord1.latitude = 45.463688;
coord1.longitude = 9.18814;
CLLocation *loc1 = [[[CLLocation alloc] initWithLatitude:coord1.latitude longitude:coord1.longitude] autorelease];
CLLocationCoordinate2D coord2;
coord2.latitude = 46.0438317;
coord2.longitude = 9.75936230000002;
CLLocation *loc2 = [[[CLLocation alloc] initWithLatitude:46.0438317 longitude:9.75936230000002] autorelease];
CLLocationDistance d1 = [loc1 distanceFromLocation:loc2];
这主要是通过数学计算完成的,与谷歌API无关,因此您不应该需要使用API来执行除了查找正确坐标之外的任何操作。
知道了这一点,这里有一个链接,指向一个先前回答过的与Javascript相关的问题。
试试这个:
const const toRadians = (val) => {
return val * Math.PI / 180;
}
const toDegrees = (val) => {
return val * 180 / Math.PI;
}
// Calculate a point winthin a circle
// circle ={center:LatLong, radius: number} // in metres
const pointInsideCircle = (point, circle) => {
let center = circle.center;
let distance = distanceBetween(point, center);
//alert(distance);
return distance < circle.radius;
};
const distanceBetween = (point1, point2) => {
//debugger;
var R = 6371e3; // metres
var φ1 = toRadians(point1.latitude);
var φ2 = toRadians(point2.latitude);
var Δφ = toRadians(point2.latitude - point1.latitude);
var Δλ = toRadians(point2.longitude - point1.longitude);
var a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
Math.cos(φ1) * Math.cos(φ2) *
Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
Spherical
类解决。