文章轉載地址 http://blog.sina.com.cn/s/blog_7bbfd5fd01017d1e.html 感謝做者。html
在原文的基礎上,我新增了sql語句,方便你們理解mysql
SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for customer -- ---------------------------- DROP TABLE IF EXISTS `customer`; CREATE TABLE `customer` ( `id` int(11) unsigned NOT NULL auto_increment COMMENT '自增主鍵', `name` varchar(50) NOT NULL COMMENT '名稱', `lon` double(9,6) NOT NULL COMMENT '經度', `lat` double(8,6) NOT NULL COMMENT '緯度', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='商戶表'; -- ---------------------------- -- Records of customer -- ---------------------------- INSERT INTO `customer` VALUES ('1', '天津市區', '117.315575', '39.133462'); INSERT INTO `customer` VALUES ('2', '北京市區', '116.407999', '39.894073'); INSERT INTO `customer` VALUES ('3', '保定', '115.557124', '38.853490'); INSERT INTO `customer` VALUES ('4', '石家莊', '114.646458', '38.072369'); INSERT INTO `customer` VALUES ('5', '昌平區1', '116.367180', '40.009561'); INSERT INTO `customer` VALUES ('6', '海淀區2', '116.313425', '39.973078'); INSERT INTO `customer` VALUES ('7', '海淀區1', '116.329236', '39.987231');
而後咱們開始用mysql自帶的函數,計算customer表中,每一個地方具體。sql
傳入參數 緯度 40.0497810000 經度 116.3424590000
/*傳入的參數爲 緯度 緯度 經度 ASC升序由近至遠 DESC 降序 由遠到近 */ SELECT *, ROUND( 6378.138 * 2 * ASIN( SQRT( POW( SIN( ( 40.0497810000 * PI() / 180 - lat * PI() / 180 ) / 2 ), 2 ) + COS(40.0497810000 * PI() / 180) * COS(lat * PI() / 180) * POW( SIN( ( 116.3424590000 * PI() / 180 - lon * PI() / 180 ) / 2 ), 2 ) ) ) * 1000 ) AS juli FROM customer ORDER BY juli ASC
至此,咱們就能清楚的查看到緯度 40.0497810000 經度 116.3424590000 距離customer表中的每一個地區的距離(單位 m)函數
PS 用到的經緯度查詢工具 http://www.gpsspg.com/maps.htm工具