是否可以向Google发送两个经纬度点以计算它们之间的距离?
是否可以向Google发送两个经纬度点以计算它们之间的距离?
如果你想使用v3的谷歌地图API,这是我使用的一个函数:
注意:你必须将&libraries=geometry
添加到你的脚本源代码中。
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>
现在是这个函数:
//calculates distance between two points in km's
function calcDistance(p1, p2){
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
是的,谷歌可以做到这一点
以下是一段 JavaScript 代码,用于获取两个点之间的距离(单位为千米)
function initialize() { if (GBrowserIsCompatible()) { map = new GMap2(document.getElementById("map_canvas")); map.setCenter(new GLatLng(52.6345701, -1.1294433), 13); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); geocoder = new GClientGeocoder();
// NR14 7PZ var loc1 = new GLatLng(52.5773139, 1.3712427); // NR32 1TB var loc2 = new GLatLng(52.4788314, 1.7577444); alert(loc2.distanceFrom(loc1) / 1000); } }
还有在C#中的距离计算:
// this returns the distance in miles. for km multiply result: * 1.609344
public static double CalculateDistance(double lat1, double lon1, double lat2, double lon2)
{
double t = lon1 - lon2;
double distance = Math.Sin(Degree2Radius(lat1)) * Math.Sin(Degree2Radius(lat2)) + Math.Cos(Degree2Radius(lat1)) * Math.Cos(Degree2Radius(lat2)) * Math.Cos(Degree2Radius(t));
distance = Math.Acos(distance);
distance = Radius2Degree(distance);
distance = distance * 60 * 1.1515;
return distance;
}
private static double Degree2Radius(double deg)
{
return (deg * Math.PI / 180.0);
}
private static double Radius2Degree(double rad)
{
return rad / Math.PI * 180.0;
}
function InitDistances() {
var startLocation = new GLatLng(startLat, startLon);
var endLocation = new GLatLng(endLat, endLon);
var dist = startLocation .distanceFrom(endLocation);
// Convert distance to miles with two decimal points precision
return (dist / 1609.344).toFixed(2);
}
有一个方便的函数
http://code.google.com/apis/maps/documentation/reference.html#GLatLng.distanceFrom
基本上创建2个GlatLng对象,然后使用上述方法。