我现在的加载谷歌地图脚本的解决方案是旧式的方式。异步加载谷歌地图v3的问题
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=true"></script>
但是这需要很长时间并且渲染内容被延迟。然后我看着Google Map Documentation,并发现如何可以异步加载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();
}
我的脚本在new google.maps.LatLng(lat,lng);
失败,这是因为initGoogleMap()
一直没有运行。
似乎script.src
的回调不起作用 - 因为我的警报从未被解雇。或者,这可能是因为事情没有按照正确的顺序进行,但仍然应该触发警报。
有没有人有这方面的经验?
我没有直接经验,我将不得不查看最近的Google Maps项目,但可以运行超时循环以检查它是否已初始化? – ldg 2011-06-13 21:46:41
@lds,我不确定我明白你的意思是什么时间循环。查看Firebug,Google地图脚本在125毫秒内加载。比现在快60%以上。 – Steven 2011-06-13 22:05:49