我想动态加载google maps api-当当前页面上存在特定元素时。
当我尝试使用地址解析器时,收到以下消息:
ReferenceError: google is not defined
因此,我认为无法成功加载maps api,但在萤火虫中一切正常(脚本称为正确)
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();
有任何想法吗?谢谢你。
感谢您指出正确的方向。已经发现,谷歌有一个异步加载的例子:
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');
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句