Я использую mapbox для рисования маркеров и кластеров, и для этого я использую querySourceFeatures
(https://docs.mapbox.com/mapbox-gl-js/api/#map # querysourcefeatures ).
Я основал свою настройку на blogpost by Mapbox (https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/)
Но после обновления моего источника (используя setData
) querySourceFeatures
не обновляется, поэтому я не вижу свои новые данные отображается на карте.
Вот мой код, немного упрощенный:
const createData = ( ) => {
markersToGenerate += 10;
const totalFeatures = [{ "type": "Feature", "properties": { "id": "ak16994521", "mag": 2.3, "time": 1507425650893, "felt": null, "tsunami": 0 }, "geometry": { "type": "Point", "coordinates": [ -151.5129, 63.1016, 0.0 ] } },
/** repeat this for 1200 times **/
];
const splicedFeatures = totalFeatures.splice(0, markersToGenerate);
return {
'type': 'geojson',
'data': {
"type": "FeatureCollection",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": splicedFeatures
},
'cluster': true,
'clusterRadius': 80,
'clusterProperties': {
// keep separate counts for each magnitude category in a cluster
'mag1': ['+', ['case', mag1, 1, 0]],
'mag2': ['+', ['case', mag2, 1, 0]],
'mag3': ['+', ['case', mag3, 1, 0]],
'mag4': ['+', ['case', mag4, 1, 0]],
'mag5': ['+', ['case', mag5, 1, 0]]
}
}
}
map.on('load', function() {
// add a clustered GeoJSON source for a sample set of earthquakes
map.addSource('earthquakes', createData());
// circle and symbol layers for rendering individual earthquakes (unclustered points)
map.addLayer({
'id': 'earthquake_circle',
'type': 'circle',
'source': 'earthquakes',
'filter': ['!=', 'cluster', true],
'paint': {
'circle-color': [
'case',
mag1,
colors[0],
mag2,
colors[1],
mag3,
colors[2],
mag4,
colors[3],
colors[4]
],
'circle-opacity': 0.6,
'circle-radius': 12
}
});
map.addLayer({
'id': 'earthquake_label',
'type': 'symbol',
'source': 'earthquakes',
'filter': ['!=', 'cluster', true],
'layout': {
'text-field': [
'number-format',
['get', 'mag'],
{ 'min-fraction-digits': 1, 'max-fraction-digits': 1 }
],
'text-font': ['Open Sans Semibold', 'Arial Unicode MS Bold'],
'text-size': 10
},
'paint': {
'text-color': [
'case',
['<', ['get', 'mag'], 3],
'black',
'white'
]
}
});
// every 5 seconds add a marker to the source and set that
setInterval( () => {
console.log('Update source');
map.getSource('earthquakes').setData(createData());
}, 5000)
// objects for caching and keeping track of HTML marker objects (for performance)
var markers = {};
var markersOnScreen = {};
function updateMarkers() {
console.log("# updateMarkers called")
var features = map.querySourceFeatures('earthquakes');
// There are more features retrieved - since some are displayed on multiple tiles ... so they are counted double. The point here is to show the count isn't increasing.
console.log("Total features displayed = " + features.reduce( (totalCount, feature) => {
if (feature.properties.cluster) {
return totalCount + feature.properties.point_count;
} else {
return totalCount + 1;
}
}, 0));
}
Для полного (действующего) кода, проверьте этот код: https://codepen.io/skarnl/pen/RwWrdPm?editors=0010
Некоторое дополнительное объяснение, как я это тестировал:
Я добавил метод с именем createData
, который сгенерирует новый Geo Json, и использовал его для вызова setData
. Я также добавил setInterval
, чтобы добавить 10 маркеров каждые 5 секунд.
Единственный способ, которым я мог работать, состоял в том, чтобы удалить и слой и источник и снова добавьте их снова. Это работает ... но это может привести к мерцанию, так как слой полностью удален.
Что я здесь не так делаю?