【问题标题】:Show nearest locations from database to user's GeoLocation [closed]显示从数据库到用户 GeoLocation 的最近位置 [关闭]
【发布时间】:2014-06-19 04:36:39
【问题描述】:

我正在使用 Google Maps API v3 将数据库中所有存储的位置显示为标记。 我要做的是在地图下方显示一个列表,其中包含最近的位置(假设在 10 公里内)及其名称、描述和到用户当前位置的距离,按距离排序。我不知道如何构建查询。我目前有这段代码,它显示了数据库中的所有位置:

$q = "SELECT name, image, description, price, lat, lng, rating, owner FROM places"; 
        $res1 = mysqli_query($linkNew, $q);

            while($row1 = mysqli_fetch_array($res1)){
                echo "<div class='place'>";
                echo "<h3 class='placeTitle'>" . $row1[0] . "</h2><br />";
                echo "<img src='" . $row1[1] . "' class='placeImage' width='30' height='30' />";    
                echo "<p class='placeDescription'>" .$row1[2] . "</p><br />";
                echo "<p class='placePrice'>€ " .$row1[3] . "/night</p><br />";
                echo "<p class='placeRating'>" .$row1[6] . "/5</p><br />";
                echo "<p class='placeOwner'>Owner: <a href='#'><b>" .$row1[7] . "</b></a></p><br />";
                echo "</div>";
            }       

【问题讨论】:

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


【解决方案1】:
$sql = "SELECT *, ( 3959 * acos( cos( radians(" . $lat . ") ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(" . $lng . ") ) + sin( radians(" . $lat . ") ) * sin( radians( lat ) ) ) ) AS distance FROM your_table HAVING distance < 5";

$lat$lng 是您的中心点的坐标,而 lat/lng 是您的表格列。以上将列出 5 nm 范围内的位置。将3959 替换为6371 以更改为公里。

此链接可能有用:https://developers.google.com/maps/articles/phpsqlsearch_v3

选择用户位置:

if (navigator.geolocation) {

    navigator.geolocation.getCurrentPosition(function(position) {

        userLat = position.coords.latitude;
        userLng = position.coords.longitude;
    });
}

【讨论】:

  • 谢谢!有没有办法以某种方式获取地理位置并在此查询中使用它作为中心点?
  • 查看我编辑的答案。
  • 您似乎提倡将值简单地连接到查询字符串中。这应该避免使用参数化查询,否则你会冒 SQL 注入的风险(当然,如果类型是某种numeric,这会得到缓解......但这是事情的原则)。
  • 这是为了解释如何构建查询。它不应该是安全培训课程。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-05
  • 2016-02-04
  • 1970-01-01
  • 2015-03-25
  • 1970-01-01
  • 2011-09-30
相关资源
最近更新 更多