haversine formula php / mysql

2019-08-29 09:04发布

问题:

I'm trying to get a common database of geo points working with a radius search. I've found several good tutorials on this topic, but I'm failing at the very end.

The main tutorial is here: http://janmatuschek.de/LatitudeLongitudeBoundingCoordinates.

The basic formula, in the form of an SQL query, is

SELECT * FROM Places 
WHERE (Lat => 1.2393 AND Lat <= 1.5532) AND (Lon >= -1.8184 AND Lon <= 0.4221)
AND acos(sin(1.3963) * sin(Lat) + cos(1.3963) * cos(Lat) * cos(Lon - (-0.6981)))
    <= 0.1570;

I've implemented this in a simple PHP test page like this:

$R = 6371; // radius of Earth in KM

$lat = '46.98025235521883'; // lat of center point
$lon = '-110.390625'; // longitude of center point
$distance = 1000; // radius in KM of the circle drawn 
$rad = $distance / $R; // angular radius for query 
$query = '';

// rough cut to exclude results that aren't close
$max_lat = $lat + rad2deg($rad/$R);
$min_lat = $lat - rad2deg($rad/$R);
$max_lon = $lon + rad2deg($rad/$R/cos(deg2rad($lat)));
$min_lon = $lon - rad2deg($rad/$R/cos(deg2rad($lat)));
// this part works just fine!
$query .= '(latitude > ' . $min_lat . ' AND latitude < ' . $max_lat . ')';
$query .= ' AND (longitude > ' . $min_lon . ' AND longitude < ' . $max_lon . ')';
// refining query -- this part returns no results
$query .= ' AND acos(sin('.$lat.') * sin(latitude) + cos('.$lat.') * cos(latitude) *
    cos(longitude - ('.$lon.'))) <= '.$rad;

Am I missing something here? I think I'm following the methodology exactly, but I cannot get the "fine tuning" query to return any results.

回答1:

not sure but :

$R = 6371; // radius of Earth in KM

$lat = '46.98025235521883'; // lat of center point
$lon = '-110.390625'; // longitude of center point
$distance = 1000; // radius in KM of the circle drawn 
$rad = $distance / $R; // angular radius for query 
$query = '';

// rough cut to exclude results that aren't close
$radR = rad2deg($rad/$R);
$max_lat = $lat + radR;
$min_lat = $lat - radR;
$radR = rad2deg($rad/$R/cos(deg2rad($lat)));
$max_lon = $lon + radR;
$min_lon = $lon - radR;
// this part works just fine!
$query .= '(latitude > ' . $min_lat . ' AND latitude < ' . $max_lat . ')';
$query .= ' AND (longitude > ' . $min_lon . ' AND longitude < ' . $max_lon . ')';
// refining query -- this part returns no results
$query .= ' AND acos(sin('.deg2rad($lat).') * sin(radians(latitude)) + cos('.deg2rad($lat).') * cos(radians(latitude)) *
    cos(radians(longitude) - ('.deg2rad($lon).'))) <= '.$rad;