[Maps API] How to check if map is fully rendered and why need to check it

Requirement

Sometimes, you may want to check if HERE map is fully loaded, just for doing something depending on it:

<br />map.addEventListener('mapviewchangeend', function () { console.log("HERE Map is loaded!");});<br />

Use Case

For example, you may want to enable some map features such as "vehicle restrictions" to enrich the content on your map:

<br />const style = map.getBaseLayer().getProvider().getStyle();var enabledFeatures = style.getEnabledFeatures();enabledFeatures.push({ feature: 'vehicle restrictions', mode: 'active & inactive' });style.setEnabledFeatures(enabledFeatures);<br />

If you put the above code directly in your script, the following error could happen:

<br />emo.html:50 Uncaught TypeError: Cannot read properties of undefined (reading 'push') at enabledFeatures (demo.html:50:22) at demo.html:69:9<br />

This is because when the code runs, the map is not fully rendered yet and there is nothing returned from style.getEnabledFeatures() call.

Resolution

1. As already shared, listen to the mapviewchangeend event, and add [] fallback to make it more robust:

<br />map.addEventListener('mapviewchangeend', function () { const style = map.getBaseLayer().getProvider().getStyle(); var enabledFeatures = style.getEnabledFeatures() || []; enabledFeatures.push({ feature: 'vehicle restrictions', mode: 'active & inactive' }); style.setEnabledFeatures(enabledFeatures);});<br />

2. Listen to the state of the map style specifically:

<br />const style = map.getBaseLayer().getProvider().getStyle();const onChangeHandler = (event) => { if (event.target.getState() === H.map.render.Style.State.READY) { style.removeEventListener('change', onChangeHandler); // Otherwise loops infinitely. var enabledFeatures = style.getEnabledFeatures() || []; enabledFeatures.push({ feature: 'vehicle restrictions', mode: 'active & inactive' }); }}`style.addEventListener('change', onChangeHandler)<br />

Reference

https://www.here.com/docs/bundle/maps-api-for-javascript-developer-guide-3.2/page/topics/features-modes.html#toggle-feature-modes-at-runtime
https://www.here.com/docs/bundle/maps-api-for-javascript-api-reference-3.2/page/H.Map.html#event:mapviewchangeend
* https://www.here.com/docs/bundle/maps-api-for-javascript-developer-guide-3.2/page/topics/vehicle-profile.html#enable-the-vehicle-restrictions-feature