3

So I want to be able to display a list of locations (given by zip code) when a user request all locations within x miles of their current location (given by zip code).

Is there a way to do this:

  1. Directly in mySQL? (i.e. only return locations in database that are within X miles of user's zip code). This would be much more efficient than returning ALL locations to iOS and using MapKit methods to filter out the ones within X miles.
JimmyJammed
  • 9,598
  • 19
  • 79
  • 146

2 Answers2

0

If you have the lat & lng in the database you use a simple query to find the locations within a certain distance.

  • Could you show us a simple query _that doesn't have to search the entire database_? The UK has about 1.2 million zip codes. – gnasher729 Jun 15 '15 at 06:07
0

A very, very simple compromise solution: Each degree latitude equals 111.11 km distance. If you are looking for places x miles apart, the difference in latitude must be less than x * (1.609 / 111.11). So if you start at (LAT, LONG) then all users must have LAT - x * (1.609 / 111.11) <= lat <= LAT + x * (1.609 / 111.11). Use that for a query to MySQL; if you are looking for a distance of 50 miles you will filter out a lot of candidates.

There are better, but more complicated solutions.

You don't need MapKit. Calculating the exact distance is very complicated, but for small distances and not very much precision there's a simple method.

Each degree latitude is 111.111 km. Each degree longitude is 111.111 * cos (latitude) km, where the angle of the cosine is taken in degrees. The distance from (LAT, LONG) to (lat, long) is approximately

sqrt ((LAT - lat)^2 + ((LONG - long) * cos (LAT))^2)
gnasher729
  • 51,477
  • 5
  • 75
  • 98