Home > Database > Mysql Tutorial > body text

Here are a few title options, varying in style and focus: **Direct & Informative:** * **How to Find Locations Within a Radius Using MySQL: An Improved Query** * **Accurate Geolocation Search in

Susan Sarandon
Release: 2024-10-26 09:44:03
Original
778 people have browsed it

Here are a few title options, varying in style and focus:

**Direct & Informative:**

* **How to Find Locations Within a Radius Using MySQL: An Improved Query**
* **Accurate Geolocation Search in MySQL: A Query for Finding Locations Within a Radius**

**Q

MySQL Query for Finding Locations Within a Radius

Queries that search for locations within a specified radius are used when dealing with geospatial data. In this case, a query is needed to retrieve all rows within a 25-mile radius of a given latitude and longitude. However, the original query was not returning accurate results for all rows.

Improved Query

The improved query eliminates the incorrect results by using a more accurate formula to calculate the distance between rows:

SELECT
    `id`,
    (
        6371 *
        acos(
            cos( radians( :lat ) ) *
            cos( radians( `lat` ) ) *
            cos(
                radians( `long` ) - radians( :long )
            ) +
            sin(radians(:lat)) *
            sin(radians(`lat`))
        )
    ) `distance`
FROM
    `location`
HAVING
    `distance` < :distance
ORDER BY
    `distance`
LIMIT
    25
Copy after login

Explanation

  • The formula acos( ... ) calculates the angle between two latitude-longitude points.
  • Multiplying this angle by 6371 converts the result to miles.
  • The resulting distance is stored in the distance column.
  • All rows with a distance less than the specified value are selected.

Parameters

  • :lat and :long are the latitude and longitude of the center point.
  • :distance is the desired radius in miles.

Using this improved query, all rows within a specified radius can be accurately retrieved, eliminating the incorrect results seen in the original query.

The above is the detailed content of Here are a few title options, varying in style and focus: **Direct & Informative:** * **How to Find Locations Within a Radius Using MySQL: An Improved Query** * **Accurate Geolocation Search in. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
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!