2015-09-16 49 views
0

我想使用外部API來檢索GeoJSON數據並最終在地圖上顯示數據。我正在使用地圖的傳單庫,我面臨的問題是我從這個API獲得的數據看起來很好(即,如果我從console.log獲取數據,然後直接在「L」中使用它。 geoJson(這是什麼在這裏輸入)「它的工作原理),但由於某種原因,如果我嘗試使用該對象本身不起作用。從外部API解析GeoJSON與傳單

   var map = L.map('map').setView([48.85, 2.35], 13); 
       var stamenLayer = L.tileLayer('https://stamen-tiles-{s}.a.ssl.fastly.net/toner/{z}/{x}/{y}.png', { 
        attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, under <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a>. Data by <a href="http://openstreetmap.org">OpenStreetMap</a>, under <a href="http://creativecommons.org/licenses/by-sa/3.0">CC BY SA</a>.' 
       }).addTo(map); 

       function reqListener() { 
        console.log(this.response); 
       } 

       var oReq = new XMLHttpRequest(); 
       oReq.addEventListener("load", reqListener); 
       oReq.open("GET", "http://dataratp.opendatasoft.com/api/records/1.0/download?dataset=liste-des-commerces-de-proximite-agrees-ratp&rows=100&format=geojson"); 
       oReq.send(); 
       L.geoJson(**WHAT TO INPUT HERE**).addTo(map); 

不太清楚是什麼導致了問題,因爲數據看起來很好(我測試http://geojsonlint.com/)。

感謝您的幫助, 朱利安

回答

1

類型您收到的數據是一個字符串。 L.GeoJSON需要一個GeoJSON對象。您可以使用JSON.parse方法將字符串轉換爲對象:

JSON.parse()方法將字符串解析爲JSON。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

L.geoJson(JSON.parse(this.response)).addTo(map); 

下一步,你需要知道,XMLHttpRequest是異步的。請參閱:Easy to understand definition of "asynchronous event"?簡而言之,當調用L.GeoJSON時,oReq.send可能尚未準備好。這是eventlistener進來的地方。當oReq.send完成接收時,它調用reqListener方法。您需要在reqListener方法來建立L.GeoJSON層像這樣:

function reqListener() { 
    L.geoJson(JSON.parse(this.response)).addTo(map); 
} 

工作例如:http://plnkr.co/edit/ODe622?p=preview

+0

非常感謝它的作品!對於第一個關於stackoverflow的問題,我很滿意詳細的答案和反應性! – Julien

+0

不用了,謝謝你的歡迎和歡迎;) – iH8