Created
January 9, 2014 16:43
-
-
Save acafourek/8337444 to your computer and use it in GitHub Desktop.
I needed a way to determine the current user's location as near as possible so I could produce valid results from Foursquare's suggestCompletion API.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//get user's location | |
var latlong; | |
if(navigator.geolocation) { | |
//try with HTML5 | |
function showPosition(position){ | |
var htmllat = position.coords.latitude; | |
var htmllon = position.coords.longitude; | |
if(htmllat && htmllon){ | |
latlong = htmllat+','+htmllon; | |
console.log('Location determined using HTML5'); | |
} | |
} | |
navigator.geolocation.getCurrentPosition(showPosition); | |
} | |
if(!latlong){ | |
//All of my users are using a form within one of our sites which may or may not have a group location available. I've put that saved lat/long into a hidden HTML div | |
var savedlat = $('#group_loc span#group_lat').text(); | |
var savedlon = $('#group_loc span#group_long').text(); | |
if(savedlat && savedlon){ | |
latlong = savedlat+','+savedlon; | |
console.log('Location determined using saved chapter location'); | |
} | |
} | |
if(!latlong){ | |
//if no group location, try external IP lookup using MaxMind js -> http://dev.maxmind.com/geoip/ | |
var geolat = geoip_latitude(); | |
var geolon = geoip_longitude(); | |
if(geolat && geolon){ | |
latlong = geolat+','+geolon; | |
console.log('Location determined using GeoIP lookup'); | |
} | |
} | |
if(!latlong){ | |
//final fallback is the geographic center of the US. Hopefully it doesn't come to this. | |
latlong = "39.8282,-98.5795" | |
console.log('Unable to determine location'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment