I am trying to get the users geolocation via the html5 geolcation api, and i use the following snippet for it:
if (navigator.geolocation) {
var timeoutVa
look at this tutsplus example http://mobile.tutsplus.com/tutorials/mobile-web-apps/html5-geolocation/
You can use this online service to get the lat lng easily:
http://dev.maxmind.com/geoip/javascript
Regarding the timeout, I don't think there's a way to interfere with the browsers permission mechanism (as in, to close that permission popup after a certain amount of seconds) - though I would gladly be proven wrong. What you could do would be to set a timer and after three seconds, get the IP based geolocation and set the map to it (or, refresh the page after 3 seconds, and set a cookie that triggers the IP based geo and not the HTML5 geo, but that's a bit over the top if you ask me).
Then, if they give permission, it would refresh the map with the HTML5 geolocation (which should be much more accurate). You can also encapsulate the IP geo fallback into a function and use it if they don't have HTML5 geolocation or they hit deny.
Here's a fiddle: http://jsfiddle.net/mfNCn/1/
Here's the rough cut from the fiddle:
<script src="http://j.maxmind.com/app/geoip.js" charset="ISO-8859-1" type="text/javascript"></script>
...
var time_perm = window.setTimeout(get_by_ip, 3000);
...
function get_by_ip() {
var lat = geoip_latitude();
var lng = geoip_longitude();
map_it(lat, lng);
}
...
function map_it(lat,lng) {
// build your map here
}
(I hesitate to put the whole code chunk onto here, as it's rather lengthy, so check the fiddle for the rest and full implementation)
You would then use a geo ip api like this one:
http://freegeoip.net/static/index.html
From UI point of view, I would follow these steps:
A) show a nice text box explaining what's going to happen next (I.e. 'the browser will ask you to grant a permission', 'click allow', etc) and asking to push a button to proceed B) display the map as you do now
Ok so this is not a code answer, more of an User Experience answer.
From a UX standpoint, the first thing that stands out is the lack of information you are offering before you trigger the browser to ask them for permission.
I suggest you have some sort of overlay box showing a screen shot (with a large arrow on it) demonstrating "where" on the screen that they are going to get asked for permission. Also you can take that opportunity to tell them what will happen if they deny permission or fail to accept it within say 10 seconds (ie. where they ignore the prompt bar).
I suggest you don't default to showing the IP location, because they essentially 'could be saying' I don't agree to letting you know where I am. Then you show a big map of where they are, that may freak a few people out that clicked deny! Besides it may be very inaccurate.
The idea of "don't ask for permission ask for forgiveness", may work in Biz dev, but not in UI as they just don't come back.
I would ask yourself if you really need high accuracy too, because it will drain user battery, take longer, and may not give you much more bang for your buck, especially if you only need it to find out loosely where they are. You can always call it again later for a more accurate reading if you need to.
The concept of timing out if they don't click deny or allow could be achieved with a setTimeout. So once they click "Ok I'm ready to click allow" on your overlay box, kick off a timeout and if it does eventually timeout then do what you told them you would do in the above step.
By using this method, you force the user to either allow or deny(ignore), either-way it puts control back in your court, and keep the user totally informed.
Although this is not a code specific answer, it is clear from your JS that "code implementation help" is not really the issue here. I hope if nothing else this gets you thinking a little more about your User Experience.
If there is a timeout or the user denies the request, I would set a default location like New York, NY (40.7142, -74.0064). If a user denies a request, they have to also expect that you won't know their location so choosing an intelligible default is the next best thing.
Using a default without changing your code much can be accomplished by calling displayPosition({coords: {latitude: 40.7142, longitude: -74.0064}}) in two places:
if (navigator.geolocation) {
var timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
displayPosition({coords: {latitude: 40.7142, longitude: -74.0064}})
}
....
function handleError(error){
switch(error.code)
{
case error.PERMISSION_DENIED: alert("User did not share geolocation data");break;
case error.POSITION_UNAVAILABLE: alert("Could not detect current position");break;
case error.TIMEOUT: alert("Retrieving position timed out");break;
default: alert("Unknown Error");break;
}
displayPosition({coords: {latitude: 40.7142, longitude: -74.0064}});
}
On http://nearbytweets.com I use a "queue" of functions for finding a user's location, looping through the queue until one of them finds a valid location. The last function returns New York, NY, which means all other attempts have failed. Here's a sample of the code modified slightly:
var position_finders = [
function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(check_position, check_position);
return;
}
check_position();
},
function () {
check_position(JSON.parse(localStorage.getItem('last_location')));
},
function () {
$.ajax({
url: 'http://www.google.com/jsapi?key=' + google_api_key,
dataType: 'script',
success: check_position
});
},
function () {
check_position({latitude: 40.7142, longitude: -74.0064}, true);
}
],
check_position = function (pos, failed) {
pos = pos || {};
pos = pos.coords ?
pos.coords :
pos.loader ?
pos.loader.clientLocation :
pos;
if (typeof pos.latitude === 'undefined' || typeof pos.longitude === 'undefined') {
position_finders.shift()();
return;
}
localStorage.setItem('last_location', JSON.stringify(pos));
// using your code, I would call this:
displayPosition(pos);
};
check_position();
Here's what each position_finder does: