Question

I been following this example for Geo search in MySQL(Really great tutorial!).

This is what I came up with:

CREATE DEFINER=`root`@`localhost` PROCEDURE `geo_distance`(in _location_id bigint(20), in dist int)
BEGIN
declare mylon double; 
declare mylat double;
declare lon1 float; 
declare lon2 float;
declare lat1 float; 
declare lat2 float;

-- get the original lon and lat for the userid 
select longitude, latitude into mylon, mylat from locations where locations.location_id = _location_id;
-- calculate lon and lat for the rectangle:
set lon1 = mylon - dist / abs(cos(radians(mylat)) * 69);
set lon2 = mylon + dist / abs(cos(radians(mylat)) * 69);
set lat1 = mylat - (dist / 69);
set lat2 = mylat + (dist / 69);

-- run the query:
SELECT destination.*,
3956 * 2 * ASIN(SQRT(POWER(SIN((orig.lat - dest.lat) * pi()/180 / 2), 2) +
COS(orig.lat * pi()/180) * COS(dest.lat * pi()/180) * POWER(SIN((orig.lon -dest.lon) * pi()/180 / 2), 2) )) as distance FROM locations destination, locations origin WHERE origin.location_id=_location_id
and destination.longitude between lon1 and lon2 and destination.latitude between lat1 and lat2 
having distance < dist ORDER BY Distance limit 10;
END

The problem is that I don't know what is orig.lat and where did he took it, perhaps I am missing some thing. Can you point me on my mistake or suggest me a good source for Geo search in MySql

Was it helpful?

Solution

The SELECT query that is being built here is to find locations that are close (within 10 units) to a point - let's call it x

orig is point x, then for each record on the database, you're comparing with orig the lat and lon values to see if it's close enough to load.

In practise, let's say you're loading a list of nightclubs nearby for a user, orig is likely to be determined by the user typing in their postcode, or something similar...

If you are still confused, let me know and I can try to help more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top