2012-07-13 3 views
1

Je travaille avec Google Maps et j'ai un problème de timing, je pense ... spécifiquement quand il faut charger le script de l'API de Google Maps.Timing/Ordre du script Chargement

Je reçois:

Uncaught ReferenceError: google is not defined 

Cependant, si je regarde l'objet Google dans la console, il apparaît très bien.

Le script de l'API n'est pas encore complètement chargé avant que j'essaie de l'utiliser?

En outre, j'ai ce script principal (ci-dessous) de chargement avec l'attribut 'defer', mais je ne pense pas que cela devrait être un problème.

Qu'est-ce qui me manque?

Merci d'avance.

var inrMap = { 
    map : null, 
    markers : [], 

    addCoords : function(){ 
     var regex1 = /\s/; 
     var regex2 = /\./; 
     for(var i in inrMap.locations){ 
      var address = inrMap.locations[i].address; 
      address = address.replace(regex1, '+'); 
      address = address.replace(regex2, ''); 
      $.ajax({ 
       data : 'http://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&sensor=false', 
       dataType : 'json', 
       type : 'get', 
       success : function(data, textStatus, xhr){ 
        inrMap.locations[i].lat = data.geometry.location.lat; 
        inrMap.locations[i].lng = data.geometry.location.lng; 
       }, 
       error : function(xhr, textStatus, errorThrown){ 
        //console.error('problem with geocoding service...'); 
       } 
      });  
     } 
    }, 

    generateMap : function(){ 
     var map_options = { center : new google.maps.LatLng(-34.397, 150.644), zoom : 8, mapTypeId : google.maps.MapTypeId.ROADMAP }; 
     inrMap.map = new google.maps.Map(document.getElementById("map_canvas"), map_options); 
     //load markers 
     for(var i in inrMap.locations){ 
      var position = new google.maps.LatLng(inrMap.locations[i].lat, inrMap.locations[i].lng); 
      inrMap.markers[i] = new google.maps.marker(position, inrMap.locations[i].title);   
      inrMap.markers[i].setMap({ map : inrMap.map, draggable : false, animation : google.maps.Animation.DROP }); 
     } 
    }, 

    bindMarkers : function(){ 
     // $(inrMap.markers).each(function(){ 
     // this.bind('click', function(){ 
     //  //create new info window 
     //  var location_name = this.id; // ***** this needs to be fixed ****** 
     //  var iw = new google.maps.InfoWindow({ content : this.id.title, maxWidth : '300' }); 
     // }) 
     // }); 
    }, 

    bindForm : function(){ 

    } 
} 

inrMap.locations = { 
      jacksonville : { 
       title : 'jacksonville', 
       address : '4651 Salisbury Rd. Suite 170, Jacksonville FL 32256', 
       phone : '(904) 398-0155', 
       link : '/location/florida-regional-office', 
       marker : null 
      }, 
      miami : { 
       title : 'Miami', 
       address : '15050 NW 79 Court Suite 104, Miami Lakes FL 33016', 
       phone : '(305) 403-0594', 
       link : '/location/florida-regional-office', 
       marker : null 
      } 

etc... 




} 

//load google maps js 
var gmaps_script = document.createElement('script'); 
gmaps_script.type = 'text/javascript'; 
gmaps_script.src = 'http://maps.googleapis.com/maps/api/js?key=*****&sensor=false'; 
$('body').append(gmaps_script); 

$(function(){ 

for(var i = 0; i < 4000; i++){ 
    var foo = Math.sin(i); 
} 

//check if locations object is not in local storage (and thus does not have coordinates) 
if(!localStorage.getItem('inr_locations')){ 
    //get lat & long, add to locations obj 
    inrMap.addCoords(); 
    //save object 
    //localStorage.setItem('inr_locations', inrMap.locations); 
} 
else{ 
    //pull locations object from local storage 
    //inrMap.locations = localStorage.getItem('inrMap.locations'); 
} 

//create element to place map in 
var map_canvas = document.createElement('div'); 
$(map_canvas).attr('id', 'map_canvas').appendTo('#content'); 

//generate map 
inrMap.generateMap(); 

//bind events to map markers 
//inrMap.bindMarkers(); 

//bind events to form/links 
//inrMap.bindForm(); 

}); 
+1

Y at-il une raison pour laquelle vous bouclez pour trouver 'Math.sin (i)' 4000 fois? – jbabey

+0

Dans quel ordre les scripts/sources sont-ils inclus dans votre code html? –

+0

@jbabey Oups, je l'ai pris. Était juste en train de jouer avec le timing, essayant de comprendre les choses. –

Répondre

0

est le script de l'API pas encore complètement chargée avant d'essayer de l'utiliser ?

Oui, c'est le problème.

Au lieu de:

var gmaps_script = document.createElement('script'); 
gmaps_script.type = 'text/javascript'; 
gmaps_script.src = 'http://maps.googleapis.com/maps/api/js?key=*****&sensor=false'; 
$('body').append(gmaps_script); 

Utilisez jQuery.getScript() et essayer quelque chose comme ceci:

//Temporary creating global function,for handling loading of the Google Maps Library 
window.__googlemapscallback = function(){ 
    delete window.__googlemapscallback; 

    //do your map initialization here 
}; 

$.getScript('http://maps.googleapis.com/maps/api/js?key=*****&sensor=false&&callback=__googlemapscallback'); 

Le principal problème de chargement Google Maps V3 API, est ce script est chargé partially.By http://maps.googleapis.com/maps/api/js?key=*****&sensor=false URL, vous chargez le premier morceau de la bibliothèque, qui charge ensuite les autres morceaux. Après que tous les morceaux sont entièrement chargés, la bibliothèque appelle callback fonction fournie dans l'URL.

+0

J'ai tout transféré au rappel $ .getScript mais j'ai toujours le même problème. –

+0

@ Tim76 Donc vous avez mis 'inrMap.generateMap();' à l'intérieur du callback? Ai-je raison? – Engineer

+0

Oui, c'est vrai. Et j'ai tout transféré dans generateMap(). –

Questions connexes