将buildLocationList()与Mapbox GL JS中的外部GeoJSON文件一起使用

时间:2019-03-16 18:11:48

标签: javascript geojson 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 += ' &middot; ' + 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,
    }
});
});

1 个答案:

答案 0 :(得分:0)

Mapbox GeoJSON Sources data属性可以是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);
    });
});