添加标记时 Mapbox GL 集成出错:"Cannot read property 'coordinates' of undefined"

Error with Mapbox GL integration when adding markers: "Cannot read property 'coordinates' of undefined"

我一直致力于在 Webflow 的 CMS 中创建动态更新的 Mapbox GL 集成。我已经成功地创建了一个可以被 Mapbox 的 API 读取的特征数组,但是这些特征不会显示在地图上,因为坐标没有被创建地图标记的函数读取。

我收到以下错误 Cannot read property 'coordinates' of undefined at map-test-page:139,这是通过此行将经度和纬度分配给当前标记的地方:.setLngLat(marker.geometry.coordinates)

找到了部分解决方案 here,但我集成到网站中的代码没有 featuresInfeaturesAt 功能,这似乎是唯一可以包含的方法一个 includeGeometry: true 参数。

我很好奇我是否需要重新考虑我是如何创建标记并使用 map.on('click', ...) reference here.

之类的函数进行操作的

这里是minimal version that reproduces my issue.

如果您熟悉 Webflow 界面,您可以查看 read-only version of the site

如有任何帮助,我们将不胜感激!

这是我在页面上使用的 Mapbox 脚本:

 var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/strawpari/ckp2nu3dw6cwu17nt4kqwf1vv',
    center: [-13.723969, 48.360542],
        zoom: 2,
        pitch: 0,
        bearing: 0,
        antialias: true,
        interactive: true
  });

var geojson = {
  type: 'FeatureCollection',
  features: farmerArray,
};

// add markers to map
geojson.features.forEach(function(marker) {

  // create a HTML element for each feature
  var el = document.createElement('div');
  el.className = 'marker';

  // make a marker for each feature and add to the map
  new mapboxgl.Marker(el)
    .setLngLat(marker.geometry.coordinates)
        .setPopup(new mapboxgl.Popup({ offset: 25 }) // add popups
    .setHTML('<img src=\'' + marker.properties.image + '\' width=\'50\' height=\'50\' border-radius=\'50%\'>' + '<h3>' + marker.properties.title + '</h3><p>' + marker.properties.description + '</p>'))
    .addTo(map);
});

这里是嵌入在每个 CMS 项目中的代码,它将农民的信息添加到 Mapbox 正在读取的 farmerArray 中。双引号 "" 中的文本是 CMS 填充的动态信息的占位符。

var farmerArrayItem = 
JSON.stringify({
   type: 'Feature',
   geometry: {
      type: 'Point',
      coordinates: ["longitude", "latitude"]
   },
   properties: {
      title: "name",
      description: "text",
      image: "imagepath"
  }
});

farmerArray.push(farmerArrayItem);

您似乎没有尝试使用开发人员工具来调试您的代码。这绝对是您应该掌握的一项技能。

使用开发工具,很快就会看到临界点marker的值是一个字符串:

所以你只需要使用 JSON.parse:

geojson.features.forEach(function(markerString) {
  const marker = JSON.parse(markerString);

  // create a HTML element for each feature
  var el = document.createElement('div');
  el.className = 'marker';

  // make a marker for each feature and add to the map
  new mapboxgl.Marker(el)
    .setLngLat(marker.geometry.coordinates)