![](/img/trans.png)
[英]How to get shortest distance between two shapes on Google Maps, using JavaScript?
[英]Google Maps - How to get the distance between two point in metre?
我有這些坐標:
(45.463688, 9.18814)
(46.0438317, 9.75936230000002)
我需要(我認為是 Google API V3)以米為單位獲得這兩個點之間的距離。 我該怎么做?
如果您想使用 v3 谷歌地圖 API,這里有一個可以使用的函數:注意:您必須將&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>
我認為您可以在沒有任何特定 API 的情況下進行,並使用純 Javascript 計算距離:
這個站點有關於地理計算的很好的信息和用於距離計算的 Javascript 示例。
好的,快速瀏覽一下 Google API 頁面,您似乎可以通過以下方式完成:
這主要是通過 google api 之外的數學完成的,因此除了找到正確的坐標之外,您不需要使用該 API 進行任何其他操作。
知道這一點,這里有一個鏈接,指向先前回答的與 Javascript 相關的問題。
嘗試這個
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];
嘗試這個:
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;
}
您指的是整個路徑長度的距離,還是只想知道位移(直線距離)? 我看沒有人在這里指出距離和位移之間的區別。 對於距離計算由 JSON/XML 數據給出的每個路線點,對於位移,有一個使用Spherical
類的內置解決方案。
您指的是整個路徑長度的距離,還是只想知道位移(直線距離)? 我看沒有人在這里指出距離和位移之間的區別。 對於距離計算由 JSON/XML 數據給出的每個路線點,對於位移,有一個使用Spherical
類的內置解決方案。 這個想法是,如果您指的是距離,那么您只需在每個路徑點上使用computeDistanceBetween
並將其連接起來。
//calculates distance between two points in km's
function calcDistance(p1, p2) {
return (google.maps.geometry.spherical.computeDistanceBetween(p1, p2) / 1000).toFixed(2);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.