2012-11-02 47 views
1

我想在我的MVC 4網頁上實現一些基於位置的服務功能。我對使用Javascript和MVC完全陌生,所以請耐心等待。功能外的Javascript導致未捕獲的引用異常

這是我目前的網頁:

@{ 
    ViewBag.Title = "OnlineUsers"; 
} 


<html> 
<head> 
    <title>Online Users</title> 
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.4/leaflet.css" /> 
    <script src="http://cdn.leafletjs.com/leaflet-0.4/leaflet.js"></script> 

</head> 
<body> 
    <button onclick="showMap()">Show Map</button> 
    <button onclick="goToLocation()">My Location</button> 
    <div id="locationDetails"></div> 
    <div id="map" style="height: 500px; width: 800px"></div> 

    <script type="text/javascript"> 
     **var map = L.map('map');** 
     function showMap() { 

      var map = L.map('map'); 
      L.tileLayer('http://{s}.tile.cloudmade.com/BC9A493B41014CAABB98F0471D759707/997/256/{z}/{x}/{y}.png', { 
       maxZoom: 18, 
       attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="http://cloudmade.com">CloudMade</a>' 
      }).addTo(map); 

      map.locate({ setView: true, maxZoom: 16 }); 
     } 

    </script> 
</body> 
</html> 

在腳本部分的頂部是下面的一段代碼:var map = L.map('map');。如果我將這段代碼包含在一個函數中,頁面加載並調用該函數將創建該映射。但是,如果我將此代碼(或任何其他JS代碼)放在函數之外,則該頁面將無法加載。

我使用Chrome的調試器和控制檯顯示以下錯誤:

Uncaught ReferenceError: L is not defined 

我沒有看到「L」被定義任何地方,但後來爲什麼從函數中調用時,這項工作?

+0

是因爲地圖需要一些參數嗎? - 試一試[http://leafletjs.com/](lettletjs.com/)'var map = L.map('map')。setView([51.505,-0.09],13); ' – Wez

回答

2

它在你的函數中起作用,因爲L是leaflet的一部分,它在你的函數被調用但不是在頁面加載時沒有加載。 L是其他東西的縮小表示。

通常要等到文檔準備就緒後,才能確定引用的js已加載,例如,如果您有jQuery的那麼下面

$(document).ready(function() { 
    var map = L.map('map'); 
} 

更新:它可能是緩慢的加載這個js,所以你可以把一張支票,因爲它是第一次出現,例如

window.setTimeout(initMap, 100); 

function initMap(){ 
     //this should check if your leaflet is available or wait if not. 
     if(typeof L=== "undefined"){ 
       window.setTimeout(initMap, 100); 
       return; 
     } 
     var map = L.map('map'); 
}; 
+0

試過這個,但仍然給出了同樣的錯誤。感謝您的建議,雖然 – Matt

+1

你需要''返回'內部if'塊 – user123444555621

+0

@ Pumbaa80謝謝。 – dove

相關問題