Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the distance between two points in MYSQL. (using the Point Datatype)

Suppose I have a 2 column table like this:

| user_id      | int(11) | NO   | UNI | NULL    |                |
| utm          | point   | NO   | MUL | NULL    |                |

As you can see, it's very simple. utm is a Point data-type. I insert it like this:

INSERT INTO mytable(user_id, utm) VALUES(1, PointFromWKB(point(50, 50)));

Then, I create a Spatial index.

ALTER TABLE mytable ...add spatial index on(utm) or something. (forgot)

Alright, everything is good. Now , I want to select * where distance < 99999. But it doesn't work!

//This is supposed to select all where the distance is less than 99999999.
set @mypoint = PointFromWKB(point(20,20))
select * from mytable where GLength(LineString(utm, @mypoint)) < 9999999;
Empty set (0.00 sec)
select * from mytable where GLength(LineStringFromWKB(LineString(utm, @mypoint))) < 9999;
Empty set (0.00 sec)

By the way, I have tried to INSERT INTO without the PointFromWKB...and it didn't work...that's why someone suggested that PointFromWKB to me.

like image 1000
TIMEX Avatar asked Feb 16 '10 01:02

TIMEX


People also ask

How can I find the distance between two points in MySQL?

Calculating Distance in MySQL To get the distance between two points, you call the function with the two points as the arguments: -- Returns distance in meters.

How does MySQL calculate distance?

Heres is MySQL query and function which use to get distance between two latitude and longitude and distance will return in KM. SELECT getDistance($lat1,$lng1,$lat2,$lng2) as distance FROM your_table. Almost a decade later, this function gives THE SAME results as Google Maps distance measurement.

What is the distance between two points?

Distance between two points is the length of the line segment that connects the two points in a plane. The formula to find the distance between the two points is usually given by d=√((x2 – x1)² + (y2 – y1)²).


2 Answers

Solved. This is what I did:

where GLength(LineStringFromWKB(LineString(asbinary(utm), asbinary(@mypoint)))) < 9999999999999;
like image 82
TIMEX Avatar answered Oct 26 '22 20:10

TIMEX


You can also do it this way. Not sure if it's faster or not.

select * from mytable where glength(geomfromtext(concat('linestring(', x(utm), ' ', y(utm), ',20 20', ')'))) < 99999999
like image 29
Ray Perea Avatar answered Oct 26 '22 18:10

Ray Perea