Dispose an OpenLayers Map

  const layers = map.getLayers().getArray();
  layers.forEach((layer) => {
    const source = layer.getSource();
    if (source && source.dispose) {
      source.clear();
      source.dispose();
    }
    if (layer.disposeInternal) {
      layer.disposeInternal();
    } else if (layer.dispose) {
      layer.dispose();
    }
    map.removeLayer(layer);
  });
  const olCanvas = map.getViewport().querySelector("canvas");
  if (olCanvas) {
    const gl = olCanvas.getContext("webgl") || olCanvas.getContext("webgl2");
    if (gl) {
      const loseContext = gl.getExtension("WEBGL_lose_context");
      if (loseContext) {
        loseContext.loseContext();
      } 
    }
  }
  map.getInteractions().clear();
  map.getOverlays().clear();
  map.dispose();
  map.setTarget(null);