Attempt to create a new, more react friendly slippy map library.

This commit is contained in:
vdv committed 2022-09-06 00:08:17 +02:00
1 parent a154a5aa44
commit 9e8aec244e
16 files changed
+3899 -505

No files matched your search

+2 -7
View File
@@ -16,15 +16,12 @@ import '@ionic/react/css/text-transformation.css';
import '@ionic/react/css/flex-utils.css';
import '@ionic/react/css/display.css';
import { Provider } from 'react-redux';
/* Theme variables */
import './theme/variables.css';
/* Components */
import LiveMap from './components/live-map';
import store from './store/index';
import Map from './components/map';
import React from 'react';
setupIonicReact();
@@ -32,9 +29,7 @@ setupIonicReact();
const App: React.FC = () => (
<IonApp>
<React.StrictMode>
<Provider store={store}>
<LiveMap />
</Provider>
<Map />
</React.StrictMode>
</IonApp>
);
+55
View File
@@ -0,0 +1,55 @@
import React from 'react';
import { PigeonProps, Point } from 'pigeon-maps';
import GPX from 'gpx-parser-builder';
import { round } from 'lodash';
const GPXFigure: React.FC<PigeonProps> = (props: PigeonProps) => {
const gpx = GPX.parse(localStorage.getItem('gpx'));
const dirtyLatLngToPixel = (point: Point) => {
if (props.mapState === undefined) {
return undefined;
}
const latRange = props.mapState.bounds.ne[0] - props.mapState.bounds.sw[0];
const lonRange = props.mapState.bounds.ne[1] - props.mapState.bounds.sw[1];
const x = round(
((point[0] - props.mapState.bounds.sw[0]) * props.mapState.width) /
lonRange
);
const y = round(
((point[1] - props.mapState.bounds.sw[1]) * props.mapState.height) /
latRange
);
return [x, props.mapState.height - y];
};
const trkToPolyline = (gpxData: any) => {
const latLongs: string[] = gpxData.trk[0].trkseg[0].trkpt.map(
(trkpt: any) => {
if (props.latLngToPixel === undefined) {
return '';
}
const point: Point = [trkpt.$.lat, trkpt.$.lon];
const pixelPoint = dirtyLatLngToPixel(point);
if (pixelPoint === undefined) {
return '';
}
return pixelPoint.join(' ');
}
);
console.log('latLongs: ' + latLongs);
return latLongs.join(' ');
};
return (
<polyline
points={trkToPolyline(gpx)}
stroke='black'
strokeWidth='3'
fill='none'
></polyline>
);
};
export default GPXFigure;
+10 -39
View File
@@ -1,52 +1,23 @@
import { Overlay, MapState, Point } from 'pigeon-maps';
import React from 'react';
import { useSelector } from 'react-redux';
const GPXOverlay: React.FC<{
mapState: any;
latLngToPixel: any;
}> = (props: {
mapState: MapState;
latLngToPixel:
| ((
latLng: Point,
center?: Point | undefined,
zoom?: number | undefined
) => Point)
| undefined;
}) => {
const track = useSelector((state: { gpx: { current: any; }; }) => state.gpx.current.trk[0]);
const trkToPolyline = (trk: any) => {
const latLongs: string[] = trk.trkseg[0].trkpt.map((trkpt: any) => {
if (props.latLngToPixel === undefined) {
return '';
}
const point: Point = [trkpt['$'].lat, trkpt['$'].lon];
const pixelPoint = props.latLngToPixel(point);
if (pixelPoint === undefined) {
return '';
}
return pixelPoint.join(' ');
});
console.log('latLongs: ' + latLongs);
return latLongs.join(' ');
};
import { Overlay, PigeonProps } from 'pigeon-maps';
import GPXFigure from './gpx-figure';
const GPXOverlay: React.FC<PigeonProps> = (props: PigeonProps) => {
return (
<Overlay mapState={props.mapState} latLngToPixel={props.latLngToPixel}>
{props.mapState.width > 0 && (
<Overlay >
{props.mapState && props.mapState.width > 0 && (
<svg
xmlns='http://www.w3.org/2000/svg'
viewBox={'0 0 ' + props.mapState.width + ' ' + props.mapState.height}
width={props.mapState.width}
height={props.mapState.height}
>
<polyline
points={trkToPolyline(track)}
stroke='black'
strokeWidth='3'
fill='none'
></polyline>
<GPXFigure
mapState={props.mapState}
latLngToPixel={props.latLngToPixel}
/>
</svg>
)}
</Overlay>
-68
View File
@@ -1,68 +0,0 @@
import react, { useState } from 'react';
import { Map, Marker, ZoomControl } from 'pigeon-maps';
import { useDispatch } from 'react-redux';
import { gpxActions } from '../store/gpx';
import GPXOverlay from './gpx-overlay';
import { registerBackgroundGeolocation } from '../lib/geolocation';
const LiveMap: react.FC = () => {
const initialCenter: [number, number] = [43.57154, 3.94351];
const initialZoom: number = 15;
const [initialized, setInitialized] = useState(false);
const [center, setCenter] = useState(initialCenter);
const [position, setPosition] = useState(initialCenter);
const [zoom, setZoom] = useState(initialZoom);
const dispatch = useDispatch();
if (!initialized) {
dispatch(
gpxActions.clearGPX({
trkKey: 'current',
})
);
dispatch(
gpxActions.appendTrkpt({
trkKey: 'current',
trkpt: {
$: {
lat: 43.57154,
lon: 3.94351,
},
},
})
);
dispatch(
gpxActions.appendTrkpt({
trkKey: 'current',
trkpt: {
$: {
lat: 43.56922,
lon: 3.94228,
},
},
})
);
registerBackgroundGeolocation(dispatch);
setInitialized(true);
}
return (
<Map
center={center}
zoom={zoom}
onBoundsChanged={({ center, zoom }) => {
setCenter(center);
setZoom(zoom);
}}
animate={true}
>
<GPXOverlay mapState={undefined} latLngToPixel={undefined} />
<Marker width={20} anchor={position} />
<ZoomControl />
</Map>
);
};
export default LiveMap;
+83
View File
@@ -0,0 +1,83 @@
import _, { round } from 'lodash';
import react, { useState, useEffect } from 'react';
import GPXOverlay from './gpx-overlay';
import Tile from './tile';
import '../theme/map.css';
export const tileSize = 256;
// cf https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames#ECMAScript_(JavaScript/ActionScript,_etc.)
const lon2tile = (lon: number, zoom: number) => {
const real = ((lon + 180) / 360) * Math.pow(2, zoom);
const floor = Math.floor(real);
return [floor, real - floor];
};
const lat2tile = (lat: number, zoom: number) => {
const real =
((1 -
Math.log(
Math.tan((lat * Math.PI) / 180) + 1 / Math.cos((lat * Math.PI) / 180)
) /
Math.PI) /
2) *
Math.pow(2, zoom);
const floor = Math.floor(real);
return [floor, real - floor];
};
const Map: react.FC = () => {
const initialCenter: [number, number] = [43.57029965, 3.94242897];
const initialZoom: number = 15;
const [center, setCenter] = useState(initialCenter);
const [zoom, setZoom] = useState(initialZoom);
const [dimensions, setDimensions] = useState({
height: window.innerHeight,
width: window.innerWidth,
});
useEffect(() => {
const handleResize = () => {
setDimensions({
height: window.innerHeight,
width: window.innerWidth,
});
};
window.addEventListener('resize', handleResize);
});
const nbTilesY = _.ceil(dimensions.height / tileSize) + 2;
const nbTilesX = _.ceil(dimensions.width / tileSize) + 2;
const [tileCenterY, deltaY] = lat2tile(center[0], zoom);
const [tileCenterX, deltaX] = lon2tile(center[1], zoom);
const firstTileY = tileCenterY - _.ceil(nbTilesY / 2);
const firstTileX = tileCenterX - _.ceil(nbTilesX / 2);
return (
<div className='tiles'>
{_.range(nbTilesY).map((iy) => (
<div key={'y' + iy} className='tilesRow'>
{_.range(nbTilesX).map((ix) => (
<Tile
key={'x' + ix}
iy={iy}
ix={ix}
x={firstTileX + ix}
y={firstTileY + iy}
deltaX ={deltaX}
deltaY ={deltaY}
zoom={zoom}
/>
))}
</div>
))}
</div>
);
};
export default Map;
+37
View File
@@ -0,0 +1,37 @@
import React from 'react';
import { tileSize } from './map';
const tileProvider = (zoom: number, x: number, y: number) =>
'https://tile.openstreetmap.org/' + zoom + '/' + x + '/' + y + '.png';
const Tile: React.FC<{
ix: number;
iy: number;
x: number;
y: number;
deltaX: number;
deltaY: number;
zoom: number;
}> = (props: {
ix: number;
iy: number;
x: number;
y: number;
deltaX: number;
deltaY: number;
zoom: number;
}) => {
const style = {
width: tileSize + 'px',
height: tileSize + 'px',
transform:
'translate3d(' +
(props.ix - props.deltaX -1) * tileSize +
'px, ' +
(props.iy - props.deltaY -1) * tileSize +
'px, 0px)',
};
return <img src={tileProvider(props.zoom, props.x, props.y)} style={style} />;
};
export default Tile;
+1
View File
@@ -0,0 +1 @@
declare module 'gpx-parser-builder'
-104
View File
@@ -1,104 +0,0 @@
import { BackgroundGeolocationPlugin } from '@capacitor-community/background-geolocation';
import { registerPlugin } from '@capacitor/core';
import { gpxActions } from '../store/gpx';
export const registerBackgroundGeolocation = (dispatch: (arg0: any) => void) => {
const BackgroundGeolocation = registerPlugin<BackgroundGeolocationPlugin>(
'BackgroundGeolocation'
);
console.log('com.dyomedea.dyomedea LOG', ' - Adding the watcher');
BackgroundGeolocation.addWatcher(
{
// If the "backgroundMessage" option is defined, the watcher will
// provide location updates whether the app is in the background or the
// foreground. If it is not defined, location updates are only
// guaranteed in the foreground. This is true on both platforms.
// On Android, a notification must be shown to continue receiving
// location updates in the background. This option specifies the text of
// that notification.
backgroundMessage: 'Cancel to prevent battery drain.',
// The title of the notification mentioned above. Defaults to "Using
// your location".
backgroundTitle: 'Tracking You.',
// Whether permissions should be requested from the user automatically,
// if they are not already granted. Defaults to "true".
requestPermissions: true,
// If "true", stale locations may be delivered while the device
// obtains a GPS fix. You are responsible for checking the "time"
// property. If "false", locations are guaranteed to be up to date.
// Defaults to "false".
stale: false,
// The minimum number of metres between subsequent locations. Defaults
// to 0.
distanceFilter: 1,
},
function callback(location, error) {
console.log('com.dyomedea.dyomedea LOG', ' - Callback');
if (error) {
if (error.code === 'NOT_AUTHORIZED') {
if (
window.confirm(
'This app needs your location, ' +
'but does not have permission.\n\n' +
'Open settings now?'
)
) {
// It can be useful to direct the user to their device's
// settings when location permissions have been denied. The
// plugin provides the 'openSettings' method to do exactly
// this.
BackgroundGeolocation.openSettings();
}
}
return console.error(
'com.dyomedea.dyomedea LOG',
' - error: ',
error
);
}
console.log(location);
if (location !== undefined) {
//setCenter([location.latitude, location.longitude]);
//setPosition([location.latitude, location.longitude]);
dispatch(
gpxActions.appendTrkpt({
trkKey: 'current',
trkpt: {
$: {
lat: location.latitude,
lon: location.longitude,
},
},
})
);
}
return console.log(
'com.dyomedea.dyomedea LOG',
' - location: ',
location
);
}
)
.then(function after_the_watcher_has_been_added(watcher_id) {
// When a watcher is no longer needed, it should be removed by calling
// 'removeWatcher' with an object containing its ID.
console.log('com.dyomedea.dyomedea LOG', ' - Watcher added');
/*BackgroundGeolocation.removeWatcher({
id: watcher_id,
}); */
})
.catch((reason) => {
console.error('com.dyomedea.dyomedea LOG', ' - reason: ', reason);
});
};
+26
View File
@@ -0,0 +1,26 @@
import _ from 'lodash';
const initialState: any = {
current: {
$: {},
trk: [
{
trkseg: [{ trkpt: [] }],
},
],
},
};
export const appendTrkpt = (gpx:any , trkpt:any) => {
var updatedGpx = _.cloneDeep(gpx);
updatedGpx.trk[0].trkseg[0].trkpt.push(trkpt);
return updatedGpx;
};
export const clearTrkpt = (gpx:any) => {
var updatedGpx = _.cloneDeep(gpx);
updatedGpx.trk[0]=[];
return updatedGpx;
};
-31
View File
@@ -1,31 +0,0 @@
import { createSlice } from '@reduxjs/toolkit';
const initialState: any = {
current: {
$: {},
trk: [
{
trkseg: [{ trkpt: [] }],
},
],
},
};
const slice = createSlice({
name: 'gpx',
initialState: initialState,
reducers: {
appendTrkpt(state, action) {
state[action.payload.trkKey].trk[0].trkseg[0].trkpt.push(
action.payload.trkpt
);
},
clearGPX(state, action) {
state[action.payload.trkKey] = initialState.current;
},
},
});
export const gpxActions = slice.actions;
export default slice.reducer;
-9
View File
@@ -1,9 +0,0 @@
import { configureStore } from '@reduxjs/toolkit';
import gpxReducer from './gpx';
const store = configureStore({
reducer: { gpx: gpxReducer },
});
export default store;
+9
View File
@@ -0,0 +1,9 @@
.tiles {
position: absolute;
}
.tiles img {
max-width: none;
position: absolute;
}