アプリケーション (MVC を使用した ASP.NET) で Google Maps API を使用しています。
座標の配列 (それぞれが緯度と経度で構成される) を持っています。これを「原点」(これはポリゴン、ポリライン、またはマーカーにすることができます) と呼び、別の座標配列を「目的地」と呼びましょう (ポリゴン、ポリライン、またはマーカーのいずれか)。
「出発地」と「目的地」の最短距離を計算したい。どうやってやるの?
アプリケーション (MVC を使用した ASP.NET) で Google Maps API を使用しています。
座標の配列 (それぞれが緯度と経度で構成される) を持っています。これを「原点」(これはポリゴン、ポリライン、またはマーカーにすることができます) と呼び、別の座標配列を「目的地」と呼びましょう (ポリゴン、ポリライン、またはマーカーのいずれか)。
「出発地」と「目的地」の最短距離を計算したい。どうやってやるの?
ポイント間の距離を計算するには、球面余弦法則を使用することをお勧めします。出発地の緯度と経度の配列と、目的地の緯度と経度の配列がある場合、次のようなことができます。
var origins = [{lat: "35.5", lon: "-80.0"}, ...]; // Array of origin coordinates
var destinations = [{lat: "34.5", lon: "-80.0"}, ...]; // Array of destination coordinates
var shortestDistance = null;
var shortestPair = [];
for (i = 0; i < origins.length; i++) {
for (j = 0; j < destinations.length; j++) {
var lat1 = origins[i].lat.toRadians();
var lat2 = destinations[j].lat.toRadians();
var lon = (destinations[j].lon - origins[i].lon).toRadians();
var R = 6371; // gives distance in kilometers
var calcDistance = Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon)) * R;
if (shortestDistance === null || calcDistance < shortestDistance) {
shortestPair[0] = origins[i]; // Store the origin coordinates
shortestPair[1] = destinations[j]; // Store the destination coordinates
shortestDistance = calcDistance; // Update the shortest distance
}
}
}
/* After this runs, you'll have the array indexes for the origin and
destination with the shortest distance as well as the actual distance (kilometers)
in the array shortestPair and the variable shortestDistance respectively.
For miles, divide shortestDistance by 1.609344
For nautical miles, divide shortestDistance by 1.852
*/
これは、距離の計算に Maps API を使用するよりも簡単な方法のようです。上記の式はhttp://www.movable-type.co.uk/scripts/latlong.htmlから引用されました。計算をより正確にする必要がある場合は、harsine 式を使用することもできます。リンク先のページに詳しく書いてあります。