Mapbox有时不加载标记

时间:2019-07-08 13:00:46

标签: javascript mapbox

我正在使用Mapbox,并且在我的本地主机中,它始终正确加载我的标记。但是,既然我已经部署了我的应用程序,则没有。

至少有时

我注意到,如果我加载页面,然后在页面加载之前,我切换到另一个选项卡,然后等待5秒钟,然后返回到我的应用程序所在的选项卡。它确实可以工作并加载标记。

此外,当我尝试设置要素状态时(当您将鼠标悬停在侧栏项目上且标记未加载的情况下)时,我收到错误消息:The source 'users' does not exist in the map's style.map.setFeatureState({source: 'users', id: i}, { hover: true})

我还注意到当标记未加载时map.on('load', fn)不会触发,因为如果我在其中添加console.log,则不会被记录。未加载)

因此未加载源...

所以,我猜想它是某种异步问题,或者说map.on('load', fn)的问题可能会遇到某些竞争条件:https://github.com/mapbox/mapbox-gl-js/issues/6707

这就是为什么当我花一些时间通过转到另一个选项卡然后再返回它时可以工作。

但是我想不出解决方案。

我有这个loadUsers函数,该函数对后端进行API调用,获取用户,然后调用map.on('load', fn)

我在获得用户时正在使用await:

     const res = await axios.get(`${apiUrl}?lat=${lat}&lng=${lng}`)
     const users = res.data;
     ...

谁能看到问题出在哪里?为什么我的标记没有加载?

我的网站正在运行:https://jamsesssion.com/

如果您检查并搜索以下文件,则可以在其中看到代码:在chrome控制台中按cmd + p并搜索文件。usersMap.js。

这是代码:

async function loadUsers(map, lat = 52.5, lng = 13.4, apiUrl = `/api/users/near?lat=${lat}&lng=${lng}`) {
  const res = await axios.get(`${apiUrl}?lat=${lat}&lng=${lng}`)

      const users = res.data;
      if (!users.length) {
        alert('Oooops! \n\nThere are no registered users in the place you searched yet, If you live there, register to Jamsession and tell your friends!');
        return;
      }

      const geoJsonMarkers = users.map( (place, i ) => {
        const [placeLng, placeLat] = place.location.coordinates;
        const position = { lat: placeLat, lng: placeLng };

        return {
          'type': 'Feature',
          'geometry': {
            'type': 'Point',
            'coordinates': [position.lng, position.lat]
          },
          'id': i,
          'properties': {
            'name': place.name,
            'genres': place.genres,
            'photo': place.photo,
            'slug': place.slug,
          }
        }
      })
      let markers = { 'features': geoJsonMarkers }

      map.on('load', function() {

        map.addSource('users', {
        type: "geojson",
        data: markers,
        cluster: true,
        clusterMaxZoom: 22,
        clusterRadius: 50,
        })

          map.addLayer({
            id: "singles",
            type: "circle",
            source: "users",
            filter: ["!has", "point_count"],
            paint: {
                'circle-radius': {
                    'base': 10,
                    'stops': [[5, 20], [13, 50], [14, 60]]
                },
                // 'circle-color': '#ddffc8',
                'circle-color':  ["case",
                ["boolean", ["feature-state", "hover"], false],
                '#ff4da6',
                '#ddffc8'
                ],
              }
          });
}

1 个答案:

答案 0 :(得分:1)

您可能需要将map.on('load'..)请求放置在loadUsers函数之外,以便地图等待loadUsers请求完成。您还可以创建一个单独的函数来添加源和图层,这些源也可以等待loadUsers请求。看起来可能像这样:

map.on('load', function () { loadUsers(addSources) });