-1

我試圖遵循一些示例代碼段約谷歌地圖API的電子書,但我無法使用一些button標籤與適當的ID來改變一些地圖的使用javascript的屬性。未能控制與HTML按鈕元素谷歌地圖API

是否有任何理由,爲什麼下面的代碼是無法被點擊的按鈕後改變這些屬性呢?另外,有沒有爲什麼有時候當我移動的JavaScript的網頁上呼籲buttonEvents()行加載地圖無法載入所有在一起的原因是什麼?

// global variable of map 
var map; 
// the name initMap is just convention when using the Maps API 
function initMap() { 
    // initialising the map's visual settings and theme 
    google.maps.visualRefresh = true; 
    // initial app settings 
    var mapOptions = { 
     center: new google.maps.LatLng(39.9078, 32.8252), 
     zoom: 10, 
     mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 
    // retrieving element in DOM where map will be 
    var mapElement = document.getElementById("map"); 
    // creating map on this element 
    map = new google.maps.Map(mapElement, mapOptions); 
} // end initMap() 

function zoomToIstanbul() { 
    var istanbulCenter = new google.maps.LatLng(41.0579. 29.0340); 
    map.setCenter(istanbulCenter); 
} // end zoomToIstanbul() 

function disableDrag() { 
    map.setOptions({ 
     draggable: false 
    }); 
} // end disableDrag() 

function setMaxZoom() { 
    map.setOptions({ 
     maxZoom: 12 
    }); 
} // end setMaxZoom() 

function setMinZoom() { 
    map.setOptions({ 
     minZoom: 10 
    }); 
} // end setMinZoom() 

function disableScroll() { 
    map.setOptions({ 
     scrollwheel: false 
    }); 
} // end disableScroll() 

// this listens to button clicks from the user to change 
// particular options and settings of the map 
function buttonEvents() { 
    // calls zoomToIstanbul() 
    var buttonIstanbul = document.getElementById("zoom-to-istanbul"); 
    buttonIstanbul.addEventListener("click", function() { 
     zoomToIstanbul(); 
    }); 

    // calls disableDrag() 
    var buttonDisableDrag = document.getElementById("disable-drag"); 
     buttonDisableDrag.addEventListener("click", function() { 
     disableDrag(); 
    }); 

    // calls setMaxZoom() 
    var buttonMaxZoom = document.getElementById("max-zoom"); 
    buttonMaxZoom.addEventListener("click", function() { 
     setMaxZoom(); 
    }); 

    // calls setMinZoom() 
    var buttonMinZoom = document.getElementById("min-zoom"); 
    buttonMinZoom.addEventListener("click", function() { 
     setMinZoom(); 
    }); 
} // end buttonEvents() 

// this calls initMap when the page loads 
google.maps.event.addDomListener(window, "load", initMap); 
google.maps.event.addDomListener(window, "load", buttonEvents); 
+1

什麼'map'在'zoomToIstanbul()'函數值?這些功能中的任何一個如何訪問地圖實例? – Scarysize

+0

好,我本來想叫'buttonEvents()''裏面initMap()'但隨後地圖將無法加載。 –

回答

2

這裏的問題是您在頁面加載時調用事件。什麼,你需要做的是這樣的:

<script type="text/javascript"> 
    function initMap() { 
     // Load map and set events here 
    } 
</script> 

<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script> 

這可確保initMap函數被調用谷歌地圖API加載之後。

來源:https://developers.google.com/maps/documentation/javascript/tutorial