我需要找出是否有任何div = class =" map"在页面Code Pen Example。
如果有,只有在这种情况下,请加载Google Maps API。
然后使用它使用lat和long值的数据属性将地图加载到div中。
所以我有以下内容:
<div class="map" data-long="51.5072" data-lat="0.1275">
Replace by map 1
</div>
<div class="map" data-long="74.0059" data-lat="40.7127">
Replace by map 2
</div>
我正在考虑使用类似的东西(只有在存在map div时才应该加载):
$.getScript('https://www.google.com/jsapi', function()
{
google.load('maps', '3', { other_params: 'sensor=false', callback: function()
{
}});
});
我想要应用于每张地图的代码类似于Google Maps Code:
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
谢谢你, 米格尔
答案 0 :(得分:0)
查看用于加载Google Maps API异步的解决方案: https://stackoverflow.com/a/12602845/1491212
var gMapsLoaded = false;
window.gMapsCallback = function(){
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function(){
if(gMapsLoaded) return window.gMapsCallback();
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
然后就这样做:
$(document).ready(function(){
function initialize(){
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
}
$(window).bind('gMapsLoaded', initialize);
if($('.map').length){
window.loadGoogleMaps();
}
});