HTML and CSS Reference
In-Depth Information
Coding the solution
Modify our previous example to use MaxMind as a fallback. Start by adding the Java-
Script library to the page:
<script src="http://j.maxmind.com/app/geoip.js"></script>
Then add the MaxMind fallback:
$(document).ready(function () {
// wire up button click
$('#go').click(function () {
// test for presence of geolocation
if (navigator && navigator.geolocation) {
// make the request for the user's position
navigator.geolocation.getCurrentPosition(geo_success, geo_error);
} else {
// use MaxMind IP to location API fallback
printLatLong(geoip_latitude(), geoip_longitude(), true);
}
});
});
// output lat and long
function printLatLong(latitude, longitude, isMaxMind) {
$('body').append('<p>Lat: ' + latitude + '</p>');
$('body').append('<p>Long: ' + longitude + '</p>');
// if we used MaxMind for location, add attribution link
if (isMaxMind) {
$('body').append('<p><a href="http://www.maxmind.com" target="_blank">IP
to Location Service Provided by MaxMind</a></p>');
}
}
function geo_error(err) {
// instead of displaying an error, fall back to MaxMind IP to location library
printLatLong(geoip_latitude(), geoip_longitude(), true);
}
When calling printLatLong() using MaxMind, pass in an extra true
parameter.
Discussion
Instead of showing an error if navigator or navigator.geolocation is undefined, use
the geoip_latitude() and geoip_longitude() functions that the MaxMind JavaScript
library provides to retrieve the user's latitude and longitude.
If you look at the source of the MaxMind geoip.js file, you'll see that it has already
translated your IP address into location data. MaxMind creates a dynamic JavaScript
 
Search WWH ::




Custom Search