2015-07-02 79 views
1

我正嘗試從鏈接加載小冊子地圖。如果我點擊第一個鏈接,地圖加載,那麼如果我點擊第二個鏈接,地圖不會加載。兩條鏈路都調用相同的功能。我無法理解發生了什麼事。 在此先感謝!從鏈接加載小冊子地圖

<!DOCTYPE html> 
<html> 
<head> 
    <title>Simple Leaflet Map</title> 
    <meta charset="utf-8" /> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css" /> 
</head> 
<body> 
    <a href="#" onclick="showMap('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')">OpenStreetMap</a><br> 
    <a href="#" onclick="showMap('http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png')">Thunderforest</a><hr> 
    <div id="map" style="width: 600px; height: 400px"></div> 

    <script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"> </script> 
    <script> 
     function showMap(url){ 
      var map = L.map('map').setView([-33.4387,-70.647], 14); 
      var mapLink = '<a href="http://openstreetmap.org">OpenStreetMap</a>';   

      L.tileLayer(url, { 
      attribution: 'Map data &copy; ' + mapLink, 
      maxZoom: 18, 
      }).addTo(map); 
     } 
    </script> 
</body> 
</html> 

回答

2

由於您試圖初始化地圖容器一秒鐘,所以出現錯誤。下面是你可以如何解決這個問題:

<!DOCTYPE html> 
<html> 
<head> 
    <title>Simple Leaflet Map</title> 
    <meta charset="utf-8" /> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
    <link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7/leaflet.css" /> 
</head> 
<body> 
    <a href="#" onclick="showMap('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')">OpenStreetMap</a><br> 
    <a href="#" onclick="showMap('http://{s}.tile.thunderforest.com/landscape/{z}/{x}/{y}.png')">Thunderforest</a><hr> 
    <div id="map" style="width: 600px; height: 400px"></div> 

    <script src="http://cdn.leafletjs.com/leaflet-0.7/leaflet.js"> </script> 
    <script> 

     var map; 

     function showMap(url){ 
      if(!map) 
      { 
       map = L.map('map').setView([-33.4387,-70.647], 14); 
      } 

      var mapLink = '<a href="http://openstreetmap.org">OpenStreetMap</a>';   

      L.tileLayer(url, { 
      attribution: 'Map data &copy; ' + mapLink, 
      maxZoom: 18, 
      }).addTo(map); 
     } 
    </script> 
</body> 
</html> 
+0

完美!謝謝!! –