Igor's Blog

Facebook does it, so you can do it too. I'm talking about getting the user's location when they are interacting with your website. Whereas previously you had to rely on IP address based solutions, now the modern web browsers that support HTML 5 allow you to get this information easily. Combine that with the Google Maps API and you can get some very detailed location data. Here's how.

First you have to use the HTML 5 Geolocation API to fetch the user's longitude/latitude position. This would typically trigger a prompt from the web browser to allow this action...

geocode2.png geocode1.png


Assuming that the user allows their location to be shared, you will have a JavaScript object that describes the long/lat coordinates. This object can then be fed into the Google Maps Reverse Geocoder to get a range of different locations that match the point from the geolocation.

The geocoder returns an array of matching locations and unfortunately most of them are of no use, as can be seen below when I simply print out the locations...
geocode4.png


I noticed that the 'locality' type locations give the best results, so that's exactly what I look for in my code.

So lets see some code...



First you need to include the Google Maps JavaScript into your HTML, using the places library...
 HTML
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>


Next is the bit of JavaScript that checks if geolocation is available, then requests the current position and attempts to use that to reverse geocode. The geocoder results are then processed to look for 'locality' type locations and the first matching location is picked. Note that I'm using jQuery in parts here, but it can be easily replaced with vanilla JavaScript.
 JavaScript
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var geocoder = new google.maps.Geocoder;
var point = new google.maps.LatLng(
position.coords.latitude, position.coords.longitude);
geocoder.geocode({'latLng': point}, function (locations, status) {
if (status == google.maps.GeocoderStatus.OK) {
for (var location of locations) {
if ($.inArray('locality', location.types) != -1) {
console.log('Your location is: ' + location.formatted_address);
break;
}
};
}
});
});
}



The result of running that is...
geocode3.png


Nice and clean and exactly the style of location that can be used in a web application.

-i

, , ,
About — I'm an enthusiastic software engineer and consultant interested in many fields including J2EE, programming, electronics, 3D printing, video games, wood working and gardening.
See my Resume for more information.
The views expressed in this blog are my own and not those of my employer.
comments powered by Disqus
My other posts you may like...
Programming, DIY, Games, Hacks, Tech and more.
Follow me on...
Current and Past Projects
See my Resume

Subscribe


RSS Feed

My Other Web Sites

Igor and Elise's Travels
Riverside Expressway Cam
StrFunc() Online
300 George St Blogumentary
Guru JSON-RPC Tester
Extrudifier Object Designer

Recent Blog Posts

Older versions of JD-GUI crashing on macOS Sierra

How does Seeed Fusion stack up as a low budget PCB fab

Where to find the last item (Robbie's lost lyrics) in GravityFalls Lake level

Detecting print requests to print contents of a DIV with JavaScript

Using Google DFP with AdSense on responsive pages

How to change the email subject line in Gmail

Force PHP GD library to load JPEG images that have invalid data

How to uninstall Samsung Smart Switch from your Mac

Facebook adds weather forecasts but forgets to adjust them to your time zone

No sound or microphone when answering calls on an iPhone

Recent Galleries

Space Food - Chocolate Ice Cream with Chocolate Chips

Legeod Star Wars AT-DP kit

DIY spare parts computer build with a RAIDMAX Anura case

Fake 'Lepin' brand Lego packaging

Hardwood garden bench with clear resin void filler

Fixing a 3D printer extruder that stopped heating up

Easily increase disk space in a Lenovo Ideapad 100S 14" laptop with an M.2 SSD

Making a multi-piece 3D printed solder spool holder stand

DIY indoor apartment grow light wiring

Good Friday Electronics fun Easter Bunny LED PCB Kit IBEABU-01.0

Top Categories

Blogs I follow

Matt Moores Blog
Georgi's FlatPress Guide
Perplexing Permutations
The Security Sleuth

Friends

RAWS Parts Online
Alpha Dimensions Hosting
Kristensen Photography
Ilia Rogatchevski
Travelling Fairy

Blog Activity

Blog Activity
Follow me on... 
     
...or subscribe for updates!

Don't show this again