有没有办法将API数据转换为Mapbox图层?

问题描述 投票:1回答:1

我在下面有一个回调函数,可以从Eventbrite API生成数据。目前,此功能可以通过“新标记”方法在我的Mapbox地图上生成标记。但是,我想通过“Mapbox addLayer”方法将这些数据生成到地图上的图层中,而不是标记。

    callbackEventbrite(function(result){
    const keys = Object.values(result);
    for(const key of keys){
        geojson = {
            type: 'featureCollection',
            features: [{
                type: 'feature',
                geometry: {
                    type: 'Point',
                    coordinates: [key.venue.longitude, key.venue.latitude]
                }
            }]
        }
        eventInfo.push(
            {"longitude": key.venue.longitude , "latitude": key.venue.latitude , "name": key.name.text, "venue": key.venue.name, "date": key.start.local, "category": key.category_id}
        );
    }
});

我基本上想要这个,它根据几何的坐标在地图上生成符号,但是使用API​​数据。

map.addLayer({
        "id": "locations",
        "type": "symbol",
        "source": {
            "type": "geojson",
            "data": {
                "type": "FeatureCollection",
                "features": [
                    {
                      "type": "Feature",
                      "properties": {
                        "Title": "The Congress Inn",
                        "Description": "Pub located in Longton",
                        "Type": "Pub",
                        "Address": "14 Sutherland Rd, Stoke-on-Trent ST3 1HJ",
                        "Longitude": 2.1316,
                        "Latitude": 52.9878,
                        "icon": "bar"
                      },
                      "geometry": {
                        "coordinates": [
                          -2.131836,
                          52.987238
                        ],
                        "type": "Point"
                      }
                    },

任何帮助深表感谢!谢谢

javascript ajax mapbox layer mapbox-gl-js
1个回答
2
投票

这应该相当简单,您只需要在Eventbrite响应中构建一个功能数组。

  1. 首先构建一个geojson功能数组,以便在源代码中使用。
  2. 然后在添加图层之前单独将源添加到地图。您将使用刚刚在源中创建的要素数组。
  3. 将源添加到地图后,您可以创建图层并引用图层中的源。

尝试下面的代码来帮助您入门。如果它适用于您的情况,请告诉我。

var featureArr;
callbackEventbrite(function(result) {
  const keys = Object.values(result);
  for (const key of keys) {
    var feature = {
      "type": "Feature",
      "id": key.venue.id,
      "geometry": {
        "type": "Point",
        "coordinates": [key.venue.longitude, key.venue.latitude]
      },
      "properties": {
        "title": key.venue.name,
        "description": key.venue.description,
        "icon": "bar"
      }
    };
    featureArr.push(feature);
  }
}


map.addSource("mySource", {
  "type": "geojson",
  "data": {
    "type": "FeatureCollection",
    "features": featureArr
  }
});

map.addLayer({
  "id": "locations",
  "type": "symbol",
  "source": "mySource",
  "layout": {
    "text-font": ["Open Sans Semibold", "Arial Unicode MS Bold"],
    "text-offset": [0, 0.6],
    "text-anchor": "top",
  }
});

注意:我不知道Eventbrite的响应对象中有什么,所以一些key.value.xyz组成了变量

© www.soinside.com 2019 - 2024. All rights reserved.