Skip to content
Advertisement

PHP to Javascript Arrays and GPS locations

I’m making a script that will hopefully be mainly PHP so it doesn’t require Javascript later on, but right now I’m stuck on a few things.

  1. What is the best way to store GPS locations, and then compare them? I could use to store them in a database (currently using MySQL), and then find people nearby with some code, but I fear this would quite intensive, especially if a lot of values are in the database. This should be executed on the server, I’m currently using PHP right now.

  2. How can I get this data, and then represent it in Google Maps? I’ve currently got my code working when I have already put in the data, but I would like to get this data from a database. Would it be asking too much of the user to place say 100 markers on a single Google Maps view to represent all people around the world? Or should I just stick with people within a certain area? My current code is:

    var people = [ ['Type1', -33.890542, 151.274856],
                   ['Type2', -33.923036, 151.259052],  
                   ['Type2', -34.028249, 151.157507],  
                   ['Type2', -33.80010128657071, 151.28747820854187],  
                   ['Type1', -33.950198, 151.259302]
                 ];
    

    Each ‘type’ displays a different image, so I need to pull the type, lat and long from a database and put them into this Javascript Array.

I know there’s a few questions thrown in there, I’m new to this side of javascript and Maps 🙂

Advertisement

Answer

1. Your first question

I had to solve something like this last week and I did it like this.
Let’s say I have a list of some offices in MySQL database with their GPS coordinates (gps_lat, gps_lon) and I want to sort them by their distance to my current location ($latitude, $longtitude) in km.

// MySQL query in PHP
// btw, I'm storing GPS coordinates in decimal format like 51.123234
$varA = "(POW(SIN((gps_lat - $latitude) / 2 * 0.017453293), 2) + COS($latitude * 0.017453293)
        * COS(gps_lat * 0.017453293) * POW(SIN((gps_lon - $longtitude) / 2 * 0.017453293), 2))";
    
$query = "SELECT *, (6378.140 * 2 * ATAN2(SQRT($varA), SQRT(1-$varA))) AS distanceInKm ";
$query += 'FROM Office ORDER BY distanceInKm'); 

$mysqli->query($query);
// ...

// the magic constant 0.017453293 is PI / 180 (just check the link below).

Maybe check this link Deriving the Haversine Formula, it helped me a lot. I know this looks weird in SQL. The $varA is just one part of the formula that repeats twice. Original formula in the link above looks like this:

dlon = lon2 - lon1
dlat = lat2 - lat1
a = (sin(dlat/2))^2 + cos(lat1) * cos(lat2) * (sin(dlon/2))^2
c = 2 * atan2(sqrt(a), sqrt(1-a)) 
d = R * c
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement