我正在尝试使用控件添加Google地图流量图层,因为我对此很新,所以我无法理解。我从互联网上得到了以下脚本并进行了一些微调,但我无法弄清楚如何将控件放入地图中。我只需要一种方法来为普通用户打开和关闭流量图层,所以如果有一种比将控件添加到地图更好的方法,我可以做任何事情。感谢。
var map;
var chicago = new google.maps.LatLngBounds();
function HomeControl(controlDiv, map) {
controlDiv.style.padding = '5px';
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '2px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to set the map to Home';
controlDiv.appendChild(conrolUI);
var controlText = document.createElement('div');
controlText.style.fontFamily = 'Arial.sans-serif';
controlText.style.fontSize = '12px';
controlText.style.paddingLeft = '4px';
controlText.style.paddingRight = '4px';
controlText.innerHTML = '<b>Home</b>';
controlUI.appendChild(controlText);
googlemaps.event.addDomListener(controlUI, 'click', function() {
map.setCenter(chicago)
});
}
function addtrafficlayer() {
var myLatlng = new google.maps.LatLngBounds();
var mapDiv = document.getElementById('map');
var mapOptions = {
zoom: 13,
maxWidth: 60,
}
map = new google.maps.Map(mapDiv, mapOptions);
var homeControlDiv = document.createElement('div');
var homeControl = newHomeControl(homeControlDiv, map);
homeControlDiv.index = 1;
map.controls(google.maps.ControlPosition.TOP_RIGHT).push(homeControlDiv);
var trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', addtrafficlayer);
答案 0 :(得分:4)
首先,您的addTrafficLayer
函数实际上初始化了地图......两次。此函数应命名为init
或类似名称。这是应该进行的:
function init() {
var options = {
zoom: 16,
center: new google.maps.LatLng(40.747688, -74.004142),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), options);
trafficLayer = new google.maps.TrafficLayer();
google.maps.event.addDomListener(document.getElementById('trafficToggle'), 'click', toggleTraffic);
}
toggleTraffic
非常简单:
function toggleTraffic(){
if(trafficLayer.getMap() == null){
//traffic layer is disabled.. enable it
trafficLayer.setMap(map);
} else {
//traffic layer is enabled.. disable it
trafficLayer.setMap(null);
}
}
然后你只需要一些标记来实现它:
<div id="map"></div>
<button id="trafficToggle">Toggle Traffic Layer</button>
在行动here中查看此代码。