I’m attempting to get the users location for a mobile web app, if their browser doesn’t support geolocation then send them to a default map center location. This works fine on Firefox, but when I test it on an iPhone it prompts for location usage then the map does not render. I noticed though once I close safari and reopen it the map then begins to render with the geolocation. Is this a bug in safari or something wrong in the way i am initializing my map?
function init() {
var center = new google.maps.LatLng(42.283151,-87.955098);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var loc = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 11,
center: loc,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
new google.maps.Marker({
position: point,
map: map
});
});
}
else {
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 15,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
}
Are you waiting long enough for the iPhone’s GPS to get a fix on your location? This initial activation of location services can take a while to get an accurate location to return to the API, which explains why the subsequent load works as intended.
It might be worth your while to add some code to indicate that the HTML5 geolocation function is running (perhaps displaying a “Loading…” message after you call getCurrentPosition).
An error callback would be worthwhile as well to catch and gracefully handle and errors that occur during getCurrentPosition. You can definitely run into cases where navigator.geolocation is true but it won’t trigger the success function you’ve defined.