You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mapbox GL JS聚合点每5秒从PHP拉取GeoJSON实现实时更新咨询

实现方案

你只需要在原有代码的map.on('load')回调末尾新增定时更新数据源的逻辑即可,无需修改现有图层、交互配置,Mapbox会在数据源更新后自动重新计算聚合规则、渲染点位。

核心修改点

  1. 用setInterval设置定时任务,间隔时间可自定义
  2. 调用map.getSource('scooters').setData()拉取最新的GeoJSON数据
  3. 请求地址加时间戳参数,避免浏览器缓存旧的接口返回内容

完整修改后代码

map.on('load', () => {
  // Add a new source from our GeoJSON data and
  // set the 'cluster' option to true. GL-JS will
  // add the point_count property to your source data.
  map.addSource('scooters', {
    type: 'geojson',
    // Point to GeoJSON data. This example visualizes all M1.0+ scooters
    data: 'mapvehicles.php',
    cluster: true,
    clusterMaxZoom: 14, // Max zoom to cluster points on
    clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50)
  });

  map.addLayer({
    id: 'clusters',
    type: 'circle',
    source: 'scooters',
    filter: ['has', 'point_count'],
    paint: {
      'circle-color': [
        'step',
        ['get', 'point_count'],
        '#5CB66E',
        100,
        '#5CB66E',
        750,
        '#5CB66E'
      ],
      'circle-radius': [
        'step',
        ['get', 'point_count'],
        20,
        100,
        30,
        750,
        40
      ]
    }
  });

  map.addLayer({
    id: 'cluster-count',
    type: 'symbol',
    source: 'scooters',
    filter: ['has', 'point_count'],
    layout: {
      'text-field': '{point_count_abbreviated}',
      'text-font': ['DIN Offc Pro Medium', 'Arial Unicode MS Bold'],
      'text-size': 12
    }
  });

  map.addLayer({
    id: 'unclustered-point',
    type: 'circle',
    source: 'scooters',
    filter: ['!', ['has', 'point_count']],
    paint: {
      'circle-color': '#5F36B2',
      'circle-radius': 5,
      'circle-stroke-width': 2,
      'circle-stroke-color': '#fff'
    }
  });

  map.on('click', 'clusters', (e) => {
    const features = map.queryRenderedFeatures(e.point, {
      layers: ['clusters']
    });
    const clusterId = features[0].properties.cluster_id;
    map.getSource('scooters').getClusterExpansionZoom(
      clusterId,
      (err, zoom) => {
        if (err) return;

        map.easeTo({
          center: features[0].geometry.coordinates,
          zoom: zoom
        });
      }
    );
  });

  map.on('click', 'unclustered-point', (e) => {
    const coordinates = e.features[0].geometry.coordinates.slice();
    const vehid = e.features[0].properties.id;

    while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
      coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
    }

    new mapboxgl.Popup()
      .setLngLat(coordinates)
      .setHTML(
        `ID: ${vehid}`
      )
      .addTo(map);
  });

  map.on('mouseenter', 'clusters', () => {
    map.getCanvas().style.cursor = 'pointer';
  });
  map.on('mouseleave', 'clusters', () => {
    map.getCanvas().style.cursor = '';
  });
  
  // ========== 以下是新增的定时更新代码 ==========
  // 5000代表5秒更新一次,可根据需求调整数值,单位为毫秒
  setInterval(() => {
    // 接口地址后加时间戳参数,避免浏览器缓存旧数据
    map.getSource('scooters').setData(`mapvehicles.php?t=${Date.now()}`);
  }, 5000);
});

可调整配置说明

  • 更新间隔:修改setInterval的第二个参数即可,比如改成10000就是每10秒更新一次
  • 原有交互逻辑全部保留,无需额外修改:聚合点展开、散点弹窗的功能完全不受更新逻辑影响
  • 如果你发现接口请求被缓存,确认PHP接口已经正常输出最新GeoJSON的前提下,保留时间戳参数即可解决

内容的提问来源于stack exchange,提问作者jonasgud

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 16:54:04