How to perform a geographical search with spatial data in MySQL?
To perform geographic search, you need to use MySQL's spatial data types and functions. 1. Use the POINT type to store latitude and longitude and create SPATIAL INDEX of SRID 4326; 2. Use the ST_Distance_Sphere function to find the location within the specified radius, in meters; 3. To improve performance, first use MBRContains combined with bounding box filtering and then calculate the exact distance; 4. When searching for points in polygon areas, use the ST_Within function to determine whether the points are within the range; be sure to set the SRID correctly and upgrade to MySQL 8.0 to obtain better spatial support, and ultimately, various geographic queries can be efficiently implemented.
MySQL supports spatial data types and functions that allow you to store and query geographic data, such as points, lines, and polygons. Performing a geographic search—like finding locations within a certain distance or area—can be done using spatial functions. Here's how to set up and perform such searches effectively.

1. Store Geographical Data Using Spatial Data Types
Use the POINT
data type to store latitude and longitude coordinates. For example:
CREATE TABLE locations ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100), coord POINT SRID 4326, -- WGS84 (standard for GPS) SPATIAL INDEX(coord) );
-
SRID 4327
specifies the coordinate system (WGS84 for Earth coordinates). - A
SPATIAL INDEX
on thecoord
column improves performance for spatial queries.
Insert sample data:

INSERT INTO locations (name, coordinate) VALUES ('Central Park', POINT(-73.9654, 40.7829)), ('Empire State', POINT(-73.9857, 40.7484));
2. Performance Distance-Based Searches
To find locations within a certain radius (eg, 10 kilometers), use ST_Distance_Sphere()
, which calculates distance in meters on a sphere:
SELECT name, ST_Distance_Sphere(coord, POINT(-73.9867, 40.7580)) AS distance FROM locations WHERE ST_Distance_Sphere(coord, POINT(-73.9867, 40.7580)) <= 10000;
This finds all locations within 10 km (10,000 meters) of a reference point (eg, Times Square).

Note:
ST_Distance_Sphere()
returns distance in meters, so compare accordingly.
3. Use Bounding Box for Faster Filtering
For better performance, especially on large datasets, first filter using a bounding box before applying precision distance checks:
SELECT name, ST_Distance_Sphere(coord, POINT(-73.9867, 40.7580)) AS distance FROM locations WHERE MBRContains( ST_GeomFromText('POLYGON((-74.0367 40.7080, -74.0367 40.8080, -73.9367 40.8080, -73.9367 40.7080, -74.0367 40.7080))', 4326), coord ) HAVING distance <= 10000;
-
MBRContains()
checks if a point is in a minimum bounding rectangle. - This uses the spatial index efficiently to reduce the number of rows before calculating exact distances.
4. Search Within a Polygon (eg, a City Boundary)
If you have a geographic boundary (like a city or zone), use ST_Within()
:
SET @city_boundary = 'POLYGON((-74 40.7, -74 40.8, -73.9 40.8, -73.9 40.7, -74 40.7))'; SELECT name FROM locations WHERE ST_Within(coord, ST_GeomFromText(@city_boundary, 4326));
This returns all points that lie inside the defined polygon.
A few practical tips:
- Always assign the correct
SRID
(usually 4326 for GPS data). - Use
ST_SRID()
to check or set SRID explicitly if needed. - Spatial indexes only work with certain functions like
MBRContains
,ST_Within
, andST_Distance_Sphere
in newer MySQL versions (8.0 ). - In MySQL 8.0, spatial support is significantly improved—upgrade if possible.
Basically, store your data with POINT
, index it, and use spatial functions like ST_Distance_Sphere
or ST_Within
depending on your search type. Not complicated once set up right, but easy to misconfigure if SRID or indexing is ignored.
The above is the detailed content of How to perform a geographical search with spatial data in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

UseMySQLEnterpriseAuditPluginifonEnterpriseEditionbyenablingitinconfigurationwithserver-audit=FORCE_PLUS_PERMANENTandcustomizeeventsviaserver_audit_events;2.Forfreealternatives,usePerconaServerorMariaDBwiththeiropen-sourceauditpluginslikeaudit_log;3.

TosecureMySQLeffectively,useobject-levelprivilegestolimituseraccessbasedontheirspecificneeds.Beginbyunderstandingthatobject-levelprivilegesapplytodatabases,tables,orcolumns,offeringfinercontrolthanglobalprivileges.Next,applytheprincipleofleastprivile

MySQL needs to be optimized for financial systems: 1. Financial data must be used to ensure accuracy using DECIMAL type, and DATETIME is used in time fields to avoid time zone problems; 2. Index design should be reasonable, avoid frequent updates of fields to build indexes, combine indexes in query order and clean useless indexes regularly; 3. Use transactions to ensure consistency, control transaction granularity, avoid long transactions and non-core operations embedded in it, and select appropriate isolation levels based on business; 4. Partition historical data by time, archive cold data and use compressed tables to improve query efficiency and optimize storage.

MySQL supports CHECK constraints to force domain integrity, effective from version 8.0.16; 1. Add constraints when creating a table: Use CREATETABLE to define CHECK conditions, such as age ≥18, salary > 0, department limit values; 2. Modify the table to add constraints: Use ALTERTABLEADDCONSTRAINT to limit field values, such as name non-empty; 3. Use complex conditions: support multi-column logic and expressions, such as end date ≥start date and completion status must have an end date; 4. Delete constraints: use ALTERTABLEDROPCONSTRAINT to specify the name to delete; 5. Notes: MySQL8.0.16, InnoDB or MyISAM needs to be quoted

Useamany-to-manyrelationshipwithajunctiontabletolinkitemsandtagsviathreetables:items,tags,anditem_tags.2.Whenaddingtags,checkforexistingtagsinthetagstable,insertifnecessary,thencreatemappingsinitem_tagsusingtransactionsforconsistency.3.Queryitemsbyta

When dealing with large tables, MySQL performance and maintainability face challenges, and it is necessary to start from structural design, index optimization, table sub-table strategy, etc. 1. Reasonably design primary keys and indexes: It is recommended to use self-increment integers as primary keys to reduce page splits; use overlay indexes to improve query efficiency; regularly analyze slow query logs and delete invalid indexes. 2. Rational use of partition tables: partition according to time range and other strategies to improve query and maintenance efficiency, but attention should be paid to partitioning and cutting issues. 3. Consider reading and writing separation and library separation: Read and writing separation alleviates the pressure on the main library. The library separation and table separation are suitable for scenarios with a large amount of data. It is recommended to use middleware and evaluate transaction and cross-store query problems. Early planning and continuous optimization are the key.

To display all databases in MySQL, you need to use the SHOWDATABASES command; 1. After logging into the MySQL server, you can execute the SHOWDATABASES; command to list all databases that the current user has permission to access; 2. System databases such as information_schema, mysql, performance_schema and sys exist by default, but users with insufficient permissions may not be able to see it; 3. You can also query and filter the database through SELECTSCHEMA_NAMEFROMinformation_schema.SCHEMATA; for example, excluding the system database to only display the database created by users; make sure to use

To add a primary key to an existing table, use the ALTERTABLE statement with the ADDPRIMARYKEY clause. 1. Ensure that the target column has no NULL value, no duplication and is defined as NOTNULL; 2. The single-column primary key syntax is ALTERTABLE table name ADDPRIMARYKEY (column name); 3. The multi-column combination primary key syntax is ALTERTABLE table name ADDPRIMARYKEY (column 1, column 2); 4. If the column allows NULL, you must first execute MODIFY to set NOTNULL; 5. Each table can only have one primary key, and the old primary key must be deleted before adding; 6. If you need to increase it yourself, you can use MODIFY to set AUTO_INCREMENT. Ensure data before operation
