开发者

Problem with loading google map v3 asynchronously

My current solution for loading Google map scripts, is the old fashion way.

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>

But this takes to long and rendering content is delayed. Then I looked at the Google Map Documentation and discovered how one can load the Goole Map javascripts asynchronously.

So I tested this in the javascript I'm already using. This is just snippets of my script.

jQuery(document).ready(function() {
  googleMaploadScript();
  someFunction();
}

// Script for loading googlemap with callback to initialize Google map
function googleMaploadScript() {
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.google.com/maps/api/js?sensor=true&callback=initGoogleMap";
  document.body.appendChild(script);
}

// Some function that calls populateGeoMap()
function someFunction() {
(...)
populateGeoMap(); 
}

// Script for populating google map with locations
function populateGeoMap() {
  // This is where I initialized google map each time I load the page using google map
  // But since I'm using a callback, I've commented this out.
  //initGoogleMap(); 
  var lat = '12.142123';
开发者_运维技巧  var lng = '54.524522';
  latLng  = new google.maps.LatLng(lat,lng); <-- THIS FAILS
}

// Google map init
function initGoogleMap() {
    alert('test'); <-- THIS ALERT IS NEVER TRIGGERED

    options           = {zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }    
    map               = new google.maps.Map(document.getElementById("map_canvas"), options);
    geocoder          = new google.maps.Geocoder();
    icon              = new google.maps.MarkerImage("http://mysite.com/img/pin_red.png", null, null, null, new google.maps.Size(32, 32));    
    bounds            = new google.maps.LatLngBounds();  
}

My script fails at new google.maps.LatLng(lat,lng); and this is because initGoogleMap() has not been run.

It seems that the callback in the script.src did not work - because my alert is never fired. Or it might be because things are not laoded in the correct order, but still, the alert should have been triggered.

Does anyone have experience with this?


I had the same problem and worked it out like this:

the problem is the fact that you can't get to the jQuery object itself from outside jQuery.

the API callback attribute at the end has only access to the global javascript. read up opn javascript namespace to understand better.

my solution is to set up a global object outside of the $document.ready(function(){...

var global = {};

next, you write the init function inside your jQuery block for the map as a variable and attach it to the global object:

global.initMap = function(){ ...}

now you can reference your jquery function as a global variable in the url query string like this:

...&callback=global.initMap

this worked for me.


tim's suggestion is excellent!

This is working asynchronous (lazy loading) of google maps v3 script with jQuery based Google Maps plugins.

This way no script except head.js+jquery.js are blocking the page and google maps starts loading as soon as is possible. window.load should be accessed quickly. tested on ffox 12, ie7,8,9 and chrome 18.

due to some issues with ie7,8 it was not possible to load jquery.js asynchronously :/

//////////////////// lazy loaded google map
// load head.js normally before this code.
// due to IE7,8 or head.js bug you HAVE TO load normally jQuery too:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> 
<script src="/PATH/head.js"></script> 
// load rest of your javascript using head.js function
head.js("yourscripts.js");

// IMPORTANT: google map plugin must be tagged like this:
head.js({gmap:"YOUR_PATHs/jquery.mapka.v3-rc.js"}); 



var global = {};

global.googlemaps_init = function(){  

   head.ready("gmap", function() {

     // jquery-ui-map v3 init of google maps (place YOUR jQuery based google maps plugin init here)
     $('#map_canvas').gmap({ 'center': '42.345573,-71.098326' });

    }); // head.gmap.ready END
} // global.googlemaps_init END


function loadGmapScript() {
  var global = {};
  var script = document.createElement("script");
  script.type = "text/javascript";
  script.src = "http://maps.googleapis.com/maps/api/js?&sensor=false&callback=global.googlemaps_init";
  document.body.appendChild(script);
}
window.onload = loadGmapScript;

//////////////////// lazy loaded google map END


This is because you're trying to initialize an object that you don't have access to. Try moving the GA functions into the document.onready block:

$(function(){
    // Script for loading googlemap with callback to initialize Google map
    function googleMaploadScript() {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "http://maps.google.com/maps/api/js?sensor=true&callback=initGoogleMap";
        document.body.appendChild(script);
    }

    // Some function that calls populateGeoMap()
    function someFunction() {
        (...)
        populateGeoMap(); 
    }

    // Script for populating google map with locations
    function populateGeoMap() {
        // This is where I initialized google map each time I load the page using google map
        // But since I'm using a callback, I've commented this out.
        //initGoogleMap(); 
        var lat = '12.142123';
        var lng = '54.524522';
        latLng  = new google.maps.LatLng(lat,lng); <-- THIS FAILS
    }

    // Google map init
    function initGoogleMap() {
        alert('test'); <-- THIS ALERT IS NEVER TRIGGERED

        options           = {zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }    
        map               = new google.maps.Map(document.getElementById("map_canvas"), options);
        geocoder          = new google.maps.Geocoder();
        icon              = new google.maps.MarkerImage("http://mysite.com/img/pin_red.png", null, null, null, new google.maps.Size(32, 32));    
        bounds            = new google.maps.LatLngBounds();  
    }

    googleMaploadScript();
    someFunction();
});


I think what happens is that you actually trigger "somefunction" before the map is loaded so JS fails and never actually executes the "initGoogleMap".

Place your somefunction at the end of the initGoogleMap like that:

google.maps.event.addListener(map, 'loaded', function(){
 somefunction();
});

K


you can use the async mode when loading Google Maps api, you need to provide a callback function:

http://maps.googleapis.com/maps/api/js?sensor=true&callback=my_callback_function

Here http://lucamanzo-soluzione-software.it/wp/?p=5 you can find a simple jquery plugin showing all the steps to use the async loading and jquery, and building a map with just a few lines of code. Usage example:

$.gmapstools.init();
$("#my_map_canvas").gmap({lat:37.4221913, lng:-122.08458530000001, draw_marker:true, zoom_level:13});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜