2015-11-08 109 views
2

我設法讓我的平鋪地圖可以使用ArcGIS JavaScript API工作。但是,我希望能夠切換圖層(顯示不同年份)。我創建了一個函數,可以做到這一點:ArcGIS API - 調用函數onClick()

require(["esri/map", 
    "esri/layers/ArcGISTiledMapServiceLayer", 
    "esri/geometry/Point", 
    "esri/SpatialReference", 
    "dojo/domReady!"], 
    function (Map, Tiled, Point, SpatRef) { 

... 

     function veranderTiled(jaar){ 
      map_Thema_2.removeAllLayers(); 
      tiled = new Tiled(
      "http://tiles.arcgis.com/tiles/nSZVuSZjHpEZZbRo/arcgis/rest/services/Historische_tijdreis_"+jaar+"/MapServer"); 
      map_Thema_2.addLayer(tiled); 
     } 

     ... 

    }); 

我想在我的頁面隨機放置一個按鈕時調用這個函數。就像這樣:

<input name="" type="button" onClick="veranderTiled(2015)" value="Ander jaar" /> 

函數本身工作正常,但我似乎無法從需要(...)部件之外的任何調用它。我不確定javascript如何處理這種可訪問性(主要用於C++),但我確實想知道爲了能夠從此特定腳本之外調用此函數,應該更改哪些內容。

編輯:正如所料,控制檯返回該函數未定義。有沒有辦法將它指向正確的位置(如map.veranderTiled(2015)?)

回答

2

這是一個範圍問題 - 正如您猜測的,該函數僅在require回調的範圍內定義。

通常有2種方法可以解決這個問題。

第一種方法是給按鈕一個ID並在需要回調中爲其分配事件處理程序(假設您的腳本在body的末尾,或者您需要dojo/domReady!等待身體首先加載):

require(..., function (...) { 
    ... 

    document.getElementById('veranderTiledButton').onclick = function() { 
     veranderTiled(2015); 
    }; 
}); 

(你也可以使用dojo/on掛鉤的情況下,雖然它不是在這種情況下是至關重要的。)

第二種方法是使函數全局可用,它一般不提倡,因爲全球如果你的代碼執行的話,可變範圍很快會變成狂野的西部是零星的:

var veranderTiled; // Declare outside to be globally available 

require(..., function (...) { 
    ... 

    // Define inside to be able to use loaded modules 
    veranderTiled = function (jaar) { 
     ... 
    }; 

    ... 
});