vue3-openlayers
Version:
OpenLayers Wrapper for Vue3
69 lines (68 loc) • 2.07 kB
JavaScript
import { shallowRef, onUnmounted, watch } from "vue";
import usePropsAsObjectProperties from "./usePropsAsObjectProperties.js";
import { useOpenLayersEvents, COMMON_EVENTS, VECTOR_SOURCE_EVENTS, TILE_SOURCE_EVENTS, IMAGE_SOURCE_EVENTS } from "./useOpenLayersEvents.js";
import projectionFromProperties from "../helpers/projection.js";
import TileSource from "ol/source/Tile";
import VectorSource from "ol/source/Vector";
import ImageSource from "ol/source/Image";
function useSource(SourceClass, layer, props, eventsToHandle = [], sourceUpdateActions) {
function getProperties() {
return usePropsAsObjectProperties({
...props,
...props.projection ? {
projection: projectionFromProperties(
props.projection
)
} : {}
});
}
const source = shallowRef(new SourceClass(getProperties()));
updateSource();
function updateSource() {
layer?.value?.setSource(null);
const properties = getProperties();
source.value.setProperties(properties);
for (const key in properties) {
const keyInObj = key;
if (properties[keyInObj] !== void 0) {
source.value.set(key, properties[keyInObj]);
}
}
if (sourceUpdateActions) {
sourceUpdateActions(source.value);
}
layer?.value?.setSource(source.value);
useOpenLayersEvents(source, [
...COMMON_EVENTS,
...getSourceEvents(),
...eventsToHandle
]);
return source;
}
function getSourceEvents() {
const src = source.value;
if (src instanceof VectorSource) {
return VECTOR_SOURCE_EVENTS;
} else if (src instanceof TileSource) {
return TILE_SOURCE_EVENTS;
} else if (src instanceof ImageSource) {
return IMAGE_SOURCE_EVENTS;
}
return [];
}
function removeSource() {
layer?.value?.setSource(null);
}
onUnmounted(removeSource);
watch(source, updateSource);
watch(() => layer, updateSource);
watch(() => props, updateSource, { deep: true });
return {
source,
updateSource,
removeSource
};
}
export {
useSource as default
};