简体   繁体   English

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

[英]Display all locations from database within a given radius

Using google maps I would like to retrieve and display all locations withing a fixed radius of a given point. 使用谷歌地图我想检索并显示具有给定点的固定半径的所有位置。

I've managed to find Display Location guide and also saw numerous posts regarding retrieving it using SQL query. 我已经设法找到显示位置指南,并且还看到了许多关于使用SQL查询检索它的帖子。 My database containing, name of the item, address (to find alt,lon), alt, lon and description. 我的数据库包含项目名称,地址(查找alt,lon),alt,lon和description。 How do I use the stored alt, lon to retrieve only the ones in, let's say 50km radius. 我如何使用存储的alt,lon来仅检索其中的半径,比如半径为50km。

Here is my code: 这是我的代码:

javascript 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!"});
  }

I think I need to use showPositionCoupons() in a loop maybe, while reading alt and lon? 我想我需要在循环中使用showPositionCoupons() ,同时阅读alt和lon? Thanks for any help given, I know it's frequent question yet I couldn't manage to solve it using what exists. 感谢您提供的任何帮助,我知道这是一个经常出现的问题但我无法使用现有的方法来解决它。

I've tried to use Display Location guide DisplayLocations() method, yet it didn't work for me, though the way the locations presented there is perfect, only need to exclude the ones out of radius bounds. 我曾尝试使用Display Location指南DisplayLocations()方法,但它对我来说不起作用,虽然位置在那里呈现的方式是完美的,只需要排除半径范围外的那些。

Might not exactly be what you where expecting, but I hope it might help nonetheless. 可能不完全是你所期待的,但我希望它可能会有所帮助。 Going from the link you've posted, I take you're using PHP/MySQL. 从你发布的链接开始,我带你使用PHP / MySQL。

And if that's true, I would just use PHP/MySQL to fetch the correct results, and then afterwards display them on a Google map. 如果这是真的,我会使用PHP / MySQL来获取正确的结果,然后在Google地图上显示它们。

Much more efficient if you can do the calculations without needing an external service. 如果您可以在不需要外部服务的情况下进行计算,效率会更高。

// 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);
}

And then do with the results what you want. 然后用你想要的结果做。 You can even implement this solution via an AJAX call if you'd need it on the fly. 如果您需要它,您甚至可以通过AJAX调用实现此解决方案。

UPDATE: How to output records as json 更新:如何将记录输出为json

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

UPDATE: How to load the json via an AJAX call in jquery 更新:如何通过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);
        });
    });
});

For each point you have to calculate the distance to your center-point (There's also a Google Service for that). 对于每个点,您必须计算到中心点的距离(还有一个Google服务 )。 Then only draw points with distance <= 50km. 然后只绘制距离<= 50km的点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM