首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >谷歌地图API搜索

谷歌地图API搜索
EN

Stack Overflow用户
提问于 2012-11-08 18:26:37
回答 1查看 216关注 0票数 0

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

  1. 允许用户输入位置。
  2. 一旦用户单击“查找”按钮,它就会将用户输入的位置转换为经度和纬度同弦。
  3. 在此基础上,提出了一种计算用户进入位置与20个硬编码lng和lat协调距离的算法。
  4. 它将输出以KMs为单位的距离。
  5. 然后,它必须循环通过,找到最低的距离和抓取液化天然气和lat id,所以我知道什么位置是最短的距离。

我已经完成了步骤1和步骤2,但是我无法找到一种方法来存储位置的索引(识别它的方法)以及lng和lat点,这样我就可以循环遍历它们,并将它们与用户输入的位置进行比较。我也想不出找到最短距离的方法,所有的点都能找到最接近的液化天然气和lat。

任何帮助都将不胜感激,

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2012-11-09 00:19:25

我认为你应该能够根据你的目的调整这个答案。

代码语言:javascript
运行
复制
//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.');
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13295358

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档