0

我目前正在开发一个使用 google maps API 的 Javascript 程序。它需要做什么:

  1. 允许用户输入位置。
  2. 一旦用户单击“查找”按钮,它将用户输入的位置转换为经度和纬度坐标。
  3. 然后它运行一个算法来计算用户输入的位置和 20 个硬编码的 lng 和 lat 坐标之间的距离。
  4. 它将以公里为单位输出距离。
  5. 然后它必须循环并找到最短距离并获取 lng 和 lat id,这样我就知道哪个位置是最短距离。

我已经完成了第 1 步和第 2 步,但我找不到存储位置索引(识别它的方法)以及 lng 和 lat 点的方法,以便我可以遍历它们并将它们与用户输入的位置。我也想不出一种方法来找到最短距离的所有点都可以找到最近的 lng 和 lat。

任何帮助,将不胜感激,

谢谢!

4

1 回答 1

0

我认为您应该能够根据您的目的调整此答案。

//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.');
于 2012-11-09T00:19:25.670 回答