Geolocating a user using their browser (if supported) is quite easy using HTML5 and JavaScript / jQuery. In fact, it can be done in under 50 lines of code. I wrote up this quick and easy tutorial to help anyone wanting to use geolocation within a browser.
If your browser supports geolocation, the below code will give you a simple static Google Maps image showing your location:
The key to the entire tutorial is the below code. It’s what gets the browser to locate the user:
In Chrome, the browser will prompt the user to allow permission to access their location:
The HTML:
The JavaScript:
Demo:
View a working demo of the this on jsbin. This is an exact copy of the code used above, and you can use jsbin to make clone of the code so you can edit it at your leisure. The code has been tested on Chrome, Firefox and Safari (on a Mac, make sure Location Services is enabled from System Preferences > Security & Privacy > Privacy tab).
This doesn’t work. What did you see this work on? I haven’t found one that works at all yet. I’ve been checking high and low.
What browser did you test on? This example works on iOS, Android, Chrome, Safari and Firefox. Try out the code here: http://jsbin.com/egarin/latest
You need to make sure you are including the jQuery library too. If you got any JavaScript errors, please post them here so I can take a look.