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

comments powered by Disqus
Other posts you may like...
Programming, DIY, Games, Hacks, and Tech

Recent Blog Posts

Converting a CSV file containing commas in quotes to a pipe separated file using Awk and Bash

How to get Facybox gallery popup to work for images with dynamic URLs

jQuery UI Photoboxr plugin updated to version 0.2

Learn How to Add Disclaimer to All Outgoing Emails in Office 365

How to securely host your web site for free with Google Cloud and CloudFlare (part 3)

How to securely host your web site for free with Google Cloud and CloudFlare (part 2)

How to securely host your web site for free with Google Cloud and CloudFlare (part 1)

Beware of the subtle difference in date format strings between MySQL and SQLite

Postman reporting Unexpected 'N' error in response body

Adding extra shelves to the Ikea Detolf display cabinet

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

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
Please follow me for more great content!
     
Don't show this again