If you develop web applications for mobile devices, you may find yourself needing to get the visitor’s location. On a desktop browser, this can be determined by the IP address of the computer connecting to your application, but this method is far less useful on a mobile device where the location attached to the IP address is often far from the location of the device. In this post, I will describe how to first get the device’s GPS latitude and longitude and then how to use that to determine the device’s zip code for use in forms or elsewhere.
Get Latitude And Longitude From The Phone’s GPS
When I used this in a recent app, I placed the code inside a function and called the function when the page loaded. The two console.log() calls are only for viewing the values in the console, so when you use this code in your application, you will probably want to pass that data on to another function, instead. In my case, I used an AJAX call to a PHP file that performs the query shown in the next step, below.
Translate Latitude And Longitude Into A Zip Code
Here’s how the query works… You want the difference between the database latitude and your user’s latitude and the difference between the database longitude and your user’s longitude by subtracting the user’s latitude from the database latitude and doing the same for longitude values. Then you want to combine these by adding the differences together to get your over-all difference in proximity between the zip code’s location and the user’s location. The shortest over-all distance is the user’s zip code. In the above query, the CASE statements turn any negative into a positive so that your difference will always end up as a positive number. The ORDER BY sorts the results to have the closest zip codes first, and the LIMIT restricts the result set to just one zip code.
Putting It All Together
The concept above is fine for understanding how it works, but it’s really missing some things it needs for it to all work together. Seasoned developers should be able to use the concepts above in their own code, but for beginners (and the impatient), I’ve included all the code below (minus a third-party database class from the Inexo framework I wrote this in).
(assumes the use of external $db class, but connect however you normally do)
ajax.php is assumed to sit in the root of the website. In this file, I use a switch statement and “action” variable which will allow me to use this file for other AJAX needs as well, but it’s completely optional.
That’s all there is to it. Try it out yourself and comment on your results below.