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 timeoutVal = 10 * 1000 * 1000;
navigator.geolocation.getCurrentPosition(
displayPosition,
displayError,
{ enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
);
}
else {
// DO SOME STUFF HERE
}
function displayPosition(position) {
// configuration
var myZoom = 12;
var myMarkerIsDraggable = true;
var myCoordsLenght = 6;
var defaultLat = position.coords.latitude;
var defaultLng = position.coords.longitude;
document.getElementById('latitude').value = defaultLat;
document.getElementById('longitude').value = defaultLng;
/*
1. creates the map
2. zooms
3. centers the map
4. sets the map’s type
*/
var map = new google.maps.Map(document.getElementById('canvas'), {
zoom: myZoom,
center: new google.maps.LatLng(defaultLat, defaultLng),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
});
// centers the map on markers coords
map.setCenter(myMarker.position);
// adds the marker on the map
myMarker.setMap(map);
}
function displayError(error) {
var errors = {
1: 'Permission denied',
2: 'Position unavailable',
3: 'Request timeout'
};
alert("Error: " + errors[error.code]);
}
});
The trouble with the above approach is that, few of the users have found it difficult to use. Few of the times, they have clicked Deny instead of Allow and keep staring on the screen. So from usability point of view, I think a good approach would be:
Ask them for permission.
Wait for 3 seconds, if they click deny or don't respond, use IP to show the geolcation on the map.
How can I accomplish the second step in my above snippets. Please let me know, thanks! However, what would be a better way to handle
displayError()
) not being called when the user clicks Deny or when the request times out? If it is being called (as it should), it's there that you'd want to do your second step (use the user's IP to do geolocation). – Jollenta