我目前正在开发一个使用google的Javascript程序。它需要做的是:
我已经完成了步骤1和步骤2,但是我无法找到一种方法来存储位置的索引(识别它的方法)以及lng和lat点,这样我就可以循环遍历它们,并将它们与用户输入的位置进行比较。我也想不出找到最短距离的方法,所有的点都能找到最接近的液化天然气和lat。
任何帮助都将不胜感激,
谢谢!
发布于 2012-11-09 00:19:25
我认为你应该能够根据你的目的调整这个答案。
//forumla for calculating distances between points
var getDistance = function(p1, p2) {
var rad = function(x) {return x*Math.PI/180;}
var R = 6371; // earth's mean radius in km
var dLat = rad(p2.lat() - p1.lat());
var dLong = rad(p2.lng() - p1.lng());
var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d.toFixed(3);
}
// LatLng object with your current coordinates
var yourLocation = new google.maps.LatLng(yourlat, yourlng);
// populate an array of hard coded LatLng objects
var twentypoints = {};
twentypoints['hardcodedName1'] = new google.maps.LatLng(lat1, lng1);
twentypoints['hardcodedName2'] = new google.maps.LatLng(lat2, lng2);
twentypoints['hardcodedName3'] = new google.maps.LatLng(lat3, lng3);
...
// calculate the minimum distance
var closestLocName, minDist;
for (var hardcodedName in twentypoints) {
tempMinDist = getDistance(twentypoints[hardcodedName], yourLocation));
if (minDist === undefined || tempMinDist < minDist) {
minDist = tempMinDist;
closestLocName = hardcodedName;
}
}
console.log('Closest location is called ' + closestLocName + '.');
console.log('Closest location is ' + minDist + 'km away.');https://stackoverflow.com/questions/13295358
复制相似问题