tracktracker/front/map/corridor.js

72 lines
2.0 KiB
JavaScript

/**
* Based on https://github.com/mikhailshilkov/leaflet-corridor
*/
const leaflet = require('leaflet');
/**
* Polyline whose weight is based on a fixed number of meters of thickness
* rather than a static number of pixels.
*/
const Corridor = leaflet.Polyline.extend({
initialize(latlngs, options)
{
leaflet.Polyline.prototype.initialize.call(this, latlngs, options);
this.corridor = options.corridor;
},
onAdd(map)
{
leaflet.Polyline.prototype.onAdd.call(this, map);
map.on('zoomend', () => this._updateWeight(map));
this._updateWeight(map);
},
onRemove(map)
{
map.off('zoomend', () => this._updateWeight(map));
leaflet.Polyline.prototype.onRemove.call(this, map);
},
/**
* Update the actual line weight to span the requested number of meters
* based on the current meter density.
*/
_updateWeight(map)
{
this.setStyle({
weight: this.corridor / this._getMetersPerPixel(map)
});
},
/**
* Calculate how many meters are in a pixel at the current zoom level
* around the current center point.
*
* @param map Map to take the zoom level from.
* @return Number of meters per pixel.
*/
_getMetersPerPixel(map)
{
const centerLatLng = map.getCenter();
const centerPixels = map.latLngToContainerPoint(centerLatLng);
// Place two points left and right of the center
const point1 = leaflet.point(centerPixels.x + 5, centerPixels.y);
const point2 = leaflet.point(centerPixels.x - 5, centerPixels.y);
// Convert back to latitude and longitude then compute distance
const point1LatLng = map.containerPointToLatLng(point1);
const point2LatLng = map.containerPointToLatLng(point2);
console.log(point1LatLng.distanceTo(point2LatLng) / 10, 'mètres par pixel');
return point1LatLng.distanceTo(point2LatLng) / 10;
},
});
module.exports = (latlngs, options) => new Corridor(
latlngs,
options || { corridor: 100 }
);