2015-05-07 85 views
0

我喜歡畫畫幾個不同的小片段(GPX文件),每一個單獨的傳單地圖幾種不同的單張地圖

有了這個代碼,我試圖解決該問題寫上,即單張需要一個新的層在地圖

我用「層」 - 陣列存儲所有地圖參考...

<script> 
    var layers = []; 
    var i = 0; 
    var ref; 
</script> 
@for(segment <- segments) { 
    <div id="@segment.id" style="height:300px"></div> 
    <script> 
     layers[i] = L.map("@segment.id"); 

     L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { 
     }).addTo(layers[i]); 

     var url = '/assets/gpx_files/@segment.gpxPath'; 

     new L.GPX(url, { 
      async: true, 
      marker_options: { 
       startIconUrl: '/assets/images/pinIcon.png', 
       endIconUrl: '/assets/images/pinIcon.png', 
       shadowUrl: '/assets/images/pinIconShadow.png' 
      } 
     }).on('loaded', function(e) { 
      layers[i].fitBounds(e.target.getBounds()); 
     }).addTo(layers[i]); 
     i = i+1; 
    </script> 

(我有一個存儲了每個段的新層「層」 - 陣列,因爲傳單否則無法處理)

但單張不喜歡

layer[i].fitBounds 

- >類型錯誤:層[i]是未定義

有沒有人對我來說是個好主意?

+0

你能在一個'的console.log(層)的地方'前行引發錯誤,所以我們可以看到最新回事?或者更好的是,你能不能到位這在一個在線演示?地圖容器是否被創建?是否正確插入了@ segment.id? – snkashis

+0

我構建了一個小例子,但是我沒有找到鏈接gpx文件的方法。 http://jsbin.com/xovuseqata/2/edit?html,css,output 如果將行「var ref = layers [i];」替換爲「在「圖層[i]」出現問題時,當前只有最後一張地圖顯示該曲目。 我測試了@ segment.id,它絕對正確工作。 – Tauling

+0

作爲旁註,您不應該在同一頁面上包含Leaflet 0.5和Mapbox 2.1.9。刪除'http:// cdn.leafletjs.com/leaflet-0.5/leaflet.js'引用。 – snkashis

回答

0

嘗試在未定義對象上調用fitBounds時發生錯誤。 此處的代碼塊可解決此問題。請注意,我如何將地圖引用(ref:ref)傳遞給GPX的選項散列,以便日後清晰地檢索它,而不是試圖通過索引獲取它.GPX檢索操作是異步的,並且不能保證它何時完成,所以你需要知道這一點。這段代碼將這個延遲排除在等式之外。

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset=utf-8 /> 
    <meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' /> 
    <script src='https://api.tiles.mapbox.com/mapbox.js/v2.1.9/mapbox.js'></script> 
    <link href='https://api.tiles.mapbox.com/mapbox.js/v2.1.9/mapbox.css' rel='stylesheet' /> 
</head> 
<body> 
<script src="https://rawgithub.com/mpetazzoni/leaflet-gpx/master/gpx.js"></script> 

<div id="map0" style="height:300px"></div> 
<div id="map1" style="height:300px"></div> 
<div id="map2" style="height:300px"></div> 
<div id="map3" style="height:300px"></div> 
<script> 
var layers = []; 
var i = 0; 
var map = "map"; 
for(var i=0;i<4;i++){ 
    layers[i] = L.map(map.concat(i)); 
    var ref = layers[i]; 
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { 
    }).addTo(ref); 

    var url = 'https://www.mapbox.com/mapbox.js/assets/data/run.gpx'; 

    new L.GPX(url, { 
    ref:ref, 
    async: true 
    }).on('loaded', function(e) { 
e.target.options.ref.fitBounds(e.target.getBounds()); 
    }).addTo(ref); 
} 
</script> 

見輸出@http://output.jsbin.com/yazafuvika/1/