在给定的半径范围内显示数据库中的所有位置

3
使用谷歌地图,我希望能够检索并显示给定点固定半径内的所有位置。
我已经找到了显示位置指南,也看到了许多关于使用SQL查询检索它的帖子。我的数据库包含物品名称、地址(查找alt、lon)、alt、lon和描述。
如何使用存储的alt、lon仅检索50公里半径内的位置。
以下是我的代码:
javascript
function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(31.046051, 34.85161199999993);
    var myOptions = {
        zoom: 7,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}

function updateCoordinates(latlng)
{
  if(latlng) 
  {
    document.getElementById('lat').value = latlng.lat();
    document.getElementById('lng').value = latlng.lng();
  }
}

function codeAddress() {
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            updateCoordinates(results[0].geometry.location);
            if (marker) marker.setMap(null);
            marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                draggable: true
            });

            google.maps.event.addListener(marker, "dragend", function() {
                updateCoordinates(marker.getPosition());
            });

        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
}

  

  
  function showPositionCoupons(sentlat, sentlon)
  {
  lat=sentlat;
  lon=sentlon;
  latlon=new google.maps.LatLng(lat, lon)
  mapholder=document.getElementById('map_canvas')

  var myOptions={
  center:latlon,zoom:14,
  mapTypeId:google.maps.MapTypeId.ROADMAP,
  mapTypeControl:false,
  };
  map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
  marker = new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
  }

我认为我需要在循环中使用showPositionCoupons(),同时读取alt和lon。感谢提供任何帮助,我知道这是一个频繁的问题,但我无法使用现有内容解决它。
我尝试使用Display Location指南中的DisplayLocations()方法,但它对我不起作用,尽管那里呈现位置的方式非常完美,只需要排除超出半径范围的位置。

4
改善你的帖子,不要留评论! :) - starbeamrainbowlabs
2个回答

4

可能不是您期望的内容,但我希望它仍然能有所帮助。从您发布的链接中可以看出,您正在使用PHP/MySQL。

如果确实如此,我建议只使用PHP/MySQL来获取正确的结果,然后在Google地图上显示它们。

如果您可以在不需要外部服务的情况下进行计算,则效率会高得多。

// PHP/MySQL code
$sourceLat = '';
$sourceLon = '';
$radiusKm  = 50;

$proximity = mathGeoProximity($sourceLat, $sourceLon, $radiusKm);
$result    = mysql_query("
    SELECT * 
    FROM   locations
    WHERE  (lat BETWEEN " . number_format($proximity['latitudeMin'], 12, '.', '') . "
            AND " . number_format($proximity['latitudeMax'], 12, '.', '') . ")
      AND (lon BETWEEN " . number_format($proximity['longitudeMin'], 12, '.', '') . "
            AND " . number_format($proximity['longitudeMax'], 12, '.', '') . ")
");

// fetch all record and check wether they are really within the radius
$recordsWithinRadius = array();
while ($record = mysql_fetch_assoc($result)) {
    $distance = mathGeoDistance($sourceLat, $sourceLon, $record['lat'], $record['lon']);

    if ($distance <= $radiusKm) {
        $recordsWithinRadius[] = $record;
    }
}

// and then print your results using a google map
// ...


// calculate geographical proximity
function mathGeoProximity( $latitude, $longitude, $radius, $miles = false )
{
    $radius = $miles ? $radius : ($radius * 0.621371192);

    $lng_min = $longitude - $radius / abs(cos(deg2rad($latitude)) * 69);
    $lng_max = $longitude + $radius / abs(cos(deg2rad($latitude)) * 69);
    $lat_min = $latitude - ($radius / 69);
    $lat_max = $latitude + ($radius / 69);

    return array(
        'latitudeMin'  => $lat_min,
        'latitudeMax'  => $lat_max,
        'longitudeMin' => $lng_min,
        'longitudeMax' => $lng_max
    );
}

// calculate geographical distance between 2 points
function mathGeoDistance( $lat1, $lng1, $lat2, $lng2, $miles = false )
{
    $pi80 = M_PI / 180;
    $lat1 *= $pi80;
    $lng1 *= $pi80;
    $lat2 *= $pi80;
    $lng2 *= $pi80;

    $r = 6372.797; // mean radius of Earth in km
    $dlat = $lat2 - $lat1;
    $dlng = $lng2 - $lng1;
    $a = sin($dlat / 2) * sin($dlat / 2) + cos($lat1) * cos($lat2) * sin($dlng / 2) * sin($dlng / 2);
    $c = 2 * atan2(sqrt($a), sqrt(1 - $a));
    $km = $r * $c;

    return ($miles ? ($km * 0.621371192) : $km);
}

然后根据您的需求处理结果。如果您需要即时处理,甚至可以通过Ajax调用实现此解决方案。

更新:如何将记录输出为json格式

// add this to the above php script
header('Content-type: application/json');
echo json_encode( $recordsWithinRadius );
exit();

更新:如何通过jQuery的AJAX调用加载json
// javascript/jquery code
$(document).ready(function()
{
    $.getJSON('http://yourserver/yourscript.php', function(data)
    {
        $.each(data, function(key, record) {
            // do something with record data
            console.log(record);
        });
    });
});

好的选择。我会添加一些示例代码。你需要稍微调整一下以适应你的需求。但我希望你能理解这个想法。 - Maurice
我有点菜,正如你所看到的...对于这个愚蠢的问题,抱歉。你能解释一下我如何使用这段代码吗?如何从代码中获取结果并在地图上显示它们? - Shahar Galukman
别担心,每个人都是从零开始的。不过你选择了一个有点雄心壮志的项目啊 ;-) - Maurice
1
如果你还没有,首先下载Firefox浏览器和“firebug”扩展程序。除了许多其他功能外,您可以通过执行console.log(“hello”); 来调试任何变量。这将使你的生活更轻松,特别是在学习时。 - Maurice
通过在 Javascript 代码中添加 console.log("something"); 来尝试找出错误所在。例如,在第一个 { 后面放置它以检查是否加载了主函数,然后在第二个 { 处放置它以检查是否加载了 foreach 循环。Javascript 可能找不到 PHP 文件。您是否更改了 'http://yourserver/yourscript.php'? - Maurice
显示剩余6条评论

1

对于每个点,您需要计算到中心点的距离(也可以使用Google服务)。然后只绘制距离<=50公里的点。


虽然这意味着他将不得不获取他完整的数据库,加载它到JavaScript中,并为每个点执行远程调用。我认为自己进行一些简单的计算更加高效,对吗?如果他需要实时结果,可以通过AJAX实现。 - Maurice

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接