MySQL latitude and Longitude table setup
Asked Answered
P

2

9

I want to store latitude and longitude values of places in a mysql database table. With the future in mind I will want to be able to find these places within a certain radius of a specific location. Having said that, what datatypes should I store the latitude and longitude values in? Please could you provide me with a create table script for columns like so:

place_id  |  lat  |  long

Is there perhaps a column I am missing in the above table that will provide me with additional information that I may not see I need at the current time?

Thanks for any help.

Psychrometer answered 18/1, 2011 at 15:48 Comment(1)
U
21

You should store the points in a singe column of datatype Point which you can index with a SPATIAL index (if your table type is MyISAM):

CREATE SPATIAL INDEX sx_place_location ON place (location)

SELECT  *
FROM    mytable
WHERE   MBRContains
               (
               LineString
                       (
                       Point($x - $radius, $y - $radius),
                       Point($x + $radius, $y + $radius)
                       )
               location
               )
        AND Distance(Point($x, $y), location) <= $radius

This will drastically improve the speed of queries like "find all within a given radius".

Note that it is better to use plain TM metrical coordinates (easting and northing) instead of polar (latitude and longitude). For small radii, they are accurate enough, and the calculations are simplified greatly. If all your points are in one hemishpere and are far from the poles, you can use a single central meridian.

You still can use polar coordinates of course, but the formulae for calculating the MBR and the distance will be more complex.

Unhesitating answered 18/1, 2011 at 15:52 Comment(15)
All my tables use InnoDB as I use foreign keys. Is it not a problem to have tables in both InnoDB and MyISAM?Psychrometer
@Martin: MyISAM is transactionless and you cannot use FOREIGN KEY constrains on it. For only SELECT queries, there are no problems with mixing the tables of different types.Unhesitating
Yes I understand that foreign keys don't work in MyISAM however if I have an additional table for the coordinates and have that as MyISAM and all my other tables are InnoDB is that not a problem?Psychrometer
@Martin: For SELECT queries, this is not a problem.Unhesitating
Thanks for the great answer! One more thing though - how would I insert a place with lat=51.484804 and long=0.296631 for example?Psychrometer
@Martin: INSERT INTO mytable VALUES (Point(51.484804, 0.296631)). For earlier versions of MySQL (5.0 and probably some early 5.1) this may require WKT translations like this: INSERT INTO mytable VALUES (GeomFromText('POINT(51.484804, 0.296631)')). If all your points are in UK I would really suggest using UTM coordinates in zone 30.Unhesitating
All the points will actually be in South Africa, I don't know if that makes any difference :) Thanks for all the information!Psychrometer
@Martin: no, this is even better, since SA is closer to the equator :)Unhesitating
newer versions of MySQL support spatial on innodb:dev.mysql.com/doc/refman/5.0/en/spatial-extensions.htmlFastidious
@BenMiller: InnoDB does not support spatial indexes even now in 5.6. The doc you're referencing clearly tells: For spatial columns, MyISAM supports both SPATIAL and non-SPATIAL indexes. Other storage engines support non-SPATIAL indexes. Please note that 5.0 you're referencing was out in 2006, it's not "newer".Unhesitating
@Quassnoi: My mistake, i saw " As of MySQL 5.0.16, InnoDB, NDB, BDB, and ARCHIVE also support spatial features." and missed that this did not also apply to spatial indexes.Fastidious
Two things: First, you missed the comma after LineString(). Second, $radius is roughly kilometers (km) / 100.Fosterling
Thank you. Can I get the distance between in my rows data? Like If I get 2 rows, one of them are 0.5 km away, and one is 2km away, etc.Introduction
@user3121056: please post it as a question.Unhesitating
Please take a look at it: #29692370Introduction
K
0

I've digged few hours through tons of topics and could nowhere find a query, returning points in a radius, defined by km. ST_Distance_Sphere does it, however, the server is MariaDB 5.5, not supporting ST_Distance_Sphere().

Managed to get something working, so here is my solution, compatible with Doctrine 2.5 and the Doctrine CrEOF Spatial Library:

    $sqlPoint = sprintf('POINT(%f %f)', $lng, $lat);

    $rsm = new ResultSetMappingBuilder($this->manager);
    $rsm->addRootEntityFromClassMetadata('ApiBundle\\Entity\\Place', 'p');

    $query = $this->manager->createNativeQuery(
        'SELECT p.*, AsBinary(p.location) as location FROM place p ' .
        'WHERE (6371 * acos( cos( radians(Y(ST_GeomFromText(?))) ) ' .
        '* cos( radians( Y(p.location) ) ) * cos( radians( X(p.location) ) ' .
        '- radians(X(ST_GeomFromText(?))) ) + sin( radians(Y(ST_GeomFromText(?))) ) * sin( radians( Y(p.location) ) ) )) <= ?',
        $rsm
    );

    $query->setParameter(1, $sqlPoint, 'string');
    $query->setParameter(2, $sqlPoint, 'string');
    $query->setParameter(3, $sqlPoint, 'string');
    $query->setParameter(4, $radius, 'float');

    $result = $query->getResult();

Assuming lng and lat is XY of the fixed point, Place is the entity with a "location" field POINT type. I could not use DQL directly due to problems with the param binding of MySQL, that's why the low-level native query. The rsm is required to map results into entity objects. Can live without it, though.

Feel free to use it. I hope it will save you some time.

Karr answered 19/4, 2016 at 12:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.