Google Maps javascript API + HTML5 geolocation quirk -


i'm having rather strange issue google maps javascript api , html5 geolocation.

i have following executed onload:

  var geocoder;   var map;   var latlng;   function initialize() {  if(navigator.geolocation){   navigator.geolocation.getcurrentposition(function(position){    latlng = new google.maps.latlng(position.coords.latitude,position.coords.longitude);   });  }else{   latlng = new google.maps.latlng(geoip_latitude(),geoip_longitude());  }   geocoder = new google.maps.geocoder();  var myoptions = {    zoom: 8,    center: latlng,    streetviewcontrol: false,    maptypeid: google.maps.maptypeid.hybrid   };  map = new google.maps.map(document.getelementbyid("map_canvas"), myoptions);    google.maps.event.addlistener(map, 'click', function(event) {   placemarker(event.latlng);   var latlong = string(event.latlng).replace('(', '');   latlong = latlong.replace(')', '');   $('#latlng').attr('value', latlong);    });     function placemarker(location) {   if(undefined != initialize.marker){    initialize.marker.setmap(null);   }   initialize.marker = new google.maps.marker({    position: location,     map: map   });   initialize.marker.setmap(map);   map.setcenter(location);  }   } 

now, should if browser supports geolocation, lat+long, create map, , display map centered on lat+long.

it works fine if use geoip_ functions (maxmind), geolocation has strange issue:

if code run is, google maps display shows gray box no map , no controls.

if add alert(); after

if(navigator.geolocation){     navigator.geolocation.getcurrentposition(function(position){         latlng = new google.maps.latlng(position.coords.latitude,position.coords.longitude);     }); }else{     latlng = new google.maps.latlng(geoip_latitude(),geoip_longitude()); } 

the map displays fine.

what's that?

the w3c geolocation api asynchronous; success callback function have (which sets variable latlng) won't called -- browser requires time geolocating; in fact, if user takes time read privacy prompt , decide whether or not give permission, process take many seconds. in meantime though, map loaded immediately.

you're finding works alert after because alert gives browser time finish geolocation process , call callback before getting code loads map. (just waiting second or 2 isn't solution though: users , browsers take longer before revealing location.)

to fix: call function creates map (you'll want encapsulate practically after geolocation call) , call both in success callback getcurrentposition , in geoip else branch. way you'll try load map after you're guaranteed latlng variable has been appropriately filled.


Comments

Popular posts from this blog

Add email recipient to all new Trac tickets -

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -