Igor's Blog
Programming, DIY, Games, Hacks, and Tech

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

comments powered by Disqus
Other posts you may like...

Recent Blog Posts

A hack to create an uber jar with the Maven Shade Plugin using local jar files

Is it worth it? Apple USB-C Digital Multi AV adapter vs a cheap eBay clone

Running X11 graphical applications after changing to another user using 'sudo su'

How to stop Facebook using ad images as post sharing thumbnails

Picking lists for Atari Lynx capacitor replacement kits

Performance - 2012 Retina MacBook Pro vs 2017 MacBook Pro

Look and feel - 2012 Retina MacBook Pro vs 2017 MacBook Pro

Using math to work out the diameter of hard to reach water cooling pipes

How to get the unreachable shard in the Hinterlands in DragonAge Inquisition

Measy RC12 wireless 2.4Ghz keyboard touchpad review

Recent Galleries

Monument Valley 2 is released and does not disappoint

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

My Other Web Sites

Igor and Elise's Travels
Riverside Expressway Cam
300 George St Blogumentary

My Online Tools

UUID to OID Converter
Guru JSON-RPC Tester
Extrudifier Object Designer
Travel ┬ÁBlog

Blogs and Friends

Matt Moores Blog
Georgi's FlatPress Guide
Perplexing Permutations
The Security Sleuth
Ilia Rogatchevski
Travelling Fairy

Blog Activity

Blog Activity
Don't forget to
me for more great articles!
Don't show this again