@geogirafe/lib-geoportal
Version:
GeoGirafe is a flexible application to build online geoportals.
88 lines (87 loc) • 3.18 kB
JavaScript
import DOMPurify from 'dompurify';
class MapPosition {
constructor() {
Object.defineProperty(this, "center", {
enumerable: true,
configurable: true,
writable: true,
value: []
});
Object.defineProperty(this, "zoom", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "resolution", {
enumerable: true,
configurable: true,
writable: true,
value: 100
}); /* dummy default value because it should never be null. It will be recalculated when the map will be created */
Object.defineProperty(this, "scale", {
enumerable: true,
configurable: true,
writable: true,
value: 0
});
Object.defineProperty(this, "crosshair", {
enumerable: true,
configurable: true,
writable: true,
value: false
});
Object.defineProperty(this, "tooltip", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
}
get isValid() {
if (Number.isNaN(this.resolution)) {
return false;
}
if (!this.center[0] || !this.center[1] || Number.isNaN(this.center[0]) || Number.isNaN(this.center[1])) {
return false;
}
return true;
}
}
export default MapPosition;
/**
* Extracts map position details `map_x`, `map_y`, and `map_zoom` from the current URL's query parameters.
* @returns {MapPosition | undefined} A `MapPosition` instance if valid parameters are found, otherwise undefined.
*/
export function parseMapPositionFromUrl() {
const url = new URL(window.location.href);
const mapX = url.searchParams.get('map_x');
const mapY = url.searchParams.get('map_y');
const mapZoom = url.searchParams.get('map_zoom');
const crosshair = url.searchParams.get('map_crosshair');
const tooltip = url.searchParams.get('map_tooltip');
if (mapX && mapY && mapZoom) {
const newPosition = new MapPosition();
newPosition.center = [parseFloat(mapX), parseFloat(mapY)];
newPosition.zoom = parseFloat(mapZoom);
newPosition.crosshair = crosshair === 'true';
newPosition.tooltip =
DOMPurify.sanitize(tooltip, {
ALLOWED_TAGS: ['br', 'b', 'div', 'em', 'i', 'p', 'strong'],
ALLOWED_ATTR: []
}) ?? undefined;
return newPosition.isValid ? newPosition : undefined;
}
return undefined;
}
/**
* Update the current URL according to the MapPosition object in parameter
* @param position The MapPosition instance
*/
export function setUrlFromMapPosition(position) {
const url = new URL(window.location.href);
url.searchParams.set('map_x', JSON.stringify(position.center[0]));
url.searchParams.set('map_y', JSON.stringify(position.center[1]));
url.searchParams.set('map_zoom', JSON.stringify(position.zoom));
window.history.replaceState({}, '', url.toString());
}