【问题标题】:Display all locations from database within a given radius显示给定半径内数据库中的所有位置
【发布时间】:2012-08-21 03:39:55
【问题描述】:

我想使用谷歌地图检索并显示给定点具有固定半径的所有位置。

我设法找到了Display Location guide,还看到了许多关于使用 SQL 查询检索它的帖子。 我的数据库包含项目名称、地址(查找 alt、lon)、alt、lon 和描述。 如何使用存储的 alt, lon 仅检索其中的 alt,假设半径为 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? 感谢您提供的任何帮助,我知道这是一个常见问题,但我无法使用现有的解决方案。

我尝试使用显示位置指南 DisplayLocations() 方法,但它对我不起作用,虽然那里显示位置的方式是完美的,只需要排除半径范围之外的位置。

【问题讨论】:

  • 编辑你的帖子而不是评论! :)

标签: javascript google-maps geolocation


【解决方案1】:

对于每个点,您必须计算到中心点的距离(还有一个Google Service)。然后只绘制距离

【讨论】:

  • 虽然这意味着他必须获取他的完整数据库,在 javascript 中加载它并对每个点进行远程调用。我认为自己做一些简单的计算会更有效率,对吧?如果他需要即时的结果,可以通过 AJAX 实现。
【解决方案2】:

可能不完全是您所期望的,但我希望它仍然会有所帮助。 从您发布的链接开始,我认为您正在使用 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);
        });
    });
});

【讨论】:

  • 你能解释一下关于 AJAX 调用的更多信息吗?
  • 你是否使用任何 javascript 库,如 jquery、mootools 等?
  • 甜蜜的选择。我将添加一些示例代码。您将不得不对其进行一些调整以满足您的需求。虽然我希望你能明白。
  • 有点,我是一个菜鸟,你可以说...对不起这个愚蠢的问题,你能解释一下我是如何使用代码的吗?如何从代码中获取结果并在地图中显示?
  • 如果您还没有,请先下载 Firefox 浏览器和“firebug”扩展程序。在许多其他方面,您可以通过执行console.log("hello"); 来调试您想要的任何变量,这将使您的生活更轻松,尤其是在学习时。
猜你喜欢
  • 1970-01-01
  • 2019-01-30
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-28
  • 1970-01-01
  • 2012-05-04
相关资源
最近更新 更多