【问题标题】:Finding nearest listed (array?) city from known location从已知位置查找最近的列出(数组?)城市
【发布时间】:2012-12-16 05:04:11
【问题描述】:

我希望将 HTML5 地理定位功能集成到网站中。我遇到的问题是在所选列表中获取最近的城市/城镇。该站点仅在一定数量的城镇和引用中受到支持/营销,因此其想法是浏览器找到他们的位置并选择他们最近的城镇或城市。听起来很简单,但它是“找到最近的”,我可以理解。

我找到了一个线程,它帮助我完成了从浏览器获取 long/lat 并将其转换为他们的城镇/城市名称的过程,但这无助于找到最近列出的名称:Reverse Geocoding With Google Map API And PHP To Get Nearest Location Using Lat,Long coordinates

是否有任何 API(最好在 Google 中)可以找到最近的列出位置?我看了看,找不到任何一种。

【问题讨论】:

  • 如果你没有成千上万个城市,你不能只计算距离,然后选择最小的一个吗?

标签: php javascript jquery google-maps google-maps-api-3


【解决方案1】:

您可以使用Haversine 公式找到最近的城市。以下函数用于计算地理坐标与数组坐标之间的距离

function deg2rad(degrees){
radians = degrees * (Math.PI/180);
return radians;
}

function Haversine(lat1,lon1,lat2,lon2) {
  deltaLat = lat2 - lat1 ;
  deltaLon = lon2 - lon1 ;
  earthRadius = 3959; // in miles 6371 in meters.
  alpha    = deltaLat/2;
  beta     = deltaLon/2;
  a        = Math.sin(deg2rad(alpha)) * Math.sin(deg2rad(alpha)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.sin(deg2rad(beta)) * Math.sin(deg2rad(beta)) ;
  c        = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  distance =  earthRadius * c;
  return distance.toFixed(2);
}

【讨论】:

    【解决方案2】:

    我认为最简单的解决方案是将每个城镇或城市的 lat lng 坐标存储在数据库中,然后围绕用户位置进行基于半径的搜索并产生最接近的结果。

    查看此问题的已接受答案。

    Search database with lat and long by radius using php mysql

    【讨论】:

      【解决方案3】:

      最简单的方法是使用haversine formulacomputeDistanceBetween method of the spherical geometry library 计算从用户位置到您所有城市的“如乌鸦飞”的距离,然后选择最小的那个。

      如果您的地点少于 100 个,您可以使用Distance Matrix 确定最短行驶距离,然后选择结果最短的城镇。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-27
        • 2023-03-20
        • 1970-01-01
        相关资源
        最近更新 更多