Moving the map in a component and, trying to make it live, seeing that react-leaflet isn't really... reactive !

(See https://stackoverflow.com/questions/65763931/react-leaflet-update-map-center - basically: most of the map properties are immutable)
This commit is contained in:
Eric van der Vlist 2022-09-01 18:48:29 +02:00
parent 1f53fbd3be
commit 01fc789614
2 changed files with 45 additions and 16 deletions

View File

@ -19,30 +19,22 @@ import '@ionic/react/css/display.css';
/* Theme variables */
import './theme/variables.css';
/* Leaflet */
import './theme/leaflet.css';
/* Other imports */
/* Components */
import {MapContainer, TileLayer, Marker, Popup} from 'react-leaflet' ;
import LiveMap from './components/live-map'
import React from 'react';
setupIonicReact();
const position: [number, number] = [51.505, -0.09];
const App: React.FC = () => (
<IonApp>
<MapContainer center={position} zoom={13} scrollWheelZoom={false}>
<TileLayer
attribution='{"&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors"}'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={position}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
<React.StrictMode>
<LiveMap />
</React.StrictMode>
</IonApp>
);

View File

@ -0,0 +1,37 @@
import react from "react";
import { useState, useEffect } from "react";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
import { useMap } from 'react-leaflet';
import { Geolocation } from "@awesome-cordova-plugins/geolocation";
const LiveMap: react.FC = () => {
const initialPosition: [number, number] = [44.73574, 6.18981];
const [currentPosition, setCurrentposition] = useState(initialPosition);
const theMap = useMap();
useEffect(()=>{
Geolocation.getCurrentPosition().then((position) =>
{
setCurrentposition([position.coords.latitude, position.coords.longitude]);
theMap.setView([position.coords.latitude, position.coords.longitude], 13);
}
);
}, [])
return (
<MapContainer center={initialPosition} zoom={13} scrollWheelZoom={false}>
<TileLayer
attribution='{"&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors"}'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={currentPosition}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
);
};
export default LiveMap;