Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert latitude/longitude fields into Geospatial Points

I have a table with with a latitude, longitude and coordinates column. There are over 500,000 rows. The coordinates field is currently empty on every row. What I need to do is convert the latitude and longitude into a Geospatial POINT() and put it in the coordinates column. Is this possible?

I know that POINTs can be inserted like this:

INSERT INTO `myTable` (`coordinates`) VALUES (GeomFromText('POINT(50.2 51.6)'));

I essentially need to do exactly this but by pulling the value from latitude and longitude from each row.

like image 812
jskidd3 Avatar asked Jan 17 '14 14:01

jskidd3


2 Answers

This is a older question but I have remarked that all answers are wrong (at least in 2019) latitude and longitude must be opposite as the answers

instead: POINT(latitude,longitude)

Must be: POINT(longitude,latitude)

In Mysql 5.6 and later can use :

Update myTable
Set coordinates = POINT(longitude, latitude);

If we try some like:

SELECT ST_Distance_Sphere(
    POINT(13.1500000,99.9666700), 
    POINT(48.861105, 120.335337)
);

got error:

ERROR 1210 (HY000): Incorrect arguments to st_distance_sphere

Because I have used like in the answers POINT(latitude,longitude)

But if we try POINT(longitude,latitude):

SELECT ST_Distance_Sphere(
    POINT(99.9666700, 13.1500000), 
    POINT(120.335337, 48.861105)
);

The result is:

+--------------------------------------------+
| ST_Distance_Sphere(
        POINT(99.9666700, 13.1500000),
        POINT(120.335337, 48.861105)
    ) |
+--------------------------------------------+
|                                                                                      4389299.754585881 |
+--------------------------------------------+
1 row in set (0.00 sec)
like image 149
MTK Avatar answered Oct 28 '22 16:10

MTK


A GeomFromText needs a string, you've got to lot of concatenate

INSERT INTO myTable (coordinates)  
   SELECT GeomFromText(CONCAT('POINT(',ot.latitude, ' ', ot.longitude,')'))
    FROM otherTable ot;

If it's an update to an existing table with latitude and longitude columns into a new column coordinates do this:

UPDATE  myTable 
 SET coordinates =  GeomFromText(CONCAT('POINT(',latitude, ' ', longitude,')'));
like image 20
Ray Avatar answered Oct 28 '22 16:10

Ray