脚本加载的时间/顺序

时间:2012-07-13 19:17:30

标签: javascript google-maps google-maps-api-3 loading

我正在使用谷歌地图,我遇到的问题归结为计时,我认为......特别是何时加载谷歌地图API的脚本。

我得到了:

Uncaught ReferenceError: google is not defined 

但是,如果我在控制台中查看Google对象,它就会显示正常。

在我尝试使用之前,API的脚本是否未完全加载?

另外,我有这个主脚本(下面)加载'defer'属性,虽然我不认为这应该是一个问题。

我错过了什么?

提前致谢。

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 个答案:

答案 0 :(得分:0)

  

在我尝试之前,API的脚本是否未完全加载   用吗?

是的,这就是问题所在。

而不是:

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);

使用jQuery.getScript()并尝试以下内容:

//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');

加载Google Maps V3 API的主要问题是脚本是部分加载的。通过http://maps.googleapis.com/maps/api/js?key=*****&sensor=false url,你加载库的第一个块,然后加载其他块。所有块都是完全加载,库中调用了网址中提供的callback函数。