Home > Database > Mysql Tutorial > body text

Introduction to the method of processing longitude and latitude distances using MySQL's geometry type

不言
Release: 2019-02-01 10:09:04
forward
2836 people have browsed it

This article brings you an introduction to the method of processing longitude and latitude distances using MySQL's geometry type. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Create table

CREATE TABLE `map` (
  `id` int(11) NOT NULL,
  `address` varchar(255) NOT NULL DEFAULT '',
  `location` geometry NOT NULL,
  PRIMARY KEY (`id`),
  SPATIAL KEY `idx_location` (`location`)
)
Copy after login

Insert

INSERT INTO map (id, address, location) VALUES (1, 'somewhere', ST_GeomFromText('POINT(121.366961 31.190049)'));
Copy after login
Note that the ST_GeomFromText function must be used, andPOINT() Inside is: longitude, space, latitude

Query

1. Check the latitude and longitude

SELECT address, ST_AsText(location) AS location FROM map;
Copy after login

2. Calculate the distance between two points

SELECT ST_Distance_Sphere(POINT(121.590347, 31.388094),location) AS distant FROM map;
Copy after login
The calculated result, the unit is meters
Note that the longitude and latitude in POINT() are now separated by commas

3. Query locations less than 1000m away, and sort them from far to near

SELECT id, address, ST_Distance_Sphere(POINT(121.590347, 31.388094),location) AS distant FROM map WHERE ST_Distance_Sphere(POINT(121.590347, 31.388094),location) < 1000 ORDER BY distant;
Copy after login

The above is the detailed content of Introduction to the method of processing longitude and latitude distances using MySQL's geometry type. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!