[英]Using buildLocationList() with an external GeoJSON file in Mapbox GL JS
我正在制作一個網頁地圖,只需點擊就可以飛到不同的位置,就像在這個Mapbox GL示例中一樣( https://docs.mapbox.com/help/tutorials/building-a-store-locator/#getting-started )。 但是,我試圖從外部文件加載GeoJSON功能,我可以得到點,但不是列表項。 基本上,我無法弄清楚如何使用此方法獲取列表(buildLocationList(stores);)。 有沒有辦法將外部GeoJSON文件的變量名稱設置為“存儲”。 任何幫助,將不勝感激。
var stores = "https://raw.githubusercontent.com/aarontaveras/Test/master/sweetgreen.geojson";
map.on('load', function () {
// Add the data to your map as a layer
map.addLayer({
id: 'locations',
type: 'symbol',
// Add a GeoJSON source containing place coordinates and information.
source: {
type: 'geojson',
data: stores
},
layout: {
'icon-image': 'circle-15',
'icon-allow-overlap': true,
}
});
// Initialize the list
buildLocationList(stores);
});
function buildLocationList(data) {
for (i = 0; i < data.features.length; i++) {
// Create an array of all the stores and their properties
var currentFeature = data.features[i];
// Shorten data.feature.properties to just `prop` so we're not
// writing this long form over and over again.
var prop = currentFeature.properties;
// Select the listing container in the HTML
var listings = document.getElementById('listings');
// Append a div with the class 'item' for each store
var listing = listings.appendChild(document.createElement('div'));
listing.className = 'item';
listing.id = "listing-" + i;
// Create a new link with the class 'title' for each store
// and fill it with the store address
var link = listing.appendChild(document.createElement('a'));
link.href = '#';
link.className = 'title';
link.dataPosition = i;
link.innerHTML = prop.address;
// Create a new div with the class 'details' for each store
// and fill it with the city and phone number
var details = listing.appendChild(document.createElement('div'));
details.innerHTML = prop.city;
if (prop.phone) {
details.innerHTML += ' · ' + prop.phoneFormatted;
}
我能夠輕松地從外部源加載數據,但仍然在努力構建列表。
var stores = 'https://raw.githubusercontent.com/aarontaveras/Test/master/sweetgreen.geojson';
map.on('load', function () {
map.addSource("locations", {
type: 'geojson',
data: stores
});
map.addLayer({
"id": "locations",
"type": "symbol",
"source": "locations",
"layout": {
'icon-image': 'circle-15',
'icon-allow-overlap': true,
}
});
});
Mapbox GeoJSON Sources 數據屬性可以是GeoJSON文件的URL,也可以是內聯GeoJSON。 因此,您可以獲取GeoJSON數據並將其直接傳遞給源,並使用它來構建您的位置列表。
考慮示例:
map.on('load', () => {
fetch(stores)
.then(response => response.json())
.then((data) => {
map.addSource("locations", {
type: 'geojson',
data: data
});
map.addLayer(...);
buildLocationList(data);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.