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...
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...
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...
Nice and clean and exactly the style of location that can be used in a web application.
-i