PHP MySQL get locations in radius user's location from GPS

前端 未结 5 1055
轻奢々
轻奢々 2020-12-17 03:27

I have in my database car incidents for example. These incidents have a latitude and longitude. On a mobile using the GPS, I get the user\'s location with his coordinates. T

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-17 03:33

    Calculating the distance is pretty computationally expensive, as others have said. Returning huge datasets is also not a very good idea - specially considering PHP isn't that great in performance.

    I would use a heuristic, like approximating the distance with simple addition and subtraction.

    1 minute = 1.86 kilometers = 1.15 miles

    Just search the db with incidents within that range (effectively a square, rather than a circle), and then you can work on those with PHP.


    EDIT: Here's an alternative; an approximation that's way less computationally expensive:

    Approximate distance in miles:

    sqrt(x * x + y * y)
    
    where x = 69.1 * (lat2 - lat1) 
    and y = 53.0 * (lon2 - lon1) 
    

    You can improve the accuracy of this approximate distance calculation by adding the cosine math function:

    Improved approximate distance in miles:

    sqrt(x * x + y * y)
    
    where x = 69.1 * (lat2 - lat1) 
    and y = 69.1 * (lon2 - lon1) * cos(lat1/57.3) 
    

    Source: http://www.meridianworlddata.com/Distance-Calculation.asp


    EDIT 2: I ran a bunch of tests with randomly generated datasets.

    • The difference in accuracy for the 3 algorithms is minimal, especially at short distances
    • The slowest algorithm (the one with the whole bunch of trig functions) is 4x slower than the other two.

    Definitely not worth it. Just go with an approximation.

    Code is here: http://pastebin.org/424186

提交回复
热议问题