mysql空间经纬度_mysql gis 空间数据库 根据 经纬度查找附近

先建一个 空间数据表

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

现在很多手机软件都用附近搜索功能,但具体是怎么实现的呢》 在网上查了很多资料,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']['lng']} and lng


版权声明:本文为weixin_36104484原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。