mapcomplete/Logic/Leaflet/Basemap.ts

80 lines
2.5 KiB
TypeScript
Raw Normal View History

2020-09-27 22:48:43 +02:00
import * as L from "leaflet"
import {UIEventSource} from "../UIEventSource";
2020-07-30 00:59:08 +02:00
import {UIElement} from "../../UI/UIElement";
import {BaseLayer} from "../../Models/BaseLayer";
import AvailableBaseLayers from "../Actors/AvailableBaseLayers";
import Loc from "../../Models/Loc";
2020-06-24 00:35:19 +02:00
2020-07-22 14:46:43 +02:00
export class Basemap {
2020-06-24 00:35:19 +02:00
2020-07-22 14:46:43 +02:00
// @ts-ignore
public readonly map: Map;
2020-06-24 00:35:19 +02:00
public readonly LastClickLocation: UIEventSource<{ lat: number, lon: number }> = new UIEventSource<{ lat: number, lon: number }>(undefined)
2020-06-24 00:35:19 +02:00
2020-06-29 03:12:44 +02:00
constructor(leafletElementId: string,
location: UIEventSource<Loc>,
2021-01-02 19:09:49 +01:00
currentLayer: UIEventSource<BaseLayer>,
2020-06-29 03:12:44 +02:00
extraAttribution: UIElement) {
this.map = L.map(leafletElementId, {
center: [location.data.lat ?? 0, location.data.lon ?? 0],
zoom: location.data.zoom ?? 2,
2021-01-02 19:09:49 +01:00
layers: [AvailableBaseLayers.osmCarto.layer],
2020-06-24 00:35:19 +02:00
});
2020-11-20 11:31:54 +01:00
L.control.scale(
{
position: 'topright',
}
).addTo(this.map)
2021-01-02 19:09:49 +01:00
// Users are not allowed to zoom to the 'copies' on the left and the right, stuff goes wrong then
// We give a bit of leeway for people on the edges
// Also see: https://www.reddit.com/r/openstreetmap/comments/ih4zzc/mapcomplete_a_new_easytouse_editor/g31ubyv/
this.map.setMaxBounds(
2021-01-02 19:09:49 +01:00
[[-100, -200], [100, 200]]
);
2020-06-29 03:40:19 +02:00
this.map.attributionControl.setPrefix(
extraAttribution.Render() + " | <a href='https://osm.org'>OpenStreetMap</a>");
this.map.zoomControl.setPosition("bottomright");
2020-06-24 00:35:19 +02:00
const self = this;
2021-01-02 19:09:49 +01:00
let previousLayer = currentLayer.data;
currentLayer.addCallbackAndRun(layer => {
if (layer === previousLayer) {
return;
}
if (previousLayer !== undefined) {
self.map.removeLayer(previousLayer.layer);
}
previousLayer = layer;
self.map.addLayer(layer.layer);
})
2020-06-24 00:35:19 +02:00
this.map.on("moveend", function () {
location.data.zoom = self.map.getZoom();
location.data.lat = self.map.getCenter().lat;
2020-06-29 03:12:44 +02:00
location.data.lon = self.map.getCenter().lng;
2020-06-24 00:35:19 +02:00
location.ping();
});
2020-09-27 22:48:43 +02:00
2020-06-29 03:12:44 +02:00
this.map.on("click", function (e) {
self.LastClickLocation.setData({lat: e.latlng.lat, lon: e.latlng.lng})
});
this.map.on("contextmenu", function (e) {
self.LastClickLocation.setData({lat: e.latlng.lat, lon: e.latlng.lng});
e.preventDefault();
});
2021-01-02 19:09:49 +01:00
2020-06-24 00:35:19 +02:00
}
2020-06-24 00:35:19 +02:00
}