Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6612343
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T20:05:13+00:00 2026-05-25T20:05:13+00:00

So I have this function to calculate nearest cities based on latitude, longitude and

  • 0

So I have this function to calculate nearest cities based on latitude, longitude and radius parameters.

DELIMITER $$
DROP PROCEDURE IF EXISTS `world_db`.`geolocate_close_cities`$$
CREATE PROCEDURE `geolocate_close_cities`(IN p_latitude DECIMAL(8,2), p_longitude DECIMAL(8,2), IN p_radius INTEGER(5))
BEGIN
        SELECT id, country_id, longitude, latitude, city,
        truncate((degrees(acos( sin(radians(latitude)) 
        * sin(radians(p_latitude)) 
        + cos(radians(latitude)) 
        * cos(radians(p_latitude)) 
        * cos(radians(p_longitude - longitude) ) ) ) 
        * 69.09*1.6),1) as distance 
        FROM cities
        HAVING distance < p_radius
        ORDER BY distance desc;
    END$$

DELIMITER ;

Here’s the structure of my cities table:

> +------------+-------------+------+-----+---------+----------------+ |
> Field      | Type        | Null | Key | Default | Extra          |
> +------------+-------------+------+-----+---------+----------------+ |
> id         | int(11)     | NO   | PRI | NULL    | auto_increment | |
> country_id | smallint(6) | NO   |     | NULL    |                | |
> region_id  | smallint(6) | NO   |     | NULL    |                | |
> city       | varchar(45) | NO   |     | NULL    |                | |
> latitude   | float       | NO   |     | NULL    |                | |
> longitude  | float       | NO   |     | NULL    |                | |
> timezone   | varchar(10) | NO   |     | NULL    |                | |
> dma_id     | smallint(6) | YES  |     | NULL    |                | |
> code       | varchar(4)  | YES  |     | NULL    |                |
> +------------+-------------+------+-----+---------+----------------+

It works very well.

What i’d lke to do (pseudcode) is something like:

SELECT * FROM cities WHERE DISTANCE(SELECT id FROM cities WHERE id={cityId}, {km)) 

and it’ll return me the closest cities.

Any ideas of how I can do this?

At the moment, I just call the function, and then iterate through the ids into an array and then perform a WHEREIN in the city table which obviously isn’t very efficient.

Any help is MUCH appreciated. Thanks.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T20:05:14+00:00Added an answer on May 25, 2026 at 8:05 pm

    If you can limit the maximum distance between your cities and your local position, take advantage of the fact that one minute of latitude (north – south) is one nautical mile.

    Put an index on your latitude table.

    Make yourself a haversine(lat1, lat2, long1, long2, unit) stored function from the haversine formula shown in your question. See below

    Then do this, given mylatitude, mylongitude, and mykm.

    SELECT * 
      from cities a
     where :mylatitude >= a.latitude  - :mykm/111.12
       and :mylatitude <= a.latitude  + :mykm/111.12
       and haversine(:mylatitude,a.latitude,:mylongitude,a.longitude, 'KM') <= :mykm
     order by haversine(:mylatitude,a.latitude,:mylongitude,a.longitude, 'KM')
    

    This will use a latitude bounding box to crudely rule out cities that are too far away from your point. Your DBMS will use an index range scan on your latitude index to quickly pick out the rows in your cities table that are worth considering. Then it will run your haversine function, the one with all the sine and cosine maths, only on those rows.

    I suggest latitude because the on-the-ground distance of longitude varies with latitude.

    Note this is crude. It’s fine for a store-finder, but don’t use it if you’re a civil engineer — the earth has an elliptical shape and the this assumes it’s circular.

    (Sorry about the 111.12 magic number. That’s the number of km in a degree of latitude, that is in sixty nautical miles.)


    See here for a workable distance function.

    Why does this MySQL stored function give different results than to doing the calculation in the query?

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have made this function to calculate color differences in the CIE Lab colorspace,
So I have this function used to calculate statistics (min/max/std/mean). Now the thing is
I have this function twitter_tweets_per_day($user, $rounding = 1) { // Helper function to calculate
I have this custom function to calculate MD5 hash, written in Java. I can't
so i have this function in C to calculate a power, and i'm using
I have this code in the HEAD: <script LANGUAGE=JavaScript> <!-- function calculate(form) { height
I have this code which calculate route between tow places function createDrivingRoute() { $(#nav).html();//CLEAR
I have a function which calculates distance from database records. This function is called
I have this function in my Javascript Code that updates html fields with their
I have this function in my head: <head> window.onload = function(){ var x =

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.