mysql空间查询

来源:互联网 发布:数控编程培训教程 编辑:程序博客网 时间:2024/06/18 17:46

先建一个 空间数据表  

CREATE TABLE `points` (  
  `name` varchar(20) NOT NULL DEFAULT '',  
  `location` point NOT NULL,  
  `description` varchar(200) DEFAULT NULL,  
  PRIMARY KEY (`name`),  
  SPATIAL KEY `sp_index` (`location`)  
) ENGINE=MyISAM DEFAULT CHARSET=utf8;


SET @center = GEOMFROMTEXT('POINT(120.140746 30.305061)'); 
        SET @radius = 1000; 
        SET @bbox = CONCAT('POLYGON((', 
        X(@center) - @radius, ' ', Y(@center) - @radius, ',', 
        X(@center) + @radius, ' ', Y(@center) - @radius, ',', 
        X(@center) + @radius, ' ', Y(@center) + @radius, ',', 
        X(@center) - @radius, ' ', Y(@center) + @radius, ',', 
        X(@center) - @radius, ' ', Y(@center) - @radius, '))' 
        ); 
SELECT `id`,`companyname`,`address`, 
        SQRT(POW( ABS( X(location) - X(@center)), 2) + POW( ABS(Y(location) - Y(@center)), 2 )) AS distance 
        FROM `cms_company_info` WHERE 1=1 
        AND INTERSECTS( location, GEOMFROMTEXT(@bbox) ) 
        AND SQRT(POW( ABS( X(location) - X(@center)), 2) + POW( ABS(Y(location) - Y(@center)), 2 )) < @radius 
        ORDER BY distance LIMIT 10



0

现在很多手机软件都用附近搜索功能,但具体是怎么实现的呢》
在网上查了很多资料,mysql空间数据库、矩形算法、geohash我都用过了,当数据上了百万之后mysql空间数据库方法是最强最精确的(查询前100条数据只需5秒左右)。

接下来推出一个原创计算方法,查询速度是mysql空间数据库算法的2倍

$lng是你的经度,$lat是你的纬度

SELECT lng,lat,
        (POWER(MOD(ABS(lng - $lng),360),2) + POWER(ABS(lat - $lat),2)) AS distance 
        FROM `user_location`
        ORDER BY distance LIMIT 100

经测试,在100万数据中取前100条数据只需2.5秒左右。

####################################

另外的几种算法还是在这里展示一下:

一、距形算法

define(EARTH_RADIUS, 6371);//地球半径,平均半径为6371km
 /**
 *计算某个经纬度的周围某段距离的正方形的四个点
 *
 *@param lng float 经度
 *@param lat float 纬度
 *@param distance float 该点所在圆的半径,该圆与此正方形内切,默认值为0.5千米
 *@return array 正方形的四个点的经纬度坐标
 */
 function returnSquarePoint($lng, $lat,$distance = 0.5){

    $dlng =  2 * asin(sin($distance / (2 * EARTH_RADIUS)) / cos(deg2rad($lat)));
    $dlng = rad2deg($dlng);

    $dlat = $distance/EARTH_RADIUS;
    $dlat = rad2deg($dlat);

    return array(
                'left-top'=>array('lat'=>$lat + $dlat,'lng'=>$lng-$dlng),
                'right-top'=>array('lat'=>$lat + $dlat, 'lng'=>$lng + $dlng),
                'left-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng - $dlng),
                'right-bottom'=>array('lat'=>$lat - $dlat, 'lng'=>$lng + $dlng)
                );
 }
//使用此函数计算得到结果后,带入sql查询。
$squares = returnSquarePoint($lng, $lat);
$info_sql = "select id,locateinfo,lat,lng from `lbs_info` where lat<>0 and lat>{$squares['right-bottom']['lat']} and lat<{$squares['left-top']['lat']} and lng>{$squares['left-top']['lng']} and lng<{$squares['right-bottom']['lng']} ";
0 0
原创粉丝点击