异步加载谷歌地图v3的问题

Ste*_*ven 2 php jquery google-maps-api-3

我目前用于加载Google地图脚本的解决方案是旧时尚方式.

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
Run Code Online (Sandbox Code Playgroud)

但这需要很长时间,渲染内容会延迟.然后我查看了谷歌地图文档,并发现了如何异步加载Goole Map javascripts.

所以我在我已经使用的javascript中对此进行了测试.这只是我脚本的片段.

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();  
}
Run Code Online (Sandbox Code Playgroud)

我的脚本失败了new google.maps.LatLng(lat,lng);,这是因为initGoogleMap()还没有运行.

似乎回调中script.src没有用 - 因为我的警报从未被解雇.或者可能是因为事情没有以正确的顺序排列,但仍然应该触发警报.

有任何人对此有经验吗?

tim*_*tim 5

我有同样的问题,并按照这样的方式解决了这个问题:

问题是你无法从外部jQuery获取jQuery对象.

最后的API回调属性只能访问全局javascript.读取opn javascript 命名空间以便更好地理解.

我的解决方案是在$ document.ready(function(){...之外设置一个全局对象.

var global = {};
Run Code Online (Sandbox Code Playgroud)

接下来,您将jQuery块中的init函数作为变量写入地图并将其附加到全局对象:

global.initMap = function(){ ...}
Run Code Online (Sandbox Code Playgroud)

现在你可以在url查询字符串中引用你的jquery函数作为全局变量,如下所示:

...&callback=global.initMap
Run Code Online (Sandbox Code Playgroud)

这对我有用.