Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the unit in returned by MySQL GLength method?

I want to get the length in meters between 2 points in the surface of the Earth. But the GLength method returns an unexpected value

http://dev.mysql.com/doc/refman/5.0/en/geometry-property-functions.html#function_glength

SELECT GLength(GeomFromText(
   'LINESTRING(-67.8246 -10.0073,-67.8236 -10.0082)', 4326))

actual result

0.00134536240471071

expected value in meters:

147
like image 938
Jader Dias Avatar asked May 28 '10 20:05

Jader Dias


1 Answers

I guess it's about 3 years too late for the OP, but I happened across this question while researching a similar topic, so here's my tuppence worth.

According to www.movable-type.co.uk/scripts/latlong.html there are 3 ways of calculating distance across the Earth's surface, these being, from easiest to most complex (and thus from least to most accurate): Equirectangular Approximation, Spherical Law of Cosines and the Haversine Formula. The site also provides JavaScript. This is the function for Equirectangular approximation:


function _lineDistanceC(lat1, lon1, lat2, lon2) {   
    var R = 6371; // km
    lat1 = lat1.toRad();
    lon1 = lon1.toRad();
    lat2 = lat2.toRad();
    lon2 = lon2.toRad();
    var x = (lon2-lon1) * Math.cos((lat1+lat2)/2);
    var y = (lat2-lat1);
    return Math.sqrt(x*x + y*y) * R;
}

This is my attempt at a SQL equivalent:


drop function if exists lineDistanceC;
delimiter //
CREATE FUNCTION lineDistanceC (la1 DOUBLE, lo1 DOUBLE, la2 DOUBLE, lo2 DOUBLE) RETURNS DOUBLE 
BEGIN 
    SET @r = 6371;
    SET @lat1 = RADIANS(la1);
    SET @lon1 = RADIANS(lo1);
    SET @lat2 = RADIANS(la2);
    SET @lon2 = RADIANS(lo2);
    SET @x = (@lon2-@lon1) * COS((@lat1+@lat2)/2);
    SET @y = (@lat2 - @lat1);
    RETURN (SQRT((@x*@x) + (@y*@y)) * @r);
END
//
delimiter ;

I have no idea how accurate this formula is, but the site seems very credible and definitely worth a visit for more detail. Using the coordinates in the question, the results (in kilometres) from the above JavaScript and SQL are 0.14834420231840376 and 0.1483442023182845, which makes them the same to a fraction of a millimetre, but not, curiously, the 147 metres that the OP was expecting. Enjoy.

like image 149
blankabout Avatar answered Oct 16 '22 03:10

blankabout