How to measure distance using Haversine formula with MySQL? - mysql

I get Latitude and Longitudes from Google Maps Reverse-Geocoding API and then I need something like this:
mysql_query("SELECT users.*, ".mysql_distance_column($lat,$lng)." FROM users ORDER BY DISTANCE";
function mysql_distance_column($lat=40 , $lng=-73) {
$defaultLatitudeColumn = 'user_lat';
$defaultLongitudeColumn='user_lng';
$defaultColumnName='user_distance';
return "((
(3956 * 2 * ASIN(SQRT( POWER(SIN(({$lat} - abs({$defaultLatitudeColumn}))
* pi()/180 / 2), 2) + COS({$lat} * pi()/180 )
* COS(abs({$defaultLatitudeColumn}) * pi()/180)
* POWER(SIN(({$lng} - {$defaultLongitudeColumn}) * pi()/180 / 2), 2) ))
)) ) as {$defaultColumnName} ";
}
UPDATE
I cant ge this to work
delimiter //
CREATE FUNCTION `GeoDistMiles`( lat1 FLOAT (10,6), lon1 FLOAT (10,6), lat2 FLOAT (10,6), lon2 FLOAT (10,6) )
RETURNS FLOAT
DETERMINISTIC
NO SQL
BEGIN
DECLARE pi, q1, q2, q3 FLOAT (10,6);
DECLARE rads FLOAT (10,6) DEFAULT 0;
SET pi = PI();
SET lat1 = lat1 * pi / 180;
SET lon1 = lon1 * pi / 180;
SET lat2 = lat2 * pi / 180;
SET lon2 = lon2 * pi / 180;
SET q1 = COS(lon1-lon2);
SET q2 = COS(lat1-lat2);
SET q3 = COS(lat1+lat2);
SET rads = ACOS( 0.5*((1.0+q1)*q2 - (1.0-q1)*q3) );
RETURN 3963.346 * rads;
END

Here is the formula I use. Remember that the Earth is not a perfect sphere, so the results will never be perfect.
CREATE DEFINER=`root`#`localhost` FUNCTION `GeoDistMiles`( lat1 FLOAT, lon1 FLOAT, lat2 FLOAT, lon2 FLOAT ) RETURNS float
BEGIN
DECLARE pi, q1, q2, q3 FLOAT;
DECLARE rads FLOAT DEFAULT 0;
SET pi = PI();
SET lat1 = lat1 * pi / 180;
SET lon1 = lon1 * pi / 180;
SET lat2 = lat2 * pi / 180;
SET lon2 = lon2 * pi / 180;
SET q1 = COS(lon1-lon2);
SET q2 = COS(lat1-lat2);
SET q3 = COS(lat1+lat2);
SET rads = ACOS( 0.5*((1.0+q1)*q2 - (1.0-q1)*q3) );
RETURN 3963.346 * rads;
END

I assume that you are trying to use http://en.wikipedia.org/wiki/Haversine_formula.
This is lightly tested, but I think that your formula should be:
(ROUND((3956 * 2 * ASIN(SQRT(POWER(SIN(({$lat} - {$defaultLatitudeColumn}) * pi() / 180 / 2), 2) + COS({$lat} * pi()/180 ) * COS({$defaultLatitudeColumn} * pi()/180) *POWER(SIN(({$lng} - {$defaultLongitudeColumn}) * pi()/180 / 2), 2) )) )*{$magicNumber}) )/{$magicNumber}
(I removed the abs calls.)

Hi I have a simple procedure you can use it for your work.
The procedure is very simple and calculate the distance between two cities.you can modify it in your way.
drop procedure if exists select_lattitude_longitude;
delimiter //
create procedure select_lattitude_longitude(In CityName1 varchar(20) , In CityName2 varchar(20))
begin
declare origin_lat float(10,2);
declare origin_long float(10,2);
declare dest_lat float(10,2);
declare dest_long float(10,2);
if CityName1 Not In (select Name from City_lat_lon) OR CityName2 Not In (select Name from City_lat_lon) then
select 'The Name Not Exist or Not Valid Please Check the Names given by you' as Message;
else
select lattitude into origin_lat from City_lat_lon where Name=CityName1;
select longitude into origin_long from City_lat_lon where Name=CityName1;
select lattitude into dest_lat from City_lat_lon where Name=CityName2;
select longitude into dest_long from City_lat_lon where Name=CityName2;
select origin_lat as CityName1_lattitude,
origin_long as CityName1_longitude,
dest_lat as CityName2_lattitude,
dest_long as CityName2_longitude;
SELECT 3956 * 2 * ASIN(SQRT( POWER(SIN((origin_lat - dest_lat) * pi()/180 / 2), 2) + COS(origin_lat * pi()/180) * COS(dest_lat * pi()/180) * POWER(SIN((origin_long-dest_long) * pi()/180 / 2), 2) )) * 1.609344 as Distance_In_Kms ;
end if;
end ;
//
delimiter ;

SELECT ACOS(COS(RADIANS(lat)) *
COS(RADIANS(lon)) * COS(RADIANS(34.7405350)) * COS(RADIANS(-92.3245120)) +
COS(RADIANS(lat)) * SIN(RADIANS(lon)) * COS(RADIANS(34.7405350)) *
SIN(RADIANS(-92.3245120)) + SIN(RADIANS(lat)) * SIN(RADIANS(34.7405350))) *
3963.1 AS Distance
FROM Stores
WHERE 1
HAVING Distance <= 50
Here's how I use it in PHP:
// Find rows in Stores within 50 miles of $lat,$lon
$lat = '34.7405350';
$lon = '-92.3245120';
$sql = "SELECT Stores.*, ACOS(COS(RADIANS(lat)) *
COS(RADIANS(lon)) * COS(RADIANS($lat)) * COS(RADIANS($lon)) +
COS(RADIANS(lat)) * SIN(RADIANS(lon)) * COS(RADIANS($lat)) *
SIN(RADIANS($lon)) + SIN(RADIANS(lat)) * SIN(RADIANS($lat))) *
3963.1 AS Distance
FROM Stores
WHERE 1
HAVING Distance <= 50";

3956 * 2 * ASIN(SQRT( POWER(SIN(($latitude -( cp.latitude)) * pi()/180 / 2),2) + COS($latitude * pi()/180 ) * COS( abs( cp.latitude) * pi()/180) * POWER(SIN(($longitude - cp.longitude) * pi()/180 / 2), 2) )) as distance
Returns miles or KM?

Related

Latitude and longitute in Haversine show wrong distance in mysql

I really wanna know why place B is more far than place C to place A, when i use Haversine formula, but when i see on the map the place C is more distant, i will show some data:
Place A - lat: -23.598593 lon:-46.644701
Place B - lat: -23.575966 lon:-46.619133 to A distance = 3.6117730949107836
Place C - lat: -23.594992 lon:-46.636688 to A distance = 0.9068309093558656
I'm using this query :
QUERY A to B
set #latdest = -23.575966;
set #londest = -46.619133;
set #lat = -23.598593;
set #lon = -46.644701;
select 6353 * 2 * ASIN(SQRT(POWER(SIN((#lat - #latdest) * pi()/180 / 2), 2)
+ COS(#lat * pi()/180 ) * COS(#latdest * pi()/180)
* POWER(SIN((#lon - #londest) * pi()/180 / 2), 2) )) as distance
QUERY A to C
set #latdest = -23.594992;
set #londest = -46.636688;
set #lat = -23.598593;
set #lon = -46.644701;
select 6353 * 2 * ASIN(SQRT(POWER(SIN((#lat - #latdest) * pi()/180 / 2), 2)
+ COS(#lat * pi()/180 ) * COS(#latdest * pi()/180)
* POWER(SIN((#lon - #londest) * pi()/180 / 2), 2) )) as distance

MYSQL Insert into select filtering fields

I have to insert a new row in table1 for each row found in table2.
The problem is that the select in table2 returns more fields than are needed to the insert, but are useful in where clause of select.
This query shows to a user all the shops around, based on their (shops) range (defined in the table stores)
SELECT destination.poi_id,
6371 *
2 *
ASIN(
SQRT(
POWER(SIN((use_lat - poi_lat) * PI()/180 / 2), 2) +
COS(use_lat * pi()/180) *
COS(poi_lat * pi()/180) *
POWER(SIN((use_lon - poi_lon) * PI()/180 / 2), 2)
)
) AS distance,
destination.poi_range AS range
FROM stores destination, users origin
WHERE origin.use_id=userid
AND destination.poi_lon BETWEEN lon1 AND lon2
AND destination.poi_lat BETWEEN lat1 AND lat2
HAVING distance <= range
ORDER BY distance;
Now I have to put these results in a table having this structure
user_id INTEGER
poi_id INTEGER
ins_date TIMESTAMP (CURRENT TIMESTAMP)
I don't know how to do it, can you help me?
INSERT INTO table (user_id, poi_id)
SELECT ... ? (too many fields in select)
Reading between the lines a bit but basically only include the columns you need in the insert IE:
INSERT INTO table (user_id, poi_id)
SELECT use_id,poi_id,NOW() FROM
(SELECT origin.use_id,destination.poi_id,6371 *
2 *
ASIN(
SQRT(
POWER(SIN((use_lat - poi_lat) * PI()/180 / 2), 2) +
COS(use_lat * pi()/180) *
COS(poi_lat * pi()/180) *
POWER(SIN((use_lon - poi_lon) * PI()/180 / 2), 2)
)
) as distance
FROM stores destination, users origin
WHERE origin.use_id=userid
AND destination.poi_lon BETWEEN lon1 AND lon2
AND destination.poi_lat BETWEEN lat1 AND lat2
HAVING distance <= range) sub1
ORDER BY distance;
You just need to add in your select user_id and remove distance and range because there are not in your table and actually you have to add ins_date because you dont define VALUE statement in your Insert. So your Select should be something like this
INSERT INTO table values (user_id, poi_id)
Select user_id, poi_id from FROM stores destination, users origin
WHERE origin.use_id=userid
AND destination.poi_lon BETWEEN lon1 AND lon2
AND destination.poi_lat BETWEEN lat1 AND lat2
HAVING distance <= range
ORDER BY distance;
if you need to add date in your table include this field within brackets and into select statement too

MySQL distance calculation inaccurate result

I have created a table where I store Lat/Long. data along with ZIP codes.
Here is my procedure to find ZIPs within certain radius:
CREATE PROCEDURE geodistZCTA (IN userid char(5), IN dist double)
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 Y(location), X(location) into mylon, mylat from zcta where zip=userid limit 1;
-- 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 astext(location), zip from zcta where st_within(location, envelope(linestring(point(lon1, lat1), point(lon2, lat2)))) order by st_distance(point(mylon, mylat), location) limit 10;
-- select zip,(3956 * 2 * ASIN(SQRT(POWER(SIN((lat1 - abs(lat2)) * pi()/180 / 2), 2) + COS(abs(lat1) * pi()/180 ) * COS(abs(lat2) * pi()/180) * POWER(SIN((lon1 - lon2) * pi()/180 / 2), 2) ))) AS distance FROM zcta HAVING distance<=dist ORDER BY distance ASC;
-- SELECT zip,X(location),Y(location),(((ACOS(SIN(mylat * PI() / 180) * SIN(X(location) * PI() / 180) + COS(mylat * PI() / 180) * COS(X(location) * PI() / 180) * COS((Y(location)-mylon) * PI() / 180)) * 180 / PI()) * 60 * 1.1515)) AS distance FROM zcta HAVING distance<=dist ORDER BY distance ASC;
select zip,X(location),Y(location),
( 3959 * acos( cos( radians(mylat) )
* cos( radians( X(location) ) )
* cos( radians( Y(location) ) - radians(mylon) )
+ sin( radians(mylat) )
* sin( radians( X(location) ) ) ) ) AS distance
FROM zcta
where X(location) between lat1 and lat2
and Y(location) between lon1 and lon2
HAVING distance <= dist ORDER BY distance ASC;
END;
Now when I call the procedure like:
call geodistZCTA('03804',5);
I get the following result:
# zip, X(location), Y(location), distance
-------------------------------------------------------
'03042', '43.045076', '-71.07095', '3.9798046354127266'
But when I measure the distance using http://www.allplaces.us/dbz.cgi
I get 16.2 miles ( 26.1 km )
Any idea of what I am doing wrong here?

Zipcode Radius Search with POINT Column

I have a MySQL Routine that is getting records within a 50 mile radius when passed Latitude and Longitude via utilizing the Haversin equation.
While this works great, and is pretty speedy (considering it's searching through 82k records), I am thinking that I can get better performance by creating a similar procedure utilizing a POINT column.
So, in my table I created an extra column called Location, gave it a datatype of POINT, updated my data to pass lat & lon to the Location column. Data is valid, and is fine., and added a Spatial Index
The question is, how can I convert the following query to use the Location column, instead of lat and lon columns.
SET #LAT := '37.953';
SET #LON := '-105.688';
SELECT DISTINCT
BPZ.`store_id`,
3956 * 2 * ASIN(SQRT(POWER(SIN((#LAT - abs(Z.`lat`)) * pi()/180 / 2),2) + COS(#LAT * pi()/180 ) * COS(abs(Z.`lat`) * pi()/180) * POWER(SIN((#LON - Z.`lon`) * pi()/180 / 2), 2))) as distance,
c.`name`,c.`address`,c.`city`,c.`state`,c.`phone`,c.`zip`,c.`premise_type`
FROM
`zip_codes` as Z,
`brand_product_zip` as BPZ
LEFT JOIN `customers` c ON c.`store_id` = BPZ.`store_id`
WHERE
BPZ.`zip` = Z.`zip`
AND
3956 * 2 * ASIN(SQRT(POWER(SIN((#LAT - abs(Z.`lat`)) * pi()/180 / 2),2) + COS(#LAT * pi()/180 ) * COS(abs(Z.`lat`) * pi()/180) * POWER(SIN((#LON - Z.`lon`) * pi()/180 / 2), 2))) <= 50
ORDER BY
distance LIMIT 20
I understand that this has been asked before, however, everything I see points to calculations based on lat and lon and not the POINT column
Updated Code:
SET #lat = 41.92;
SET #lon = -72.65;
SET #kmRange = 80.4672; -- = 50 Miles
SELECT *, (3956 * 2 * ASIN(SQRT(POWER(SIN((#lat - abs(`lat`)) * pi()/180 / 2),2) + COS(#lat * pi()/180 ) * COS(abs(`lat`) * pi()/180) * POWER(SIN((lon - `lon`) * pi()/180 / 2), 2)))) as distance
FROM `zip_codes`
WHERE MBRContains(LineString(Point(#lat + #kmRange / 111.1, #lon + #kmRange / (111.1 / COS(RADIANS(#lat)))), Point(#lat - #kmRange / 111.1, #lon - #kmRange / (111.1 / COS(RADIANS(#lat))))), `Location`)
Order By distance
LIMIT 20
Have you looked into hilbert curves solutions? A spatial index doesn't deliver the exact solution? . With a mysql spatial index you can use mbrcontains:
CREATE TABLE lastcrawl (id INT NOT NULL PRIMARY KEY, pnt POINT NOT NULL) ENGINE=MyISAM;
INSERT
INTO lastcrawl
VALUES (1, POINT(40, -100));
SET #lat = 40;
SET #lon = -100;
SELECT *
FROM lastcrawl
WHERE MBRContains
(
LineString
(
Point
(
#lat + 10 / 111.1,
#lon + 10 / ( 111.1 / COS(RADIANS(#lat)))
),
Point (
#lat - 10 / 111.1,
#lon - 10 / ( 111.1 / COS(RADIANS(#lat)))
)
),
pnt
);
Look here: MySQL - selecting near a spatial point.
Here: http://www.drdobbs.com/database/space-filling-curves-in-geospatial-appli/184410998
The article Nearest-location finder for MySQL explains in detail various options, and the best choice for use with the Spatial Extensions starting with MySQL 5.6.
From the article, this sample query lists zip codes within a 50 mile radius from given coordinates (42.81, -70.81):
SELECT zip, primary_city,
latitude, longitude, distance_in_mi
FROM (
SELECT zip, primary_city, latitude, longitude,r,
69.0 * DEGREES(ACOS(COS(RADIANS(latpoint))
* COS(RADIANS(latitude))
* COS(RADIANS(longpoint) - RADIANS(longitude))
+ SIN(RADIANS(latpoint))
* SIN(RADIANS(latitude)))) AS distance_in_mi
FROM zip
JOIN (
SELECT 42.81 AS latpoint, -70.81 AS longpoint, 50.0 AS r
) AS p
WHERE latitude
BETWEEN latpoint - (r / 69)
AND latpoint + (r / 69)
AND longitude
BETWEEN longpoint - (r / (69 * COS(RADIANS(latpoint))))
AND longpoint + (r / (69 * COS(RADIANS(latpoint))))
) d
WHERE distance_in_mi <= r
ORDER BY distance_in_mi;

Stored Proceedure 1064 Error My SQL

my first time using one of these and I'm pretty sure this works as I have picked it up on Stackoverflow how ever when I run it as an SQL command it fails. This seems to be a common problem and having tried several different sets of code I seem to get the same problem....
MySQL said:
1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use
near '$$ CREATE FUNCTION GetDistance(coordinate1 VARCHAR(120),
coordinate2 VARCHAR(' at line 1
DROP FUNCTION IF EXISTS `GetDistance`$$
CREATE FUNCTION `GetDistance`(coordinate1 VARCHAR(120), coordinate2 VARCHAR(120))
RETURNS VARCHAR(120)
BEGIN
DECLARE pos_comma1, pos_comma2 INT;
DECLARE lon1, lon2, lat1, lat2, distance DECIMAL(18,12);
select locate(',', coordinate1) into pos_comma1;
select locate(',', coordinate1, pos_comma1+1) into pos_comma2;
select CAST(substring(coordinate1, 1, pos_comma1-1) as DECIMAL(18,12)) into lon1;
select CAST(substring(coordinate1, pos_comma1+1, pos_comma2-pos_comma1-1) as DECIMAL(18,12)) into lat1;
select locate(',', coordinate2) into pos_comma1;
select locate(',', coordinate2, pos_comma1+1) into pos_comma2;
select CAST(substring(coordinate2, 1, pos_comma1-1) as DECIMAL(18,12)) into lon2;
select CAST(substring(coordinate2, pos_comma1+1, pos_comma2-pos_comma1-1) as DECIMAL(18,12)) into lat2;
select ((ACOS(SIN(lat1 * PI() / 180) * SIN(lat2 * PI() / 180) + COS(lat1 * PI() / 180) * COS(lat2 * PI() / 180) * COS((lon1 - lon2) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) into distance;
RETURN distance;
END$$
Thanks - Terran
EDIT
Tried..........
DROP FUNCTION IF EXISTS `GetDistance`;
delimiter $$
CREATE FUNCTION `GetDistance`(coordinate1 VARCHAR(120), coordinate2 VARCHAR(120))
RETURNS VARCHAR(120)
BEGIN
DECLARE pos_comma1, pos_comma2 INT;
DECLARE lon1, lon2, lat1, lat2, distance DECIMAL(18,12);
select locate(',', coordinate1) into pos_comma1;
select locate(',', coordinate1, pos_comma1+1) into pos_comma2;
select CAST(substring(coordinate1, 1, pos_comma1-1) as DECIMAL(18,12)) into lon1;
select CAST(substring(coordinate1, pos_comma1+1, pos_comma2-pos_comma1-1) as DECIMAL(18,12)) into lat1;
select locate(',', coordinate2) into pos_comma1;
select locate(',', coordinate2, pos_comma1+1) into pos_comma2;
select CAST(substring(coordinate2, 1, pos_comma1-1) as DECIMAL(18,12)) into lon2;
select CAST(substring(coordinate2, pos_comma1+1, pos_comma2-pos_comma1-1) as DECIMAL(18,12)) into lat2;
select ((ACOS(SIN(lat1 * PI() / 180) * SIN(lat2 * PI() / 180) + COS(lat1 * PI() / 180) * COS(lat2 * PI() / 180) * COS((lon1 - lon2) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) into distance;
RETURN distance;
END;
$$
and..........
DROP FUNCTION IF EXISTS `GetDistance`;
$$
CREATE FUNCTION `GetDistance`(coordinate1 VARCHAR(120), coordinate2 VARCHAR(120))
RETURNS VARCHAR(120)
BEGIN
DECLARE pos_comma1, pos_comma2 INT;
DECLARE lon1, lon2, lat1, lat2, distance DECIMAL(18,12);
select locate(',', coordinate1) into pos_comma1;
select locate(',', coordinate1, pos_comma1+1) into pos_comma2;
select CAST(substring(coordinate1, 1, pos_comma1-1) as DECIMAL(18,12)) into lon1;
select CAST(substring(coordinate1, pos_comma1+1, pos_comma2-pos_comma1-1) as DECIMAL(18,12)) into lat1;
select locate(',', coordinate2) into pos_comma1;
select locate(',', coordinate2, pos_comma1+1) into pos_comma2;
select CAST(substring(coordinate2, 1, pos_comma1-1) as DECIMAL(18,12)) into lon2;
select CAST(substring(coordinate2, pos_comma1+1, pos_comma2-pos_comma1-1) as DECIMAL(18,12)) into lat2;
select ((ACOS(SIN(lat1 * PI() / 180) * SIN(lat2 * PI() / 180) + COS(lat1 * PI() / 180) * COS(lat2 * PI() / 180) * COS((lon1 - lon2) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) into distance;
RETURN distance;
END;
$$
Both fail....
Terran
EDIT - Found this working script.... LINK: http://datamoil.blogspot.co.uk/2011/09/calculate-distance-between-two-points.html
CREATE FUNCTION distance_between (from_lat DECIMAL(6, 3), from_lng DECIMAL(6, 3), to_lat DECIMAL(6, 3), to_lng DECIMAL(6, 3)) RETURNS DECIMAL(11, 3)
RETURN 6371 * 2 * ATAN2(SQRT(POW(SIN(RADIANS(to_lat - from_lat)/2), 2) + POW(SIN(RADIANS(to_lng - from_lng)/2), 2) * COS(RADIANS(from_lat)) * COS(RADIANS(to_lat))), SQRT(1 - POW(SIN(RADIANS(to_lat - from_lat)/2), 2) + POW(SIN(RADIANS(to_lng - from_lng)/2), 2) * COS(RADIANS(from_lat)) * COS(RADIANS(to_lat))));
DROP FUNCTION IF EXISTS `GetDistance`;
delimiter $$
CREATE FUNCTION `GetDistance`...
...
RETURN distance;
END;
$$
You have to change your delimiter to $$ before executing this code.
This works for me (tested on MySql)
DROP FUNCTION IF EXISTS `GetDistance`;
delimiter $$
CREATE FUNCTION `GetDistance`(coordinate1 VARCHAR(120), coordinate2 VARCHAR(120))
RETURNS VARCHAR(120)
BEGIN
DECLARE pos_comma1, pos_comma2 INT;
DECLARE lon1, lon2, lat1, lat2, distance DECIMAL(18,12);
select locate(',', coordinate1) into pos_comma1;
select locate(',', coordinate1, pos_comma1+1) into pos_comma2;
select CAST(substring(coordinate1, 1, pos_comma1-1) as DECIMAL(18,12)) into lon1;
select CAST(substring(coordinate1, pos_comma1+1, pos_comma2-pos_comma1-1) as DECIMAL(18,12)) into lat1;
select locate(',', coordinate2) into pos_comma1;
select locate(',', coordinate2, pos_comma1+1) into pos_comma2;
select CAST(substring(coordinate2, 1, pos_comma1-1) as DECIMAL(18,12)) into lon2;
select CAST(substring(coordinate2, pos_comma1+1, pos_comma2-pos_comma1-1) as DECIMAL(18,12)) into lat2;
select ((ACOS(SIN(lat1 * PI() / 180) * SIN(lat2 * PI() / 180) + COS(lat1 * PI() / 180) * COS(lat2 * PI() / 180) * COS((lon1 - lon2) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) into distance;
RETURN distance;
END;
$$