192

経度と緯度の値を取得し、それらを MySQL クエリに入力する、動作する PHP スクリプトがあります。MySQLだけにしたいです。これが私の現在のPHPコードです:

if ($distance != "Any" && $customer_zip != "") { //get the great circle distance

    //get the origin zip code info
    $zip_sql = "SELECT * FROM zip_code WHERE zip_code = '$customer_zip'";
    $result = mysql_query($zip_sql);
    $row = mysql_fetch_array($result);
    $origin_lat = $row['lat'];
    $origin_lon = $row['lon'];

    //get the range
    $lat_range = $distance/69.172;
    $lon_range = abs($distance/(cos($details[0]) * 69.172));
    $min_lat = number_format($origin_lat - $lat_range, "4", ".", "");
    $max_lat = number_format($origin_lat + $lat_range, "4", ".", "");
    $min_lon = number_format($origin_lon - $lon_range, "4", ".", "");
    $max_lon = number_format($origin_lon + $lon_range, "4", ".", "");
    $sql .= "lat BETWEEN '$min_lat' AND '$max_lat' AND lon BETWEEN '$min_lon' AND '$max_lon' AND ";
    }

これを完全にMySQLにする方法を知っている人はいますか? 私はインターネットを少し閲覧しましたが、インターネットに関する文献のほとんどはかなり混乱しています。

4

9 に答える 9

374

Google Code FAQ - PHP、MySQL、Google マップを使用したスト​​ア ロケータの作成から:

以下は、座標 37, -122 から半径 25 マイル以内にある最も近い 20 の場所を見つける SQL ステートメントです。その行の緯度/経度とターゲットの緯度/経度に基づいて距離を計算し、距離の値が 25 未満の行のみを要求し、クエリ全体を距離で並べ替え、結果を 20 に制限します。マイルではなくキロメートルで検索するには、3959 を 6371 に置き換えます。

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) 
* cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin(radians(lat)) ) ) AS distance 
FROM markers 
HAVING distance < 25 
ORDER BY distance 
LIMIT 0 , 20;
于 2009-02-22T11:04:31.847 に答える
34

$greatCircleDistance = acos( cos($latitude0) * cos($latitude1) * cos($longitude0 - $longitude1) + sin($latitude0) * sin($latitude1));

緯度と経度をラジアンで。

それで

SELECT 
  acos( 
      cos(radians( $latitude0 ))
    * cos(radians( $latitude1 ))
    * cos(radians( $longitude0 ) - radians( $longitude1 ))
    + sin(radians( $latitude0 )) 
    * sin(radians( $latitude1 ))
  ) AS greatCircleDistance 
 FROM yourTable;

あなたのSQLクエリです

結果を Km またはマイルで取得するには、結果に地球の平均半径 (3959マイル、6371Km または3440海里)を掛けます。

あなたの例で計算しているのはバウンディングボックスです。座標データを空間対応の MySQL 列に配置すると、 MySQL の組み込み機能を使用してデータをクエリできます。

SELECT 
  id
FROM spatialEnabledTable
WHERE 
  MBRWithin(ogc_point, GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))'))
于 2009-02-22T11:19:48.393 に答える
14

ヘルパー フィールドを座標テーブルに追加すると、クエリの応答時間を改善できます。

このような:

CREATE TABLE `Coordinates` (
`id` INT(10) UNSIGNED NOT NULL COMMENT 'id for the object',
`type` TINYINT(4) UNSIGNED NOT NULL DEFAULT '0' COMMENT 'type',
`sin_lat` FLOAT NOT NULL COMMENT 'sin(lat) in radians',
`cos_cos` FLOAT NOT NULL COMMENT 'cos(lat)*cos(lon) in radians',
`cos_sin` FLOAT NOT NULL COMMENT 'cos(lat)*sin(lon) in radians',
`lat` FLOAT NOT NULL COMMENT 'latitude in degrees',
`lon` FLOAT NOT NULL COMMENT 'longitude in degrees',
INDEX `lat_lon_idx` (`lat`, `lon`)
)    

TokuDB を使用している場合、たとえば次のように、いずれかの述語にクラスタリング インデックスを追加すると、パフォーマンスがさらに向上します。

alter table Coordinates add clustering index c_lat(lat);
alter table Coordinates add clustering index c_lon(lon);

基本的な緯度と経度を度単位で、sin(lat) をラジアン単位で、cos(lat)*cos(lon) をラジアン単位で、cos(lat)*sin(lon) をラジアン単位でそれぞれのポイントに必要とします。次に、次のように mysql 関数を作成します。

CREATE FUNCTION `geodistance`(`sin_lat1` FLOAT,
                              `cos_cos1` FLOAT, `cos_sin1` FLOAT,
                              `sin_lat2` FLOAT,
                              `cos_cos2` FLOAT, `cos_sin2` FLOAT)
    RETURNS float
    LANGUAGE SQL
    DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY INVOKER
   BEGIN
   RETURN acos(sin_lat1*sin_lat2 + cos_cos1*cos_cos2 + cos_sin1*cos_sin2);
   END

これで距離が出ます。

緯度/経度にインデックスを追加することを忘れないでください。バウンディング ボックスが検索を遅くするのではなく、検索に役立つようにします (インデックスは上記の CREATE TABLE クエリに既に追加されています)。

INDEX `lat_lon_idx` (`lat`, `lon`)

緯度/経度座標のみを持つ古いテーブルが与えられた場合、次のように更新するスクリプトを設定できます: (meekrodb を使用した php)

$users = DB::query('SELECT id,lat,lon FROM Old_Coordinates');

foreach ($users as $user)
{
  $lat_rad = deg2rad($user['lat']);
  $lon_rad = deg2rad($user['lon']);

  DB::replace('Coordinates', array(
    'object_id' => $user['id'],
    'object_type' => 0,
    'sin_lat' => sin($lat_rad),
    'cos_cos' => cos($lat_rad)*cos($lon_rad),
    'cos_sin' => cos($lat_rad)*sin($lon_rad),
    'lat' => $user['lat'],
    'lon' => $user['lon']
  ));
}

次に、実際のクエリを最適化して、実際に必要な場合にのみ距離計算を実行します。たとえば、円 (楕円形) を内側と外側から境界付けます。そのためには、クエリ自体のいくつかのメトリックを事前に計算する必要があります。

// assuming the search center coordinates are $lat and $lon in degrees
// and radius in km is given in $distance
$lat_rad = deg2rad($lat);
$lon_rad = deg2rad($lon);
$R = 6371; // earth's radius, km
$distance_rad = $distance/$R;
$distance_rad_plus = $distance_rad * 1.06; // ovality error for outer bounding box
$dist_deg_lat = rad2deg($distance_rad_plus); //outer bounding box
$dist_deg_lon = rad2deg($distance_rad_plus/cos(deg2rad($lat)));
$dist_deg_lat_small = rad2deg($distance_rad/sqrt(2)); //inner bounding box
$dist_deg_lon_small = rad2deg($distance_rad/cos(deg2rad($lat))/sqrt(2));

これらの準備を考えると、クエリは次のようになります (php):

$neighbors = DB::query("SELECT id, type, lat, lon,
       geodistance(sin_lat,cos_cos,cos_sin,%d,%d,%d) as distance
       FROM Coordinates WHERE
       lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d
       HAVING (lat BETWEEN %d AND %d AND lon BETWEEN %d AND %d) OR distance <= %d",
  // center radian values: sin_lat, cos_cos, cos_sin
       sin($lat_rad),cos($lat_rad)*cos($lon_rad),cos($lat_rad)*sin($lon_rad),
  // min_lat, max_lat, min_lon, max_lon for the outside box
       $lat-$dist_deg_lat,$lat+$dist_deg_lat,
       $lon-$dist_deg_lon,$lon+$dist_deg_lon,
  // min_lat, max_lat, min_lon, max_lon for the inside box
       $lat-$dist_deg_lat_small,$lat+$dist_deg_lat_small,
       $lon-$dist_deg_lon_small,$lon+$dist_deg_lon_small,
  // distance in radians
       $distance_rad);

上記のクエリの EXPLAIN は、インデックスをトリガーするのに十分な結果がない限り、インデックスを使用していないと言うかもしれません。インデックスは、座標テーブルに十分なデータがある場合に使用されます。FORCE INDEX (lat_lon_idx) を SELECT に追加して、テーブルのサイズに関係なくインデックスを使用できるようにすることができるため、正しく機能していることを EXPLAIN で確認できます。

上記のコード サンプルを使用すると、最小限のエラーで距離によるオブジェクト検索の実用的でスケーラブルな実装が得られるはずです。

于 2011-09-02T13:54:04.557 に答える
10

私はこれをいくつか詳細に解決しなければならなかったので、結果を共有します。これはとzipテーブルを含むテーブルを使用します。Google マップには依存しません。むしろ、緯度/経度を含む任意のテーブルに適応させることができます。latitudelongitude

SELECT zip, primary_city, 
       latitude, longitude, distance_in_mi
  FROM (
SELECT zip, primary_city, latitude, longitude,r,
       (3963.17 * ACOS(COS(RADIANS(latpoint)) 
                 * COS(RADIANS(latitude)) 
                 * COS(RADIANS(longpoint) - RADIANS(longitude)) 
                 + SIN(RADIANS(latpoint)) 
                 * SIN(RADIANS(latitude)))) AS distance_in_mi
 FROM zip
 JOIN (
        SELECT  42.81  AS latpoint,  -70.81 AS longpoint, 50.0 AS r
   ) AS p 
 WHERE latitude  
  BETWEEN latpoint  - (r / 69) 
      AND latpoint  + (r / 69)
   AND longitude 
  BETWEEN longpoint - (r / (69 * COS(RADIANS(latpoint))))
      AND longpoint + (r / (69 * COS(RADIANS(latpoint))))
  ) d
 WHERE distance_in_mi <= r
 ORDER BY distance_in_mi
 LIMIT 30

そのクエリの途中にある次の行を見てください。

    SELECT  42.81  AS latpoint,  -70.81 AS longpoint, 50.0 AS r

zipこれは、緯度/経度ポイント 42.81/-70.81 から 50.0 マイル以内で、テーブル内の最も近い 30 個のエントリを検索します。これをアプリに組み込むと、そこに独自のポイントと検索半径を配置します。

マイルではなくキロメートルで作業したい場合は、クエリ内で69toおよびto111.045に変更します。3963.176378.10

ここに詳細な書き込みがあります。それが誰かに役立つことを願っています。 http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/

于 2013-07-25T12:19:02.870 に答える
3

上記の回答についてコメントすることはできませんが、@PavelChuchuvaの回答には注意してください。両方の座標が同じである場合、その式は結果を返しません。その場合、distanceはnullであるため、その式をそのまま使用して行が返されることはありません。

私はMySQLの専門家ではありませんが、これは私のために働いているようです:

SELECT id, ( 3959 * acos( cos( radians(37) ) * cos( radians( lat ) ) * cos( radians( lng ) - radians(-122) ) + sin( radians(37) ) * sin( radians( lat ) ) ) ) AS distance 
FROM markers HAVING distance < 25 OR distance IS NULL ORDER BY distance LIMIT 0 , 20;
于 2012-11-24T19:38:43.923 に答える
3

同じことを計算できる手順を書きましたが、それぞれの表に緯度と経度を入力する必要があります。

drop procedure if exists select_lattitude_longitude;

delimiter //

create procedure select_lattitude_longitude(In CityName1 varchar(20) , In CityName2 varchar(20))

begin

    declare origin_lat float(10,2);
    declare origin_long float(10,2);

    declare dest_lat float(10,2);
    declare dest_long float(10,2);

    if CityName1  Not In (select Name from City_lat_lon) OR CityName2  Not In (select Name from City_lat_lon) then 

        select 'The Name Not Exist or Not Valid Please Check the Names given by you' as Message;

    else

        select lattitude into  origin_lat from City_lat_lon where Name=CityName1;

        select longitude into  origin_long  from City_lat_lon where Name=CityName1;

        select lattitude into  dest_lat from City_lat_lon where Name=CityName2;

        select longitude into  dest_long  from City_lat_lon where Name=CityName2;

        select origin_lat as CityName1_lattitude,
               origin_long as CityName1_longitude,
               dest_lat as CityName2_lattitude,
               dest_long as CityName2_longitude;

        SELECT 3956 * 2 * ASIN(SQRT( POWER(SIN((origin_lat - dest_lat) * pi()/180 / 2), 2) + COS(origin_lat * pi()/180) * COS(dest_lat * pi()/180) * POWER(SIN((origin_long-dest_long) * pi()/180 / 2), 2) )) * 1.609344 as Distance_In_Kms ;

    end if;

end ;

//

delimiter ;
于 2011-08-29T04:08:21.610 に答える
2

私のjavascriptの実装は、次のものへの良い参照になると思いました:

/*
 * Check to see if the second coord is within the precision ( meters )
 * of the first coord and return accordingly
 */
function checkWithinBound(coord_one, coord_two, precision) {
    var distance = 3959000 * Math.acos( 
        Math.cos( degree_to_radian( coord_two.lat ) ) * 
        Math.cos( degree_to_radian( coord_one.lat ) ) * 
        Math.cos( 
            degree_to_radian( coord_one.lng ) - degree_to_radian( coord_two.lng ) 
        ) +
        Math.sin( degree_to_radian( coord_two.lat ) ) * 
        Math.sin( degree_to_radian( coord_one.lat ) ) 
    );
    return distance <= precision;
}

/**
 * Get radian from given degree
 */
function degree_to_radian(degree) {
    return degree * (Math.PI / 180);
}
于 2012-04-15T07:57:09.300 に答える