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 896615
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T14:45:23+00:00 2026-05-15T14:45:23+00:00

I’ve got an sql query that pulls locations from a database based on coordinates

  • 0

I’ve got an sql query that pulls locations from a database based on coordinates within a certain range. Now I’m trying to order them by proximity with a bit of math – but no matter how many times im writing it out on paper I can’t seem to figure out a working solution.

lets describe a few variables:

  • $plat (the latitude of the place)
  • $plong (the longitude of the place)
  • $slat (the latitude of the searched location)
  • $slong (the longitude of the searched location)

One big thing to note is that I’ve converted all coordinates to positive numbers and have another feild that determines positive or negative – but for this assume that I’ve already queried the nearby coordinates properly.

In order to order it this way I’ve seen people use “ORDER BY abs(coord-coords)” for something simple -but what I need is something more like:

[($slat – $plat) * ($slong – plong)] – but this causes problems because if the resulting calulation on one side is zero – then after multiplied the result would be zero as well – making it innaccurate.

Any ideas –

  • 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-15T14:45:24+00:00Added an answer on May 15, 2026 at 2:45 pm

    The solution for distance between latitude/longitude coordinates is called the haversine formula. It’s complex because you need to take the curvature of the earth into account unless your distances are very short.

    Here’s an article about using PHP and MySQL to implement a locator app: Creating a Store Locator with PHP, MySQL & Google Maps

    You can also find many other questions here on Stack Overflow regarding calculating distance between coordinates: https://stackoverflow.com/search?q=longitude+distance

    If you only need to calculate distance within 5km, the curvature of the earth is probably not significant. You can use a plain distance formula. You can even skip the square-root calculation if you only need to use this value to sort which one is closer.

    SELECT s.location_id,
      (s.lat-p.lat)*(s.lat-p.lat) + (s.long-p.long)*(s.long-p.long) AS distance_squared
    FROM Locations s, Locations p
    WHERE p.location_id = ?
    ORDER BY distance_squared;
    

    The table (‘locations’) I am selecting from has lat/long coordinates (lets call them $plat and $plong).

    No, those are PHP variables. You need to calculate the distance from the lat/long coordinates on each row of your database table.

    The problem is that SQL normally only calculates things from one row at a time. So you need to have some way of combining two rows into one row, so a calculation can use the coordinates of two locations. You do this with a self-join. This is basically pairing each row with another row from the same table. And that’s why I list Locations twice, and give them two different aliases, s and p (the technical term is correlation name).

    If you’re accustomed to PHP, think of this self-join as analogous to a nested loop:

    foreach ($locations as &$s) {
        foreach ($locations as &$p) {
            // calculate the distance between $s and $p
        }
    }
    

    The WHERE clause restricts the rows of p to just the place you start from (you would substitute a single value for the ? placeholder), so it’s just one row that the query pairs with all the rows of the table.

    Another tip: I skipped using SQRT() because it’s not necessary just to sort by distance. That is, if three locations are 10km, 15km, and 20km from me, then I can sort by 100, 225, and 400 and get the same ordering as if I sort by 10, 15, and 20. The advantage is that I’ve eliminated calculating the square root which reduces the cost of my query somewhat.

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

Sidebar

Related Questions

I've got a string that has curly quotes in it. I'd like to replace
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have a view passing on information from a database: def serve_article(request, id): served_article
I want to count how many characters a certain string has in PHP, but
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
For some reason, after submitting a string like this Jack’s Spindle from a text
I have a jquery bug and I've been looking for hours now, I can't
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
this is what i have right now Drawing an RSS feed into the php,

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.