2016-05-16 101 views
1

我已經有一個矢量地圖集上的tileset,通過上傳包含代表澳大利亞維多利亞州特定郊區的多邊形的geojson文件創建。我的矢量圖集具有三個屬性 - 郊區,州,郵政編碼 - 對應於geojson中的特徵屬性。Mapbox WebGL JS - querySourceFeatures()函數與矢量瓷磚來源

我也可以通過Mapbox web gl js庫成功查詢這些屬性以獲取準確的地圖。例如,我有一張地圖工作,當我點擊一個突出顯示的多邊形時會顯示一個彈出窗口,並且彈出窗口正確顯示了郊區的屬性(郊區,州,郵政編碼)。

現在我想在我的網頁中訪問這些屬性 - 對於我的tileset中的每個功能。我基本上想要將這些屬性作爲列表轉儲到地圖外的div中;只是列出每個郊區及其屬性。爲此,我試圖使用MapBox Web GL JS庫的querySourceFeatures函數。我掙扎了一下。

這是我的代碼。我的地圖按預期顯示。但在JS控制檯中,我只是得到一個空數組。

這裏是我的代碼

var map = new mapboxgl.Map({ 
    container: 'map', // container id 
    style: 'mapbox://styles/mapbox/streets-v8', //stylesheet location 
    center: [144.96, -37.81], // starting position 
    zoom: 8, // starting zoom, 
    hash:true 
}); 

// Add zoom and rotation controls to the map. 
map.addControl(new mapboxgl.Navigation()); 

map.on('load', function() { 
    map.addSource('charlieSource', { 
     type: 'vector', 
     url: 'mapbox://charlie.962dstid' 
    }); 


    map.addLayer({ 
    "id": "charlielayer", 
    "type": "fill", 
    "source": "charlieSource", 
    "source-layer": "my-source-layer-name", 
    "layout": {}, 
    "paint": { 
     "fill-color": "#00525a", 
     "fill-opacity": 0.5 
    } 

    }); 

    var myFeatures = map.querySourceFeatures('charlieSource', 
     { 
      sourceLayer: 'my-source-layer-name', 
      // i'm confident there is data matching this filter 
      filter: ["==", "postcode", "3000"] 
     } 
     ); 

    console.log(myFeatures); 


}); 

的DOCO比較清淡,所以如果我正確使用querySourceFeatures功能我不知道。如果它的東西非常簡單,我總是JS noob很抱歉。

在我的控制檯中,我只是得到一個長度爲零的數組。不知道該從哪裏出發。

我正在使用地圖箱web gl js庫的v0.18.0。

回答

1

編輯:添加源後,您必須等待瓷磚加載前調用queryRenderedFeatures。此代碼應解決您的問題:你已經發布

var wasLoaded = false; 
map.on('render', function() { 
    if (!map.loaded() || wasLoaded) return; 
    var myFeatures = map.querySourceFeatures('charlieSource', { 
     sourceLayer: 'my-source-layer-name', 
     filter: ["==", "postcode", "3000"] 
    }); 
    console.log(myFeatures); 
    wasLoaded = true; 
}); 

一切看起來是正確的,查理。如果沒有使用數據的功能演示,我無法找出問題所在。

您是否嘗試將您的過濾器從["==", "postcode", "3000"]更改爲["==", "postcode", 3000]? (將3000轉換爲數字而不是字符串)

您確定要搜索的數據在視口內嗎? querySourceFeatures僅適用於視口內的數據。

您確定您的sourcesourceLayer的值是正確的?

+0

謝謝盧卡斯。回答你的問題。郵政編碼是一個字符串,所以這不是問題。我的數據在視口內。源和sourceLayer是正確的,據我所知。 我在控制檯中找到'幾何超出允許的範圍',但是我在我的所有地圖上都得到了這一點,而不管我是否使用querySourceFeatures函數。 你可以在這裏看到我的工作代碼 - http://where-we-build.pancakeapps.com/example-04.html – Charlie

+0

我想知道是否在源文件加載之前使用函數啓動了一些東西?你有任何建議來處理這個問題嗎? 謝謝。感謝你的幫助。 – Charlie

+0

你完全正確!上面編輯了我的答案。 –