Documentation menu
Example
Live updates with updateData
Move a fleet of vans every two seconds by sending only what changed. DataLayer.updateData patches features by id, so a position feed of hundreds of vehicles never re-sends the whole collection the way setData does.
ts
import { createMap, DataLayer } from "@mapmap/maps";
const map = createMap({
container: "map",
apiKey: "snk_...",
attributionPosition: "bottom-left",
center: [-0.12, 51.51],
zoom: 11.5,
});
await map.whenReady();
// updateData finds features by id: promoteId names the property holding it.
const vans = Array.from({ length: 40 }, (_, i) => ({
id: "van-" + i,
lng: -0.12 + Math.cos(i) * 0.06,
lat: 51.51 + Math.sin(i * 1.7) * 0.03,
}));
const fleet = new DataLayer(map, {
data: {
type: "FeatureCollection",
features: vans.map((v) => ({
type: "Feature",
properties: { id: v.id },
geometry: { type: "Point", coordinates: [v.lng, v.lat] },
})),
},
promoteId: "id",
style: { simple: { color: "#1a6bff" } },
});
// Stand-in for your feed: nudge every van, then patch only the geometry.
setInterval(() => {
for (const v of vans) {
v.lng += (Math.random() - 0.5) * 0.002;
v.lat += (Math.random() - 0.5) * 0.0012;
}
fleet.updateData({
update: vans.map((v) => ({
id: v.id,
newGeometry: { type: "Point", coordinates: [v.lng, v.lat] },
})),
});
}, 2000);Worth knowing
- updateData takes remove, add and update in one diff and applies them in that order. Updating an id that is not in the layer is ignored rather than an error, and the patched data is what a theme swap re-adds.
- updateData needs a unique id on every feature from the start: set feature.id or promoteId when you create the layer. DataLayer throws, naming the fix, when the ids were generated.
- A diff also changes properties: addOrUpdateProperties: [{ key: "status", value: "late" }] on an update entry restyles one van without touching its position.