[英]Cannot load google map javascript dynamically
The follow tells me that GMap2 is not defined.下面告诉我 GMap2 没有定义。 But the code that uses GMap2 is in the callback.
但是使用 GMap2 的代码在回调中。
$(function() {
$('#sample').click(function() {
$.getScript("http://maps.google.com/maps?file=api&v=2&sensor=true&key=API_KEY_HERE", function() {
var map = new GMap2(document.getElementById("mapTest"));
map.setCenter(new GLatLng(18, -77.4), 13);
map.setUIToDefault();
});
});
});
<a id="sample">Click Me</a>
<div id="mapTest" style="width: 200px; height: 100px;"></div>
You can go two ways with this:您可以通过两种方式使用此方法:
1. Continue to use $.getScript
: 1. 继续使用
$.getScript
:
It seems that you need both an async=2
parameter as well as a different callback structure for it to work.似乎您需要一个
async=2
参数以及一个不同的回调结构才能使其工作。 My answer is adapted to your code from this great walkthrough here .我的答案适用于您在此处的精彩演练中的代码。
<script type="text/javascript">
function map_callback(){
var map = new GMap2(document.getElementById("mapTest"));
map.setCenter(new GLatLng(18, -77.4), 13);
map.setUIToDefault();
}
$(function(){
$('#sample').click(function(){
$.getScript("http://maps.google.com/maps?file=api&v=2&sensor=true&callback=map_callback&async=2&key=API_KEY_HERE");
}
}
</script>
2. Use the Google AJAX Loader 2. 使用谷歌 AJAX 加载器
Since you are already using a Google Library, why not use their loader to help you out:既然您已经在使用 Google 图书馆,为什么不使用他们的加载程序来帮助您:
<script type="text/javascript" src="http://www.google.com/jsapi?key=ABCDEFG"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
google.setOnLoadCallback(function(){
$('#sample').click(function(){
google.load("maps", "2", {"callback" : function(){
var map = new GMap2(document.getElementById("mapTest"));
map.setCenter(new GLatLng(18, -77.4), 13);
map.setUIToDefault();
} });
});
}, true); // Passing true, though undocumented, is supposed to work like jQuery DOM ready
</script>
Did you check the if the browser is compatible?你有没有检查浏览器是否兼容? I do this in all my GMAP applications, although it rarely fails...
我在所有 GMAP 应用程序中都这样做,尽管它很少失败......
if (GBrowserIsCompatible())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.