Dynamic GeoJSON renders on HERE API for JavaScript engine
It often happens that you need to render GeoJSON in on the fly based on user inputs and interactions (changing date/time, thresholds, ...etc.)
HERE APIs for JavaScript rendering engine has a featured GeoJSON reader responsible for fetching and interpreting GeoJSON data. It creates an instance of H.map.Object that can be displayed on the map.
// define and initialize HERE GeoJSON reader
let reader = new H.data.geojson.Reader(null, {
disableLegacyMode: true,
style: function (mapObject) {
if (mapObject instanceof H.map.Polyline) {
let style = getTrafficBasedStyle(parseFloat(mapObject.data.CONGESTION_FACTOR));
mapObject.setStyle(style);
}
}
});
let geoJsonLayer_HERE = reader.getLayer();
// Please note a couple of points HERE
// 1- I initially did set the geoJOSN reader to null, and will be set later based on user input or interactions
// 2- I initially set the style to a function that returns a variable style based on the GeoJOSN feature properties value
// add HERE geoJSON reader layer to the map to it can be ready to display the features once we set the source
map.addLayer(geoJsonLayer_HERE);
async function init_GeoJSON(file_GeoJSON) {
const response = await fetch(file_GeoJSON);
const data = await response.json();
return data;
}
function getTrafficBasedStyle(congestionFactor) {
let style;
if (congestionFactor <= 0.5) {
style = {
strokeColor: '#61ba72', //green
lineWidth: 3
};
} else if (congestionFactor > 0.5 && congestionFactor <= 0.75) {
style = {
strokeColor: '#fecf00', //yellow
lineWidth: 4
};
} else if (congestionFactor > 0.75) {
style = {
strokeColor: '#ea232d', //red
lineWidth: 5
};
}
return style;
}
// make sure the execute the following logic whenever there is any user input/interaction that changes the geoJSON datasource and/or on the initialization
let geoJSON_data = await init_GeoJSON(`../output.geojson`);
geoJsonLayer_HERE.getProvider().getRootGroup().removeAll();
reader.parseData(geoJSON_data);