Sep 5, 2013

Visitor’s zip code using HTML5 geolocation & Google Maps API

While playing around with a weather widget, the other day, I though to myself why not use HTML5’s geolocation capabilities to show the user the weather for their current location automatically. This turns out to be exceedingly easy, if you’re willing to live with a couple of small assumptions, such as it’s safe to use a regular expression to parse the zip code out of Google Maps API’s formatted_address. Although they do offer a more specific “postal code” field as part of the address object, this is just a little quicker to get to, if you’re willing to assume a format like “, IL 60601″.

<SCRIPT type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></SCRIPT>
<SCRIPT type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></SCRIPT>
<SCRIPT type="text/javascript">
$(function() {
if(navigator.geolocation) {
var fallback = setTimeout(function() { fail('10 seconds expired'); }, 10000);
navigator.geolocation.getCurrentPosition(
function (pos) {
clearTimeout(fallback);
console.log('pos', pos);
var point = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
new google.maps.Geocoder().geocode({'latLng': point}, function (res, status) {
if(status == google.maps.GeocoderStatus.OK && typeof res[0] !== 'undefined') {
var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
if(zip) {
$("._res").html('Zip code is ' + zip[1]);
} else fail('Failed to parse');
} else {
fail('Failed to reverse');
}
});
}, function(err) {
fail(err.message);
}
);
} else {
$("._res").html('Geolocation unsupported!');
}
function fail(err) {
console.log('err', err);
$("._res").html('Error ' + err);
}
});
</SCRIPT>
<div class="_res">Nothing yet....</div>

SOURCE

1 comment:

santosh said...

Does it work i tested in js fiddle and it does not work for me.