我想动态加载google maps api - 当我在当前页面上存在特定元素时。
当我尝试使用地理编码器时,我收到以下消息:
ReferenceError: google is not defined
所以我认为地图api无法成功加载,但在firebug中一切看起来都很好(脚本被称为正确)
if ($('.vcard').length > 0) {
// load google maps when vcard is present
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://maps.google.com/maps/api/js?sensor=false";
$("head").append(s);
// error here - unable to use google maps
var geocoder = new google.maps.Geocoder();
有什么想法吗?谢谢。
答案 0 :(得分:1)
我已经修改了代码,以便在脚本加载后运行:
if ($('.vcard').length > 0) {
// load google maps when vcard is present
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "https://maps.google.com/maps/api/js?sensor=false";
s.onload = function() {
var geocoder = new google.maps.Geocoder();
};
$("head").append(s);
答案 1 :(得分:1)
感谢您指出我正确的方向。已经发现,谷歌有一个异步加载的例子:
function loadScript() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp' +
'&signed_in=true&callback=initialize';
document.body.appendChild(script);
}
function addGoogleMap() {
if ($('.vcard').length > 0) {
loadScript();
}
}
function initialize() {
// get the adress
var CurrentAddress = $('.adr').children().text();
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': CurrentAddress }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('success');
}
}