【问题标题】:How to pass custom fields into mapbox-gl js to create points on map?如何将自定义字段传递到 mapbox-gl js 以在地图上创建点?
【发布时间】:2019-09-30 12:18:09
【问题描述】:

我使用 mapbox 创建了一个地图,并绘制了多个可以与之交互的自定义​​点。我也在使用 Wordpress,并希望使用高级自定义字段来创建每个点,以便可以从非技术人员轻松管理它们。这些字段都已设置,但我无法将它们传递到我的 php 模板中的 javascript。

我尝试过使用循环,但无法在 javascript 中使用循环。这是我用来绘制点并希望使用高级自定义字段的 Mapbox 代码:

var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/coptmarketing/cjvi7hc4602dk1cpgqul6mz0b',
    center: [-76.615573, 39.285685],
    zoom: 16 // starting zoom
});

var geojson = {
    "type": "FeatureCollection",
    "features": [{
            "type": "Feature",
            "properties": {
                "title": "Shake Shack",
                "id": "shake-shack"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [-76.609844, 39.286894]
            }
        },
        {
            "type": "Feature",
            "properties": {
                "title": "Starbucks",
                "id": "starbucks"
            },
            "geometry": {
                "type": "Point",
                "coordinates": [-76.619071, 39.286649]
            }
        }
    ]
};

我已将数据存储在 JSON 数组中:

[{"title":"Shake Shack","slug":"shake-shack","latitude":"-76.609844","longitude":"39.286894"},{"title":"Starbucks","slug":"starbucks","latitude":"-76.619071","longitude":"39.286649"}]

如何将其插入 geoJSON?

【问题讨论】:

  • 这个问题对我来说有点太模糊了,无法离散地解决。至少,在您获取数据时向我们展示 Wordpress 的原始输出。如果我必须这样做,我可能会采用以下两种方法之一:1. 使用 Wordpress 的本机 JSON api,它现在随附。 2. 在 PHP 中,循环自定义字段,构建我将存储在 HTML 中的 JSON 对象。然后,从 JS 中抓取 JSON 对象并插入 GeoJSON
  • 谢谢,我正在寻找一些指导。我将从你的建议开始。

标签: javascript php wordpress mapbox advanced-custom-fields


【解决方案1】:

想通了:

首先,我创建了一个插件,将自定义帖子数据存储在 JSON 数组中,并将其存储在服务器上。每次我更新、保存或删除帖子时,这也会更新。这是 JSON 示例:

data = {"placeList": [{"title":"Shake Shack","slug":"shake-shack","latitude":"-76.609844","longitude":"39.286894"},{"title":"Starbucks","slug":"starbucks","latitude":"-76.619071","longitude":"39.286649"}]}

然后在 php 文件中,我调用了 .json 文件并在我的 javascript 中,将数组插入到 GeoJSON 中:

var placeJson = data;

        var geojson = {
          type: "FeatureCollection",
          features: [],
        };

        for (i = 0; i < placeJson.placeList.length; i++) {

          geojson.features.push({
            "type": "Feature",
            "geometry": {
              "type": "Point",
              "coordinates": [placeJson.placeList[i].latitude, placeJson.placeList[i].longitude]
            },
            "properties": {
              "id": placeJson.placeList[i].slug,
              "title": placeJson.placeList[i].title
            }
          });
        }

【讨论】:

    猜你喜欢
    • 2021-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    相关资源
    最近更新 更多