Merge branch 'master' into feature/dialog-editor

# Conflicts:
#	src/components/dialogs/MapListDialog.tsx
#	src/modules/Poly.ts
#	src/styles/dialogs.less
This commit is contained in:
muerwre 2019-03-06 14:08:16 +07:00
commit d42586d9e0
25 changed files with 556 additions and 971 deletions

65
src/modules/Arrows.ts Normal file
View file

@ -0,0 +1,65 @@
import { LatLngLiteral, LayerGroup, Map } from "leaflet";
import { arrowClusterIcon, createArrow } from "$utils/arrow";
import { MarkerClusterGroup } from 'leaflet.markercluster/dist/leaflet.markercluster-src.js';
import { angleBetweenPoints, dist2, middleCoord } from "$utils/geom";
class Component extends LayerGroup {
constructor(props){
super(props);
}
setLatLngs = (latlngs: LatLngLiteral[]): void => {
if (!this.map) return;
this.arrowLayer.clearLayers();
if (latlngs.length === 0) return;
const midpoints = latlngs.reduce((res, latlng, i) => (
latlngs[i + 1] && dist2(latlngs[i], latlngs[i + 1]) > 0.00005
? [
...res,
{
latlng: middleCoord(latlngs[i], latlngs[i + 1]),
angle: angleBetweenPoints(
this.map.latLngToContainerPoint(latlngs[i]),
this.map.latLngToContainerPoint(latlngs[i + 1])
),
}
]
: res
), []);
midpoints.forEach(({ latlng, angle }) => (
this.arrowLayer.addLayer(createArrow(latlng, angle))
));
};
map: Map;
arrowLayer: MarkerClusterGroup = new MarkerClusterGroup({
spiderfyOnMaxZoom: false,
showCoverageOnHover: false,
zoomToBoundsOnClick: false,
animate: false,
maxClusterRadius: 120,
iconCreateFunction: arrowClusterIcon,
});
}
Component.addInitHook(function () {
this.once('add', (event) => {
if (event.target instanceof Arrows) {
this.map = event.target._map;
this.arrowLayer.addTo(this.map);
}
});
this.once('remove', (event) => {
if (event.target instanceof Arrows) {
this.arrowLayer.removeFrom(this.map);
}
});
});
export const Arrows = Component;

View file

@ -14,7 +14,7 @@ import {
setAddress,
setChanged,
setDistance,
setIsEmpty,
setIsEmpty, setIsRouting,
setLogo,
setMarkersShown,
setMode,
@ -81,9 +81,19 @@ export class Editor {
map, routerMoveStart, lockMapClicks, setDistance: this.setDistance, triggerOnChange, editor: this,
});
this.stickers = new Stickers({ map, lockMapClicks, triggerOnChange, editor: this });
this.stickers = new Stickers({
map,
lockMapClicks,
triggerOnChange,
editor: this
});
this.router = new Router({
map, lockMapClicks, setRouterPoints: this.setRouterPoints, pushPolyPoints
map,
lockMapClicks,
pushPolyPoints,
setRouterPoints: this.setRouterPoints,
setIsRouting: this.setIsRouting,
});
this.switches = {
@ -176,6 +186,7 @@ export class Editor {
setAddress: typeof setAddress = value => store.dispatch(setAddress(value));
setPublic: typeof setPublic = value => store.dispatch(setPublic(value));
setIsEmpty: typeof setIsEmpty = value => store.dispatch(setIsEmpty(value));
setIsRouting: typeof setIsRouting = value => store.dispatch(setIsRouting(value));
setMarkersShown = (value: boolean): void => {
if (this.getState().markers_shown !== value) store.dispatch(setMarkersShown(value));
@ -397,7 +408,7 @@ export class Editor {
get isEmpty(): boolean {
const { route, stickers } = this.dumpData();
return (!route || route.length < 1) && (!stickers || stickers.length <= 0);
return (!route || route.length <= 1) && (!stickers || stickers.length <= 0);
}
get hasEmptyHistory(): boolean {

View file

@ -33,8 +33,8 @@ export class Component extends Polyline {
this.constraintsStyle = { ...this.constraintsStyle, ...options.constraintsStyle };
this.maxMarkers = options.maxMarkers || this.maxMarkers;
this.kmMarksEnabled = options.kmMarksEnabled || this.kmMarksEnabled;
this.kmMarksStep = options.kmMarksStep || this.kmMarksStep;
// this.kmMarksEnabled = options.kmMarksEnabled || this.kmMarksEnabled;
// this.kmMarksStep = options.kmMarksStep || this.kmMarksStep;
this.constrLine = new Polyline([], this.constraintsStyle);
@ -49,7 +49,7 @@ export class Component extends Polyline {
this.setLatLngs(latlngs);
this.recreateMarkers();
this.recalcDistance();
this.recalcKmMarks();
// this.recalcKmMarks();
this.touchHinter.setLatLngs(latlngs);
this.fire('latlngschange', { latlngs });
};
@ -405,6 +405,7 @@ export class Component extends Polyline {
this.setLatLngs(latlngs);
this.fire('latlngschange', { latlngs });
this.showVisibleMarkers();
this.startDrawing();
};
@ -483,35 +484,35 @@ export class Component extends Polyline {
this.fire('distancechange', { distance: this.distance });
};
//
// recalcKmMarks = () => {
// if (!this.kmMarksEnabled) return;
//
// const latlngs = this.getLatLngs() as LatLngLiteral[];
//
// this.kmMarks = { };
//
// let last_km_mark = 0;
//
// latlngs.reduce((dist, latlng, index) => {
// if (index >= latlngs.length - 1) return;
//
// const next = latlngs[index + 1];
// const sum = dist + distKm(latlng, next);
// const rounded = Math.floor(dist / this.kmMarksStep) * this.kmMarksStep;
//
// if (rounded > last_km_mark) {
// last_km_mark = rounded;
// this.kmMarks[rounded] = latlng;
// }
//
// return sum;
// }, 0);
// };
recalcKmMarks = () => {
if (!this.kmMarksEnabled) return;
const latlngs = this.getLatLngs() as LatLngLiteral[];
this.kmMarks = { };
let last_km_mark = 0;
latlngs.reduce((dist, latlng, index) => {
if (index >= latlngs.length - 1) return;
const next = latlngs[index + 1];
const sum = dist + distKm(latlng, next);
const rounded = Math.floor(dist / this.kmMarksStep) * this.kmMarksStep;
if (rounded > last_km_mark) {
last_km_mark = rounded;
this.kmMarks[rounded] = latlng;
}
return sum;
}, 0);
};
kmMarksEnabled?: InteractivePolylineOptions['kmMarksEnabled'] = true;
kmMarksStep?: InteractivePolylineOptions['kmMarksStep'] = 5;
kmMarks?: { [x: number]: LatLngLiteral };
// kmMarksEnabled?: InteractivePolylineOptions['kmMarksEnabled'] = true;
// kmMarksStep?: InteractivePolylineOptions['kmMarksStep'] = 5;
// kmMarks?: { [x: number]: LatLngLiteral };
// kmMarksLayer?: LayerGroup = new LayerGroup();
markers: Marker[] = [];

156
src/modules/KmMarks.ts Normal file
View file

@ -0,0 +1,156 @@
import { divIcon, LatLngLiteral, Layer, LayerGroup, Map, marker, Marker } from "leaflet";
import { arrowClusterIcon, createArrow } from "$utils/arrow";
import { MarkerClusterGroup } from 'leaflet.markercluster/dist/leaflet.markercluster-src.js';
import { allwaysPositiveAngleDeg, angleBetweenPoints, distKm } from "$utils/geom";
import classNames from 'classnames';
interface KmMarksOptions {
showMiddleMarkers: boolean,
showEndMarker: boolean,
kmMarksStep: number,
}
class Component extends LayerGroup {
constructor(latlngs?: LatLngLiteral[], options?: KmMarksOptions){
super();
this.options = {
showMiddleMarkers: true,
showEndMarker: true,
kmMarksStep: 10,
...(options || {}),
} as KmMarksOptions;
}
setLatLngs = (latlngs: LatLngLiteral[]): void => {
if (!this.map) return;
this.marksLayer.clearLayers();
this.endMarker.clearLayers();
this.distance = 0;
if (latlngs.length <= 1) return;
if (this.options.showMiddleMarkers) this.drawMiddleMarkers(latlngs);
if (this.options.showEndMarker) this.drawEndMarker(latlngs);
};
drawMiddleMarkers = (latlngs: LatLngLiteral[]) => {
const kmMarks = {};
let last_km_mark = 0;
this.distance = latlngs.reduce((dist, current, index) => {
if (index >= latlngs.length - 1) return dist;
const next = latlngs[index + 1];
const diff = distKm(current, next);
const sum = dist + diff;
const rounded = Math.floor(sum / this.options.kmMarksStep) * this.options.kmMarksStep;
const count = Math.floor((rounded - last_km_mark) / this.options.kmMarksStep);
if (rounded > last_km_mark) {
const angle = angleBetweenPoints(
this.map.latLngToContainerPoint(current),
this.map.latLngToContainerPoint(next),
);
for (let i = 1; i <= count; i += 1) {
const step = last_km_mark + (i * this.options.kmMarksStep);
const shift = (step - dist) / diff;
const coords = {
lat: current.lat - ((current.lat - next.lat) * shift),
lng: current.lng - ((current.lng - next.lng) * shift),
};
kmMarks[step] = { ...coords, angle };
this.marksLayer.addLayer(this.createMiddleMarker(coords, angle, step));
}
last_km_mark = rounded;
}
return sum;
}, 0);
};
createMiddleMarker = (latlng: LatLngLiteral, angle: number, distance: number): Marker => marker(latlng, {
draggable: false,
interactive: true,
icon: divIcon({
html: `
<div class="leaflet-km-dist" style="transform: translate(-50%, -50%) rotate(${allwaysPositiveAngleDeg(angle)}deg);">
${distance}
</div>
`,
className: 'leaflet-km-marker',
iconSize: [11, 11],
iconAnchor: [6, 6]
})
});
createEndMarker = (latlng: LatLngLiteral, angle: number, distance: number): Marker => marker(latlng, {
draggable: false,
interactive: true,
icon: divIcon({
html: `
<div class="leaflet-km-dist">
${parseFloat(distance.toFixed(1))}
</div>
`,
className: classNames('leaflet-km-marker end-marker', { right: (angle > -90 && angle < 90) }),
iconSize: [11, 11],
iconAnchor: [6, 6]
}),
zIndexOffset: -100,
});
drawEndMarker = (latlngs: LatLngLiteral[]): void => {
this.endMarker.clearLayers();
const current = latlngs[latlngs.length - 2];
const next = latlngs[latlngs.length - 1
];
const angle = angleBetweenPoints(
this.map.latLngToContainerPoint(current),
this.map.latLngToContainerPoint(next),
);
this.endMarker.addLayer(this.createEndMarker(next, angle, this.distance));
};
options: KmMarksOptions;
map: Map;
marksLayer: MarkerClusterGroup = new MarkerClusterGroup({
spiderfyOnMaxZoom: false,
showCoverageOnHover: false,
zoomToBoundsOnClick: false,
animate: false,
maxClusterRadius: 120,
iconCreateFunction: arrowClusterIcon,
});
endMarker: LayerGroup = new LayerGroup();
distance: number = 0;
}
Component.addInitHook(function () {
this.once('add', (event) => {
if (event.target instanceof KmMarks) {
this.map = event.target._map;
this.marksLayer.addTo(this.map);
this.endMarker.addTo(this.map);
}
});
this.once('remove', (event) => {
if (event.target instanceof KmMarks) {
this.marksLayer.removeFrom(this.map);
this.endMarker.removeFrom(this.map);
}
});
});
export const KmMarks = Component;

View file

@ -1,13 +1,12 @@
import { Map, LatLng } from 'leaflet';
import { EditablePolyline } from '$utils/EditablePolyline';
import { simplify } from '$utils/simplify';
import { CLIENT } from '$config/frontend';
import { editor, Editor } from "$modules/Editor";
import { ILatLng } from "$modules/Stickers";
import { InteractivePoly } from "$modules/InteractivePoly";
import { MarkerClusterGroup } from 'leaflet.markercluster/dist/leaflet.markercluster-src.js';
import { angleBetweenPoints, dist2, distToSegment, middleCoord } from "$utils/geom";
import { arrowClusterIcon, createArrow } from "$utils/arrow";
import { Arrows } from "$modules/Arrows";
import { KmMarks } from "$modules/KmMarks";
import { isMobile } from "$utils/window";
interface Props {
map: Map;
@ -25,14 +24,13 @@ export class Poly {
this.poly = new InteractivePoly([ ], {
color: 'url(#activePathGradient)',
weight: 6,
maxMarkers: 100,
maxMarkers: isMobile() ? 20 : 100,
smoothFactor: 3,
})
.on('distancechange', this.onDistanceUpdate)
.on('allvertexhide', this.onVertexHide)
.on('allvertexshow', this.onVertexShow)
.on('latlngschange', this.updateArrows)
.on('latlngschange', triggerOnChange);
.on('latlngschange', this.updateMarks)
this.poly.addTo(map);
this.editor = editor;
@ -44,7 +42,8 @@ export class Poly {
this.triggerOnChange = triggerOnChange;
this.lockMapClicks = lockMapClicks;
this.arrowLayer.addTo(map);
this.arrows = new Arrows({}).addTo(map);
this.kmMarks = new KmMarks().addTo(map);
}
onDistanceUpdate = (event) => {
@ -55,66 +54,15 @@ export class Poly {
onVertexHide = (): void => this.editor.setMarkersShown(false);
onVertexShow = (): void => this.editor.setMarkersShown(true);
updateArrows = event => {
this.editor.setChanged(true);
updateMarks = event => {
// this.editor.setChanged(true);
this.editor.triggerOnChange();
const { latlngs } = event;
this.arrowLayer.clearLayers();
if (latlngs.length === 0) return;
const midpoints = latlngs.reduce((res, latlng, i) => (
latlngs[i + 1] && dist2(latlngs[i], latlngs[i + 1]) > 0.00005
? [
...res,
{
latlng: middleCoord(latlngs[i], latlngs[i + 1]),
angle: angleBetweenPoints(
this.map.latLngToContainerPoint(latlngs[i]),
this.map.latLngToContainerPoint(latlngs[i + 1])
),
}
]
: res
), []);
midpoints.forEach(({ latlng, angle }) => (
this.arrowLayer.addLayer(createArrow(latlng, angle))
));
this.arrows.setLatLngs(latlngs);
this.kmMarks.setLatLngs(latlngs);
};
// setModeOnDrawing = (): void => {
// if (this.editor.getMode() !== MODES.POLY) this.editor.setMode(MODES.POLY);
// };
//
// drawArrows = () => {
// // todo: fix this
// this.arrows.clearLayers();
// const { latlngs } = this;
//
// if (!latlngs || latlngs.length <= 1) return;
//
// latlngs.forEach((latlng, i) => {
// if (i === 0) return;
//
// const mid = middleCoord(latlngs[i], latlngs[i - 1]);
// const dist = findDistance(latlngs[i - 1].lat, latlngs[i - 1].lng, latlngs[i].lat, latlngs[i].lng);
//
// if (dist <= 1) return;
//
// const slide = new Polyline(
// [
// latlngs[i - 1],
// [mid.lat, mid.lng]
// ],
// { color: 'none', weight: CLIENT.STROKE_WIDTH }
// ).addTo(this.arrows) as any;
//
// // todo: uncomment and fix this:
// slide._path.setAttribute('marker-end', 'url(#long-arrow)');
// });
// };
continue = (): void => {
this.poly.editor.continue();
};
@ -147,8 +95,6 @@ export class Poly {
this.poly.setPoints([]);
};
// clearArrows = (): LayerGroup<any> => this.arrows.clearLayers();
dumpData = (): Array<LatLng> => this.latlngs;
get latlngs(): Array<LatLng> {
@ -161,16 +107,9 @@ export class Poly {
return (!this.latlngs || Object.values(this.latlngs).length <= 0);
}
arrows;
poly;
arrowLayer: MarkerClusterGroup = new MarkerClusterGroup({
spiderfyOnMaxZoom: false,
showCoverageOnHover: false,
zoomToBoundsOnClick: false,
animate: false,
maxClusterRadius: 120,
// disableClusteringAtZoom: 13,
iconCreateFunction: arrowClusterIcon,
});
kmMarks;
editor: Props['editor'];
map: Props['map'];

View file

@ -13,6 +13,7 @@ interface IWaypoint {
}
interface Props {
setIsRouting: typeof editor.setIsRouting,
map: Map,
setRouterPoints: typeof editor.setRouterPoints,
pushPolyPoints: typeof editor.pushPolyPoints,
@ -21,12 +22,13 @@ interface Props {
export class Router {
constructor({
map, lockMapClicks, setRouterPoints, pushPolyPoints
map, lockMapClicks, setRouterPoints, pushPolyPoints, setIsRouting,
}: Props) {
this.waypoints = [];
this.lockMapClicks = lockMapClicks;
this.setRouterPoints = setRouterPoints;
this.pushPolyPoints = pushPolyPoints;
this.setIsRouting = setIsRouting;
const routeLine = r => Routing.line(r, {
styles: [
@ -38,8 +40,9 @@ export class Router {
this.router = Routing.control({
serviceUrl: CLIENT.OSRM_URL,
profile: 'bike',
profile: CLIENT.OSRM_PROFILE,
fitSelectedRoutes: false,
showAlternatives: false,
routeLine,
altLineOptions: {
styles: [{ color: '#4597d0', opacity: 1, weight: 3 }]
@ -50,14 +53,29 @@ export class Router {
draggable: true,
icon: this.createWaypointMarker(),
}),
routeWhileDragging: true,
routeWhileDragging: false,
}),
routeWhileDragging: true
}).on('waypointschanged', this.updateWaypointsCount);
routeWhileDragging: false,
routingOptions: {
geometryOnly: false,
},
useHints: false,
})
.on('routingstart', this.showSpinner)
.on('routesfound routingerror', this.hideSpinner)
.on('waypointschanged', this.updateWaypointsCount);
this.router.addTo(map);
}
showSpinner = () => {
this.setIsRouting(true);
};
hideSpinner = () => {
this.setIsRouting(false);
};
pushWaypointOnClick = ({ latlng: { lat, lng } }: { latlng: ILatLng }): void => {
const waypoints = this.router.getWaypoints().filter(({ latLng }) => !!latLng);
this.router.setWaypoints([...waypoints, { lat, lng }]);
@ -87,7 +105,7 @@ export class Router {
}
window.removeEventListener('mouseup', this.unlockPropagations);
setTimeout(() => this.lockMapClicks(false), 300);
setTimeout(() => this.lockMapClicks(false), 0);
};
startFrom = (latlngs: ILatLng): void => {
@ -148,6 +166,7 @@ export class Router {
};
waypoints: Array<IWaypoint> = [];
setIsRouting: Props['setIsRouting'];
lockMapClicks: Props['lockMapClicks'];
setRouterPoints: Props['setRouterPoints'];
pushPolyPoints: Props['pushPolyPoints'];

View file

@ -9,7 +9,7 @@ import classnames from 'classnames';
import { getLabelDirection } from '$utils/geom';
import { ILatLng } from "$modules/Stickers";
import { IRootState } from "$redux/user/reducer";
import { editor } from "$modules/Editor";
import { Editor, editor } from "$modules/Editor";
const getX = e => (
e.touches && e.touches.length > 0
@ -33,6 +33,7 @@ interface Props {
set: IRootState['activeSticker']['set'];
angle?: number;
text?: string;
editor: Editor,
deleteSticker: (sticker: this) => void;
@ -42,7 +43,7 @@ interface Props {
export class Sticker {
constructor({
latlng, deleteSticker, map, lockMapClicks, sticker, set, triggerOnChange, angle = 2.2, text = '',
latlng, deleteSticker, map, lockMapClicks, sticker, set, triggerOnChange, angle = 2.2, text = '', editor,
}: Props) {
this.text = text;
this.latlng = latlng;
@ -54,6 +55,7 @@ export class Sticker {
this.direction = getLabelDirection(this.angle);
this.deleteSticker = deleteSticker;
this.lockMapClicks = lockMapClicks;
this.editor = editor;
ReactDOM.render(
<React.Fragment>
@ -94,17 +96,27 @@ export class Sticker {
this.marker = marker(latlng, { icon: mark, draggable: true });
this.marker.on('add', this.updateModeOnAdd);
this.element.addEventListener('mouseup', this.onDragStop);
this.element.addEventListener('mouseup', this.preventPropagations);
this.element.addEventListener('touchend', this.onDragStop);
this.element.addEventListener('touchend', this.preventPropagations);
this.marker.addEventListener('dragend', this.triggerOnChange);
this.marker.on('dragend', this.triggerOnChange);
this.setAngle(this.angle);
}
updateModeOnAdd = () => {
if (this.editor.getEditing()) {
this.startEditing();
} else {
this.stopEditing();
}
};
setText = (text: Props['text']): void => {
this.text = text;
};
@ -122,11 +134,10 @@ export class Sticker {
this.lockMapClicks(true);
window.addEventListener('mousemove', this.onDrag);
window.addEventListener('mouseup', this.onDragStop);
window.addEventListener('touchmove', this.onDrag);
window.addEventListener('touchend', this.onDragStop);
// this.marker.disableEdit();
window.addEventListener('mouseup', this.onDragStop);
window.addEventListener('touchend', this.onDragStop);
};
preventPropagations = (e): void => {
@ -144,9 +155,9 @@ export class Sticker {
this.isDragging = false;
window.removeEventListener('mousemove', this.onDrag);
window.removeEventListener('mouseup', this.onDragStop);
window.removeEventListener('touchmove', this.onDrag);
window.removeEventListener('mouseup', this.onDragStop);
window.removeEventListener('touchend', this.onDragStop);
this.lockMapClicks(false);
@ -207,6 +218,7 @@ export class Sticker {
marker: Marker;
isDragging: boolean = false;
direction: string;
editor: Editor;
text: Props['text'];
latlng: Props['latlng'];

View file

@ -3,6 +3,7 @@ import { IStickerDump, Sticker } from '$modules/Sticker';
import { MarkerClusterGroup } from 'leaflet.markercluster/dist/leaflet.markercluster-src.js';
import { clusterIcon } from '$utils/clusterIcon';
import { editor, Editor } from "$modules/Editor";
import { STICKERS } from "$constants/stickers";
export interface ILatLng {
lat: number,
@ -25,7 +26,7 @@ export class Stickers {
this.clusterLayer.addTo(map);
this.clusterLayer.on('animationend', this.onSpiderify);
// this.clusterLayer.on('animationend', this.onSpiderify);
this.lockMapClicks = lockMapClicks;
this.stickers = [];
@ -36,6 +37,9 @@ export class Stickers {
createSticker = ({
latlng, sticker, angle = 2.2, text = '', set
}: IStickerDump): void => {
if (!STICKERS[set] || !STICKERS[set].layers || !STICKERS[set].layers[sticker]) return;
const marker = new Sticker({
latlng,
angle,
@ -46,6 +50,7 @@ export class Stickers {
set,
triggerOnChange: this.triggerOnChange,
text,
editor: this.editor,
});
this.stickers.push(marker);
@ -76,14 +81,15 @@ export class Stickers {
dumpData = (): Array<IStickerDump> => this.stickers.map(sticker => sticker.dumpData());
onSpiderify = (): void => {
// todo: it has markers passed as argument. Update only them.
if (this.editor.getEditing()) {
this.startEditing();
} else {
this.stopEditing();
}
};
// onSpiderify = (): void => {
// console.log('spider?');
// // todo: it has markers passed as argument. Update only them.
// if (this.editor.getEditing()) {
// this.startEditing();
// } else {
// this.stopEditing();
// }
// };
startEditing = (): void => {
this.stickers.map(sticker => sticker.startEditing());