UNL Map JSUNL Map JS DocsExamplesUpdate a feature in realtime

Update a feature in realtime

Change an existing feature on your map in real-time by updating its data.

Note
If you want to test this example, edit it in JSFiddle or CodePen and replace the "YOUR-OWN-API-KEY" and "YOUR-OWN-VPM-ID" placeholders with your actual api key and vpm id.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Update a feature in realtime</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
<script src="https://unpkg.com/unl-map-js@0.1.5/lib/unl-map-js.js"></script>
<link href="https://unpkg.com/unl-map-js@0.1.5/lib/unl-map-js.css" rel="stylesheet" />
<link
href="https://unpkg.com/maplibre-gl@2.1.9/dist/maplibre-gl.css"
rel="stylesheet"
/>
<style>
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
</style>
</head>
<body>
<div id="map"></div>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var map = new UnlSdk.Map({
container: "map",
apiKey: "YOUR-OWN-API-KEY",
vpmId: "YOUR-OWN-VPM-ID",
zoom: 0,
});
map.on("load", function () {
// We use D3 to fetch the JSON here so that we can parse and use it separately
// from GL JS's use in the added source. You can use any request method (library
// or otherwise) that you want.
d3.json(
"https://u-n-l.github.io/unl-map-js-docs/assets/hike.geojson",
function (err, data) {
if (err) throw err;
// save full coordinate list for later
var coordinates = data.features[0].geometry.coordinates;
// start by showing just the first coordinate
data.features[0].geometry.coordinates = [coordinates[0]];
// add it to the map
map.addSource("trace", { type: "geojson", data: data });
map.addLayer({
id: "trace",
type: "line",
source: "trace",
paint: {
"line-color": "yellow",
"line-opacity": 0.75,
"line-width": 5,
},
});
// setup the viewport
map.jumpTo({ center: coordinates[0], zoom: 14 });
map.setPitch(30);
// on a regular basis, add more coordinates from the saved list and update the map
var i = 0;
var timer = window.setInterval(function () {
if (i < coordinates.length) {
data.features[0].geometry.coordinates.push(coordinates[i]);
map.getSource("trace").setData(data);
map.panTo(coordinates[i]);
i++;
} else {
window.clearInterval(timer);
}
}, 10);
}
);
});
</script>
</body>
</html>