Recommended Posts

I'm trying to figure out the best way to do a radius search based on latitude and longitude.

What I'm doing that works: I'm loading each record key and lat/long into an array, geocoding the distance from a set point, then sorting the array by that distance. It's pretty heavy - but not bad for the 30 records I'm working with.

What's a better way to do this with hundreds or even thousands of records?

Share on other sites

What are you doing exactly?

Share on other sites

where are you loading information from?  are you trying to do a "zip" code distance type search?

what is your current code look like?

Share on other sites

The end goal is to get the distance of hundreds of different points in the same general geographic area from any random location in the same area on the fly. I'll want to dump the fifteen closest as points on an embedded map api. The distances will be recalculated on map move, and the 15 closest locations will replace the old 15.

I didn't want to muddy this discussion with code, since the code itself isn't the problem (since it works). The problem is I have to call this code for each location in the entire database to establish a distance from my arbitrary location before I can sort out fifteen of them.

Share on other sites

if your using mysql you can try...

```\$lat/\$lon has to be the point from which you want to locate...
\$miles=10; or how many miles you want to radius...
and just limit the result to 15....
SELECT ((ACOS(SIN(\$lat * PI() / 180) * SIN(lat * PI() / 180) + COS(\$lat * PI() / 180) * COS(lat * PI() / 180) * COS((\$lon - lon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS distance FROM members HAVING distance<='\$miles' ORDER BY distance ASC
```

Share on other sites

Very nice! Well, since we're in the math forum, I just have to ask what the difference between your code (which works wonderfully, by the way) and the following code is?

```    SELECT `id`, X(gm_coor) AS `latitude`, Y(gm_coor) AS `longitude`,
ATAN2(
SQRT(
) * 6372.795 AS `distance`
FROM `my_table`
HAVING `distance` < 1```

mine is shorter

Share on other sites

This thread is more than a year old. Are you sure you have something important to add to it?

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

×   Pasted as rich text.   Restore formatting

Only 75 emoji are allowed.