将多个地图canvas添加到窗口 – Google Maps Javascript API v3
我想在一个窗口中显示多个谷歌地图canvas,但它不起作用。 在for循环中创建的地图都显示为灰色,没有任何内容,我无法弄清楚原因。
HTML
jQuery的/ JavaScript的
var margin = 50; var maps = []; for (var i = 0; i < 5; i++) { $("#routeContainer").append("hello world "); var mapOptions = { zoom: 10, scrollwheel: false }; maps[i] = new google.maps.Map(document.getElementById('map-canvas'+i),mapOptions); };
如果有人能告诉我,我做错了什么会很棒!
- 包括两个强制选项(缩放和中心)
- 动态创建DOM元素以避免等待它们被创建,
- 给他们一个大小。
工作小提琴
var margin = 50; var maps = []; for (var i = 0; i < 5; i++) { var tableCell = document.createElement("td"); tableCell.setAttribute("style", "height:100% width:100%"); var newMapCont = document.createElement("div"); newMapCont.setAttribute("style", "margin-left: " + margin + "px; height:100% width:100%"); newMapCont.setAttribute("class", 'test'); var newMap = document.createElement("div"); newMap.setAttribute("id", "map-canvas" + i); newMap.setAttribute("style", "width:500px; height:500px; float:left;"); newMapCont.appendChild(newMap); tableCell.appendChild(newMapCont); $("#routeContainerTR").append(tableCell); var mapOptions = { zoom: 10, center: new google.maps.LatLng(i, i), scrollwheel: false }; maps[i] = new google.maps.Map(newMap, mapOptions); }
代码段:
function initialize() { var margin = 50; var maps = []; for (var i = 0; i < 5; i++) { var tableCell = document.createElement("td"); tableCell.setAttribute("style", "height:100% width:100%"); var newMapCont = document.createElement("div"); newMapCont.setAttribute("style", "margin-left: " + margin + "px; height:100% width:100%"); newMapCont.setAttribute("class", 'test'); var newMap = document.createElement("div"); newMap.setAttribute("id", "map-canvas" + i); newMap.setAttribute("style", "width:500px; height:500px; float:left;"); newMapCont.appendChild(newMap); tableCell.appendChild(newMapCont); $("#routeContainerTR").append(tableCell); var mapOptions = { zoom: 10, center: new google.maps.LatLng(i, i), scrollwheel: false }; maps[i] = new google.maps.Map(newMap, mapOptions); createMarker(mapOptions.center, mapOptions.center.toUrlValue(6), maps[i]); } } function createMarker(latlng, title, map) { var marker = new google.maps.Marker({ position: latlng, map: map, title: title }); var infowindow = new google.maps.InfoWindow(); google.maps.event.addListener(marker, 'click', function(e) { infowindow.setContent(title); infowindow.open(map, marker); }); google.maps.event.trigger(marker, 'click'); } google.maps.event.addDomListener(window, 'load', initialize);
html, body { height: 100%; width: 100%; margin: 0px; padding: 0px; border: 2px; }
使用Google地图Javascript API创建地图需要center
属性,将地图添加到地图mapOptions
,它将正常工作。