UNPKG

maplair

Version:

JavaScript library for mobile-friendly interactive maps

338 lines (290 loc) • 8.92 kB
import {Path} from './Path.js'; import * as Util from '../../core/Util.js'; import * as LineUtil from '../../geometry/LineUtil.js'; import {LatLng} from '../../geo/LatLng.js'; import {LatLngBounds} from '../../geo/LatLngBounds.js'; import {Bounds} from '../../geometry/Bounds.js'; import {Point} from '../../geometry/Point.js'; import {latLngsToCoords, getFeature} from '../GeoJSONUtil.js'; /** @import {Feature} from 'geojson' */ /** @import {LatLngExpression} from '../../geo/LatLng.js' */ /** @import {PointExpression} from '../../geometry/Point.js' */ /** @import {PathOptions} from './Path.js' */ /** * Options of `Polyline`. * @typedef {object} PolylineOptions * @property {number} [smoothFactor=0.5] How much to simplify the polyline on each zoom * level (Douglas–Peucker epsilon, in pixels). Higher values mean faster rendering but * less accuracy; lower values mean more accuracy but slower rendering. * @property {boolean} [noClip=false] Disable polyline clipping. * @extends PathOptions */ /** * A class for drawing polyline overlays on a map. Extends `Path`. * * @example * ```js * // create a red polyline from an array of LatLng points * const latlngs = [ * [45.51, -122.68], * [37.77, -122.43], * [34.04, -118.2] * ]; * * const polyline = new Polyline(latlngs, {color: 'red'}).addTo(map); * * // zoom the map to the polyline * map.fitBounds(polyline.getBounds()); * ``` * * You can also pass a multi-dimensional array to represent a `MultiPolyline` shape: * * ```js * // create a red polyline from an array of arrays of LatLng points * const latlngs = [ * [[45.51, -122.68], * [37.77, -122.43], * [34.04, -118.2]], * [[40.78, -73.91], * [41.83, -87.62], * [32.76, -96.72]] * ]; * ``` */ export class Polyline extends Path { static defaultOptions = { smoothFactor: 0.5, noClip: false }; /** * Instantiates a polyline object given an array of geographical points and * optionally an options object. You can create a `Polyline` object with * multiple separate lines (`MultiPolyline`) by passing an array of arrays * of geographic points. * @param {LatLngExpression[]|LatLngExpression[][]|LatLngExpression[][][]} latlngs * @param {PolylineOptions} [options] */ constructor(latlngs, options) { super(); Util.setOptions(this, options); this._setLatLngs(latlngs); this.callInitHooks(Polyline); } /** * Returns an array of the points in the path, or nested arrays of points in case of * multi-polyline. * @returns {LatLng[]|LatLng[][]|LatLng[][][]} */ getLatLngs() { return this._latlngs; } /** * Replaces all the points in the polyline with the given array of geographical points. * @param {LatLngExpression[]|LatLngExpression[][]|LatLngExpression[][][]} latlngs * @returns {this} */ setLatLngs(latlngs) { this._setLatLngs(latlngs); return this.redraw(); } /** * Returns `true` if the Polyline has no LatLngs. * @returns {boolean} */ isEmpty() { return !this._latlngs.length; } /** * Returns the point closest to `p` on the Polyline, with its `distance` to `p` in * pixels, or `null` if the polyline is not visible. * @param {PointExpression} p * @returns {(Point & {distance: number})|null} */ closestLayerPoint(p) { p = Point.from(p); let minDistance = Infinity, minPoint = null, p1, p2; const closest = LineUtil._sqClosestPointOnSegment, closed = this._isClosed(); for (const points of this._parts) { for (let i = closed ? 0 : 1, len = points.length; i < len; i++) { p1 = points[(i || len) - 1]; p2 = points[i]; const sqDist = closest(p, p1, p2, true); if (sqDist < minDistance) { minDistance = sqDist; minPoint = closest(p, p1, p2); } } } if (minPoint) { minPoint.distance = Math.sqrt(minDistance); } return minPoint; } /** * Returns the center ([centroid](https://en.wikipedia.org/wiki/Centroid)) of the polyline. * @returns {LatLng} */ getCenter() { // throws error when not yet added to map as this center calculation requires projected coordinates if (!this._map) { throw new Error('Must add layer to map before using getCenter()'); } return LineUtil.polylineCenter(this._defaultShape(), this._map.options.crs); } /** * Returns the `LatLngBounds` of the path. * @returns {LatLngBounds} */ getBounds() { return this._bounds; } /** * Adds a given point to the polyline. By default, adds to the first ring of * the polyline in case of a multi-polyline, but can be overridden by passing * a specific ring as a LatLng array (that you can earlier access with * [`getLatLngs`](#polyline-getlatlngs)). * @param {LatLngExpression} latlng * @param {LatLng[]} [latlngs] * @returns {this} */ addLatLng(latlng, latlngs) { latlngs ??= this._defaultShape(); latlng = new LatLng(latlng); latlngs.push(latlng); this._bounds.extend(latlng); return this.redraw(); } _setLatLngs(latlngs) { this._bounds = new LatLngBounds(); this._latlngs = this._convertLatLngs(latlngs); } _defaultShape() { return LineUtil.isFlat(this._latlngs) ? this._latlngs : this._latlngs[0]; } // recursively convert latlngs input into actual LatLng instances; calculate bounds along the way _convertLatLngs(latlngs) { const result = [], flat = LineUtil.isFlat(latlngs); for (let i = 0, len = latlngs.length; i < len; i++) { if (flat) { result[i] = new LatLng(latlngs[i]); this._bounds.extend(result[i]); } else { result[i] = this._convertLatLngs(latlngs[i]); } } return result; } _project() { const pxBounds = new Bounds(); this._rings = []; this._projectLatlngs(this._latlngs, this._rings, pxBounds); if (this._bounds.isValid() && pxBounds.isValid()) { this._rawPxBounds = pxBounds; this._updateBounds(); } } _updateBounds() { const w = this._clickTolerance(), p = new Point(w, w); if (!this._rawPxBounds) { return; } this._pxBounds = new Bounds([ this._rawPxBounds.min.subtract(p), this._rawPxBounds.max.add(p) ]); } // recursively turns latlngs into a set of rings with projected coordinates _projectLatlngs(latlngs, result, projectedBounds) { const flat = latlngs[0] instanceof LatLng; if (flat) { const ring = latlngs.map(latlng => this._renderer._latLngToLayerPoint(latlng)); ring.forEach(r => projectedBounds.extend(r)); result.push(ring); } else { latlngs.forEach(latlng => this._projectLatlngs(latlng, result, projectedBounds)); } } // clip polyline by renderer bounds so that we have less to render for performance _clipPoints() { const bounds = this._renderer._bounds; this._parts = []; if (!this._pxBounds?.intersects(bounds)) { return; } if (this.options.noClip) { this._parts = this._rings; return; } const parts = this._parts; let k = 0; for (const points of this._rings) { for (let j = 0, len = points.length; j < len - 1; j++) { const segment = LineUtil.clipSegment(points[j], points[j + 1], bounds, j); if (!segment) { continue; } parts[k] ??= []; parts[k].push(segment[0]); // if segment goes out of screen, or it's the last one, it's the end of the line part if ((segment[1] !== points[j + 1]) || (j === len - 2)) { parts[k].push(segment[1]); k++; } } } } // simplify each clipped part of the polyline for performance _simplifyPoints() { const parts = this._parts, tolerance = this.options.smoothFactor; for (let i = 0, len = parts.length; i < len; i++) { parts[i] = LineUtil.simplify(parts[i], tolerance); } } _update() { if (!this._map) { return; } this._clipPoints(); this._simplifyPoints(); this._updatePath(); } _updatePath() { this._renderer._updatePoly(this); } // polygon rings also have a segment from the last point back to the first _isClosed() { return false; } // Needed by the `Canvas` renderer for interactivity _containsPoint(p, closed) { const w = this._clickTolerance(); if (!this._pxBounds?.contains(p)) { return false; } // hit detection for polylines for (const part of this._parts) { for (let j = closed ? 0 : 1, len = part.length; j < len; j++) { if (LineUtil.pointToSegmentDistance(p, part[(j || len) - 1], part[j]) <= w) { return true; } } } return false; } /** * Coordinates values are rounded with [`formatNum`](#util-formatnum) to the * given `precision`. Returns a [`GeoJSON`](https://en.wikipedia.org/wiki/GeoJSON) * representation of the polyline (as a GeoJSON `LineString` or `MultiLineString` * Feature). * @param {number|false} [precision] * @returns {Feature} */ toGeoJSON(precision) { const multi = !LineUtil.isFlat(this._latlngs); const coords = latLngsToCoords(this._latlngs, multi ? 1 : 0, false, precision); return getFeature(this, { type: `${multi ? 'Multi' : ''}LineString`, coordinates: coords }); } }