查询两点间隔距离

1.创建测试表

 
  1. CREATE TABLE `location` (

  2. `id` int(10) unsigned NOT NULL AUTO_INCREMENT,

  3. `name` varchar(50) NOT NULL,

  4. `longitude` decimal(13,10) NOT NULL,

  5. `latitude` decimal(13,10) NOT NULL,

  6. PRIMARY KEY (`id`),

  7. KEY `long_lat_index` (`longitude`,`latitude`)

  8. ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.插入测试数据

 
  1. insert into location(name,longitude,latitude) values

  2. ('广州东站',113.332264,23.156206),

  3. ('林和西',113.330611,23.147234),

    扫描二维码关注公众号,回复: 4474883 查看本文章
  4. ('天平架',113.328095,23.165376);

  5.  
  6. mysql> select * from `location`;

  7. +----+--------------+----------------+---------------+

  8. | id | name | longitude | latitude |

  9. +----+--------------+----------------+---------------+

  10. | 1 | 广州东站 | 113.3322640000 | 23.1562060000 |

  11. | 2 | 林和西 | 113.3306110000 | 23.1472340000 |

  12. | 3 | 天平架 | 113.3280950000 | 23.1653760000 |

  13. +----+--------------+----------------+---------------+

3.搜寻1公里内的数据

搜寻点坐标:时代广场 113.323568, 23.146436

6370.996公里为地球的半径

计算球面两点坐标距离公式

 
  1. C = sin(MLatA)sin(MLatB)cos(MLonA-MLonB) + cos(MLatA)cos(MLatB)

  2. Distance = RArccos(C)*Pi180

根据计算公式得到查询语句如下:

 
  1. select * from `location` where (

  2. acos(

  3. sin(([#latitude#]*3.1415)/180) * sin((latitude*3.1415)/180) +

  4. cos(([#latitude#]*3.1415)/180) * cos((latitude*3.1415)/180) * cos(([#longitude#]*3.1415)/180 - (longitude*3.1415)/180)

  5. )*6370.996

  6. )<=1;

执行查询:

 
  1. mysql> select * from `location` where (

  2. -> acos(

  3. -> sin((23.146436*3.1415)/180) * sin((latitude*3.1415)/180) +

  4. -> cos((23.146436*3.1415)/180) * cos((latitude*3.1415)/180) * cos((113.323568*3.1415)/180 - (longitude*3.1415)/180)

  5. -> )*6370.996

  6. -> )<=1;

  7. +----+-----------+----------------+---------------+

  8. | id | name | longitude | latitude |

  9. +----+-----------+----------------+---------------+

  10. | 2 | 林和西 | 113.3306110000 | 23.1472340000 |

  11. +----+-----------+----------------+---------------+

猜你喜欢

转载自blog.csdn.net/weixin_33207551/article/details/84967091