rlayers
Version:
React Components for OpenLayers
1 lines • 4.06 kB
JavaScript
"use strict";(self.webpackChunkrlayers=self.webpackChunkrlayers||[]).push([[6142],{6142(e,n,t){t.d(n,{default:()=>a});const a="import React, {JSX} from 'react';\nimport {fromLonLat} from 'ol/proj';\nimport {Point} from 'ol/geom';\nimport {Feature} from 'ol';\nimport {Coordinate} from 'ol/coordinate';\nimport 'ol/ol.css';\n\nimport monument from './svg/monument.svg';\nimport {RMap, ROSM, RLayerVector, RStyle, RFeature, ROverlay} from 'rlayers';\n\nexport const coords: Record<string, Coordinate> = {\n 'Arc de Triomphe': [2.295, 48.8737],\n \"Place d'Italie\": [2.355, 48.831],\n Bastille: [2.369, 48.853],\n 'Tour Eiffel': [2.294, 48.858],\n Montmartre: [2.342, 48.887]\n};\n\nlet unique_id = 0;\n\nexport default function Interactions(): JSX.Element {\n // The features must be part of the state as they will be modified\n const [features, setFeatures] = React.useState(() =>\n Object.keys(coords).map(\n (f) =>\n new Feature({\n geometry: new Point(fromLonLat(coords[f])),\n name: f,\n uid: unique_id++\n })\n )\n );\n const vectorRef = React.useRef(null) as React.RefObject<RLayerVector>;\n return (\n <React.Fragment>\n <RMap\n className='example-map'\n initial={{center: fromLonLat([2.364, 48.82]), zoom: 11}}\n onClick={(e) => {\n const coords = e.map.getCoordinateFromPixel(e.pixel);\n features.push(new Feature({geometry: new Point(coords), uid: unique_id++}));\n // Why not setFeatures(features) ?\n // Because it won't have any effect -\n // unless you artificially create a new array\n // React won't know that something changed\n setFeatures([...features]);\n }}\n >\n <ROSM />\n\n <RLayerVector ref={vectorRef}>\n <RStyle.RStyle>\n <RStyle.RIcon src={monument} />\n </RStyle.RStyle>\n {features.map((f) => (\n <RFeature\n // This is the very important part: if we are going to be\n // adding or deleting features, we must have a key field\n // that won't be transient - we can't use the array index, as\n // it will change every time we delete a feature in the middle\n key={f.get('uid')}\n feature={f}\n onClick={(e) => {\n // This the deletion\n const idx = features.findIndex(\n (x) => x.get('uid') === e.target.get('uid')\n );\n if (idx >= 0) {\n features.splice(idx, 1);\n setFeatures([...features]);\n // It is very important to return false to stop the\n // event propagation - otherwise that same event will\n // also trigger the Map onClick\n return false;\n }\n }}\n >\n <ROverlay>\n <div className={'user-select-none'}>{f.get('uid')}</div>\n </ROverlay>\n </RFeature>\n ))}\n </RLayerVector>\n </RMap>\n <div className='mx-0 mt-0 mb-3 p-1 w-100 jumbotron shadow shadow'>\n <p>Click an empty space to add a monument or click a monument to delete it.</p>\n </div>\n </React.Fragment>\n );\n}\n"}}]);