Table of Contents
1. Store Geographical Data Using Spatial Data Types
2. Performance Distance-Based Searches
3. Use Bounding Box for Faster Filtering
4. Search Within a Polygon (eg, a City Boundary)
Home Database Mysql Tutorial How to perform a geographical search with spatial data in MySQL?

How to perform a geographical search with spatial data in MySQL?

Aug 04, 2025 am 02:45 AM

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.

How to perform a geographic search with spatial data in MySQL?

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.

How to perform a geographic search with spatial data in MySQL?

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 the coord column improves performance for spatial queries.

Insert sample data:

How to perform a geographic search with spatial data in MySQL?
 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).

How to perform a geographic search with spatial data in MySQL?

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(&#39;POLYGON((-74.0367 40.7080, -74.0367 40.8080, 
                                   -73.9367 40.8080, -73.9367 40.7080, 
                                   -74.0367 40.7080))&#39;, 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 = &#39;POLYGON((-74 40.7, -74 40.8, -73.9 40.8, -73.9 40.7, -74 40.7))&#39;;

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 , and ST_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!

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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1594
276
How to audit database activity in MySQL? How to audit database activity in MySQL? Aug 05, 2025 pm 01:34 PM

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

Securing MySQL with Object-Level Privileges Securing MySQL with Object-Level Privileges Jul 29, 2025 am 01:34 AM

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

Optimizing MySQL for Financial Data Storage Optimizing MySQL for Financial Data Storage Jul 27, 2025 am 02:06 AM

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.

How to use check constraints to enforce data rules in MySQL? How to use check constraints to enforce data rules in MySQL? Aug 06, 2025 pm 04:49 PM

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

How to implement a tagging system in a MySQL database? How to implement a tagging system in a MySQL database? Aug 05, 2025 am 05:41 AM

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

Best Practices for Managing Large MySQL Tables Best Practices for Managing Large MySQL Tables Aug 05, 2025 am 03:55 AM

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.

How to show all databases in MySQL How to show all databases in MySQL Aug 08, 2025 am 09:50 AM

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

How to add a primary key to an existing table in MySQL? How to add a primary key to an existing table in MySQL? Aug 12, 2025 am 04:11 AM

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

See all articles