php - 异步加载 google map v3 的问题

标签 php jquery google-maps-api-3

我当前加载 Google map 脚本的解决方案是老式方法。

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

但这需要很长时间并且渲染内容会延迟。然后我看了Google Map Documentation并发现如何异步加载 Goole Map javascript。

所以我在我已经使用的 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();  
}

我的脚本在 new google.maps.LatLng(lat,lng); 处失败,这是因为 initGoogleMap() 尚未运行。

似乎 script.src 中的回调不起作用 - 因为我的警报从未被触发。或者可能是因为事情没有按正确的顺序加载,但警报仍然应该被触发。

有人有这方面的经验吗?

最佳答案

我也遇到了同样的问题,解决方法如下:

问题在于您无法从 jQuery 外部访问 jQuery 对象本身

最后的API回调属性只能访问全局javascript。阅读 opn javascript namespace 以更好地理解。

我的解决方案是在 $document.ready(function(){...

之外设置一个全局对象
var global = {};

接下来,您在 map 的 jQuery block 中编写 init 函数作为变量并将其附加到全局对象:

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

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

...&callback=global.initMap

这对我有用。

关于php - 异步加载 google map v3 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6336732/

相关文章:

php - Magento:添加自定义 EAV 属性,在创建实体时使用其默认值自动填充

javascript - 减少 jQuery 彩色动画的加载时间

javascript - 谷歌地图 Javascript V3 未捕获类型错误 : Cannot read property 'offsetWidth' of null

javascript - Angular 谷歌地图正确策略

PHP PhantomJS 未通过 Composer 在类中加载

PHP连接数据库成功后也找不到表

javascript - JavaScript 计算器中只有除法按钮可以正常工作。 "Cannot read property ' toString' of undefined“其他运算符的错误

javascript - 在 asp.net mvc 3 中引用自定义外部 javascript 文件

api - 使用 Google Places API 时的 REQUEST_DENIED

php - 无法让 $_POST 工作