Home >Database >Mysql Tutorial >How to Find the Nearest Geographic Record Within a Specified Radius Using Latitude and Longitude?

How to Find the Nearest Geographic Record Within a Specified Radius Using Latitude and Longitude?

Susan Sarandon
Susan SarandonOriginal
2025-01-18 16:07:13922browse

How to Find the Nearest Geographic Record Within a Specified Radius Using Latitude and Longitude?

Determine the distance in the latitude and longitude database

Given latitude and longitude coordinates, the task is to retrieve the record with the nearest matching latitude and longitude from the database while ensuring that the distance remains within a specified threshold. If the distance exceeds the specified limit, no records should be returned.

The table structure provided includes columns for longitude, latitude, and other location-related information. To do this we use the following SQL query:

<code class="language-sql">SELECT latitude, longitude, SQRT(
    POW(69.1 * (latitude - [startlat]), 2) +
    POW(69.1 * ([startlng] - longitude) * COS(latitude / 57.3), 2)) AS distance
FROM TableName HAVING distance < [radius]</code>

In this query, [startlat] and [startlng] represent the starting coordinates of the measured distance. Distance calculations are performed using Haversine's formula, which accurately determines the distance between two points on a sphere (in this case, the Earth). The POW() function squares the difference between the start and target coordinates, and the COS() function takes the curvature of the Earth into account. The end result is the distance in miles.

By including the HAVING clause with the condition "distance < [radius]" we ensure that only records whose distance is less than the specified radius [radius] are returned.

The above is the detailed content of How to Find the Nearest Geographic Record Within a Specified Radius Using Latitude and Longitude?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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