react-bkoi-gl 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/components/map.tsx","../src/components/use-map.tsx","../src/utils/deep-equal.ts","../src/utils/transform.ts","../src/utils/style-utils.ts","../src/maplibre/maplibre.ts","../src/maplibre/create-ref.ts","../src/utils/use-isomorphic-layout-effect.ts","../src/utils/set-globals.ts","../src/components/logo-control.ts","../src/utils/apply-react-style.ts","../src/components/use-control.ts","../src/components/attribution-control.ts","../src/components/marker.ts","../src/utils/compare-class-names.ts","../src/components/popup.ts","../src/components/fullscreen-control.ts","../src/components/geolocate-control.ts","../src/components/navigation-control.ts","../src/components/scale-control.ts","../src/components/terrain-control.ts","../src/components/source.ts","../src/utils/assert.ts","../src/components/canvas-source.ts","../src/components/layer.ts","../src/components/draw-control.ts","../src/components/globe-control.ts","../src/components/minimap-control.ts","../src/exports-maplibre-gl.ts"],"sourcesContent":["import * as React from 'react'\nimport { useState, useRef, useEffect, useContext, useMemo, useImperativeHandle } from 'react'\n\nimport { MountedMapsContext } from './use-map'\nimport Maplibre, { MaplibreProps } from '../maplibre/maplibre'\nimport createRef, { MapRef } from '../maplibre/create-ref'\n\nimport type { CSSProperties } from 'react'\nimport useIsomorphicLayoutEffect from '../utils/use-isomorphic-layout-effect'\nimport setGlobals, { GlobalSettings } from '../utils/set-globals'\nimport type { MapLib, MapOptions } from '../types/lib'\nimport type { MapOptionsInternal } from '../types/internal'\nimport { LogoControl } from './logo-control'\nimport { AttributionControl } from './attribution-control'\n\nexport type MapContextValue = {\n mapLib: MapLib\n map: MapRef\n}\n\nexport const MapContext = React.createContext<MapContextValue>(null)\n\ntype MapInitOptions = Omit<\n MapOptions,\n 'style' | 'container' | 'bounds' | 'fitBoundsOptions' | 'center'\n>\n\nexport type MapProps = MapInitOptions &\n MaplibreProps &\n GlobalSettings & {\n mapLib?: MapLib | Promise<MapLib>\n reuseMaps?: boolean\n /** Map container id */\n id?: string\n /** Map container CSS style */\n style?: CSSProperties\n children?: React.ReactNode\n } & React.RefAttributes<MapRef>\n\nfunction _Map(props: MapProps, ref: React.Ref<MapRef>) {\n const mountedMapsContext = useContext(MountedMapsContext)\n const [mapInstance, setMapInstance] = useState<Maplibre>(null)\n const containerRef = useRef()\n\n const { current: contextValue } = useRef<MapContextValue>({\n mapLib: null,\n map: null,\n })\n\n useEffect(() => {\n const mapLib = props.mapLib\n let isMounted = true\n let maplibre: Maplibre | null = null\n\n Promise.resolve(mapLib || import('maplibre-gl'))\n .then((module: MapLib | { default: MapLib }) => {\n if (!isMounted) {\n return\n }\n if (!module) {\n throw new Error('Invalid mapLib')\n }\n const mapboxgl = 'Map' in module ? module : module.default\n if (!mapboxgl.Map) {\n throw new Error('Invalid mapLib')\n }\n\n setGlobals(mapboxgl, props)\n if (props.reuseMaps) {\n maplibre = Maplibre.reuse(props, containerRef.current)\n }\n if (!maplibre) {\n maplibre = new Maplibre(\n mapboxgl.Map,\n {\n ...props,\n attributionControl: false,\n } as MapOptions & MapOptionsInternal & MaplibreProps,\n containerRef.current\n )\n }\n if (maplibre) {\n contextValue.map = createRef(maplibre)\n contextValue.mapLib = mapboxgl\n setMapInstance(maplibre)\n }\n mountedMapsContext?.onMapMount(contextValue.map, props.id)\n })\n .catch(error => {\n const { onError } = props\n if (onError) {\n onError({\n type: 'error',\n target: null,\n originalEvent: null,\n error,\n })\n } else {\n console.error(error)\n }\n })\n\n return () => {\n isMounted = false\n if (maplibre) {\n mountedMapsContext?.onMapUnmount(props.id)\n if (props.reuseMaps) {\n maplibre.recycle()\n } else {\n maplibre.destroy()\n }\n }\n }\n }, [])\n\n useIsomorphicLayoutEffect(() => {\n if (mapInstance) {\n mapInstance.setProps(props)\n }\n })\n\n useImperativeHandle(ref, () => contextValue.map, [mapInstance])\n\n const style: CSSProperties = useMemo(\n () => ({\n position: 'relative',\n width: '100%',\n height: '100%',\n ...props.style,\n }),\n [props.style]\n )\n\n const CHILD_CONTAINER_STYLE = {\n height: '100%',\n }\n\n return (\n <div id={props.id} ref={containerRef} style={style}>\n {mapInstance && (\n <MapContext.Provider value={contextValue}>\n <div style={CHILD_CONTAINER_STYLE}>\n {/* Automatically include Barikoi Logo and Attribution controls */}\n <LogoControl position='bottom-left' />\n <AttributionControl position='bottom-right' />\n {props.children}\n </div>\n </MapContext.Provider>\n )}\n </div>\n )\n}\n\nexport const Map: React.FC<MapProps> = React.forwardRef(_Map)\n","import * as React from 'react'\nimport { useState, useCallback, useMemo, useContext } from 'react'\n\nimport { MapRef } from '../maplibre/create-ref'\nimport { MapContext } from './map'\n\ntype MountedMapsContextValue = {\n maps: { [id: string]: MapRef }\n onMapMount: (map: MapRef, id: string) => void\n onMapUnmount: (id: string) => void\n}\n\nexport const MountedMapsContext = React.createContext<MountedMapsContextValue>(null)\n\nexport const MapProvider: React.FC<{ children?: React.ReactNode }> = props => {\n const [maps, setMaps] = useState<{ [id: string]: MapRef }>({})\n\n const onMapMount = useCallback((map: MapRef, id: string = 'default') => {\n setMaps(currMaps => {\n if (id === 'current') {\n throw new Error(\"'current' cannot be used as map id\")\n }\n if (currMaps[id]) {\n throw new Error(`Multiple maps with the same id: ${id}`)\n }\n return { ...currMaps, [id]: map }\n })\n }, [])\n\n const onMapUnmount = useCallback((id: string = 'default') => {\n setMaps(currMaps => {\n if (currMaps[id]) {\n const nextMaps = { ...currMaps }\n delete nextMaps[id]\n return nextMaps\n }\n return currMaps\n })\n }, [])\n\n return (\n <MountedMapsContext.Provider\n value={{\n maps,\n onMapMount,\n onMapUnmount,\n }}\n >\n {props.children}\n </MountedMapsContext.Provider>\n )\n}\n\nexport type MapCollection = {\n [id: string]: MapRef | undefined\n current?: MapRef\n}\n\nexport function useMap(): MapCollection {\n const maps = useContext(MountedMapsContext)?.maps\n const currentMap = useContext(MapContext)\n\n const mapsWithCurrent = useMemo(() => {\n // If currentMap is available from MapContext, use it\n // Otherwise, fall back to the first registered map from MountedMapsContext\n const current = currentMap?.map || (maps ? Object.values(maps)[0] : undefined)\n return { ...maps, current }\n }, [maps, currentMap])\n\n return mapsWithCurrent as MapCollection\n}\n","import type { PointLike } from '../types/common'\n\n/**\n * Compare two points\n * @param a\n * @param b\n * @returns true if the points are equal\n */\nexport function arePointsEqual(a?: PointLike, b?: PointLike): boolean {\n const ax = Array.isArray(a) ? a[0] : a ? a.x : 0\n const ay = Array.isArray(a) ? a[1] : a ? a.y : 0\n const bx = Array.isArray(b) ? b[0] : b ? b.x : 0\n const by = Array.isArray(b) ? b[1] : b ? b.y : 0\n return ax === bx && ay === by\n}\n\n/**\n * Compare any two objects\n * @param a\n * @param b\n * @returns true if the objects are deep equal\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true\n }\n if (!a || !b) {\n return false\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) {\n return false\n }\n }\n return true\n } else if (Array.isArray(b)) {\n return false\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const aKeys = Object.keys(a)\n const bKeys = Object.keys(b)\n if (aKeys.length !== bKeys.length) {\n return false\n }\n for (const key of aKeys) {\n if (!Object.prototype.hasOwnProperty.call(b, key)) {\n return false\n }\n if (!deepEqual(a[key], b[key])) {\n return false\n }\n }\n return true\n }\n return false\n}\n","import type { MaplibreProps } from '../maplibre/maplibre'\nimport type { ViewState } from '../types/common'\nimport type { TransformLike } from '../types/internal'\nimport { deepEqual } from './deep-equal'\n\n/**\n * Capture a transform's current state\n * @param transform\n * @returns descriptor of the view state\n */\nexport function transformToViewState(tr: TransformLike): ViewState {\n return {\n longitude: tr.center.lng,\n latitude: tr.center.lat,\n zoom: tr.zoom,\n pitch: tr.pitch,\n bearing: tr.bearing,\n padding: tr.padding,\n }\n}\n\n/**\n * Applies requested view state to a transform\n * @returns an object containing detected changes\n */\nexport function applyViewStateToTransform(\n /** An object that describes Maplibre's camera state */\n tr: TransformLike,\n /** Props from Map component */\n props: MaplibreProps\n): Partial<TransformLike> {\n const v: Partial<ViewState> = props.viewState || props\n const changes: Partial<TransformLike> = {}\n\n if (\n 'longitude' in v &&\n 'latitude' in v &&\n (v.longitude !== tr.center.lng || v.latitude !== tr.center.lat)\n ) {\n const LngLat = tr.center.constructor\n // @ts-expect-error we should not import LngLat class from maplibre-gl because we don't know the source of mapLib\n changes.center = new LngLat(v.longitude, v.latitude)\n }\n if ('zoom' in v && v.zoom !== tr.zoom) {\n changes.zoom = v.zoom\n }\n if ('bearing' in v && v.bearing !== tr.bearing) {\n changes.bearing = v.bearing\n }\n if ('pitch' in v && v.pitch !== tr.pitch) {\n changes.pitch = v.pitch\n }\n if (v.padding && tr.padding && !deepEqual(v.padding, tr.padding)) {\n changes.padding = v.padding\n }\n return changes\n}\n","import type { StyleSpecification } from '../types/style-spec'\nimport type { ImmutableLike } from '../types/common'\n\nconst refProps = ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout']\n\n// Legacy layer type with optional fields not in current type definitions\ninterface LegacyLayer {\n id: string\n interactive?: boolean\n ref?: string\n [key: string]: unknown\n}\n\n// Prepare a map style object for diffing\n// If immutable - convert to plain object\n// Work around some issues in older styles that would fail Mapbox's diffing\nexport function normalizeStyle(\n style: string | StyleSpecification | ImmutableLike<StyleSpecification>\n): string | StyleSpecification | null {\n if (!style) {\n return null\n }\n if (typeof style === 'string') {\n return style\n }\n if ('toJS' in style) {\n style = style.toJS()\n }\n if (!style.layers) {\n return style\n }\n const layerIndex: Record<string, LegacyLayer> = {}\n\n for (const layer of style.layers) {\n layerIndex[layer.id] = layer as LegacyLayer\n }\n\n const layers = style.layers.map(layer => {\n const legacyLayer = layer as LegacyLayer\n let normalizedLayer: LegacyLayer | null = null\n\n if ('interactive' in legacyLayer) {\n normalizedLayer = Object.assign({}, legacyLayer)\n // Breaks style diffing :(\n delete normalizedLayer.interactive\n }\n\n // Style diffing doesn't work with refs so expand them out manually before diffing.\n const layerRef = layerIndex[legacyLayer.ref as string]\n if (layerRef) {\n normalizedLayer = normalizedLayer || Object.assign({}, legacyLayer)\n delete normalizedLayer.ref\n // https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/deref.js\n for (const propName of refProps) {\n if (propName in layerRef) {\n normalizedLayer[propName] = layerRef[propName]\n }\n }\n }\n\n return (normalizedLayer || layer) as typeof layer\n })\n\n // Do not mutate the style object provided by the user\n return { ...style, layers }\n}\n","import { transformToViewState, applyViewStateToTransform } from '../utils/transform'\nimport { normalizeStyle } from '../utils/style-utils'\nimport { deepEqual } from '../utils/deep-equal'\n\nimport type { TransformLike, MapInternalProperties, MapWithProjection } from '../types/internal'\nimport type {\n ViewState,\n Point,\n PointLike,\n PaddingOptions,\n ImmutableLike,\n LngLatBoundsLike,\n MapGeoJSONFeature,\n} from '../types/common'\nimport type {\n StyleSpecification,\n SkySpecification,\n LightSpecification,\n TerrainSpecification,\n ProjectionSpecification,\n} from '../types/style-spec'\nimport type { Map as MapInstance } from '../types/lib'\nimport type {\n MapCallbacks,\n ViewStateChangeEvent,\n MapEvent,\n ErrorEvent,\n MapMouseEvent,\n} from '../types/events'\n\nexport type MaplibreProps = Partial<ViewState> &\n MapCallbacks & {\n /** Camera options used when constructing the Map instance */\n initialViewState?: Partial<ViewState> & {\n /** The initial bounds of the map. If bounds is specified, it overrides longitude, latitude and zoom options. */\n bounds?: LngLatBoundsLike\n /** A fitBounds options object to use only when setting the bounds option. */\n fitBoundsOptions?: {\n offset?: PointLike\n minZoom?: number\n maxZoom?: number\n padding?: number | PaddingOptions\n }\n }\n\n /** If provided, render into an external WebGL context */\n gl?: WebGLRenderingContext\n\n /** For external controller to override the camera state */\n viewState?: ViewState & {\n width: number\n height: number\n }\n\n // Styling\n\n /** Mapbox style */\n mapStyle?: string | StyleSpecification | ImmutableLike<StyleSpecification>\n /** Enable diffing when the map style changes\n * @default true\n */\n styleDiffing?: boolean\n /** The projection property of the style. Must conform to the Projection Style Specification.\n * @default 'mercator'\n */\n projection?: ProjectionSpecification | 'mercator' | 'globe'\n /** Light properties of the map. */\n light?: LightSpecification\n /** Terrain property of the style. Must conform to the Terrain Style Specification.\n * If `undefined` is provided, removes terrain from the map. */\n terrain?: TerrainSpecification\n /** Sky properties of the map. Must conform to the Sky Style Specification. */\n sky?: SkySpecification\n\n /** Default layers to query on pointer events */\n interactiveLayerIds?: string[]\n /** CSS cursor */\n cursor?: string\n }\n\nconst DEFAULT_STYLE = {\n version: 8,\n sources: {},\n layers: [],\n} as StyleSpecification\n\nconst pointerEvents = {\n mousedown: 'onMouseDown',\n mouseup: 'onMouseUp',\n mouseover: 'onMouseOver',\n mousemove: 'onMouseMove',\n click: 'onClick',\n dblclick: 'onDblClick',\n mouseenter: 'onMouseEnter',\n mouseleave: 'onMouseLeave',\n mouseout: 'onMouseOut',\n contextmenu: 'onContextMenu',\n touchstart: 'onTouchStart',\n touchend: 'onTouchEnd',\n touchmove: 'onTouchMove',\n touchcancel: 'onTouchCancel',\n}\nconst cameraEvents = {\n movestart: 'onMoveStart',\n move: 'onMove',\n moveend: 'onMoveEnd',\n dragstart: 'onDragStart',\n drag: 'onDrag',\n dragend: 'onDragEnd',\n zoomstart: 'onZoomStart',\n zoom: 'onZoom',\n zoomend: 'onZoomEnd',\n rotatestart: 'onRotateStart',\n rotate: 'onRotate',\n rotateend: 'onRotateEnd',\n pitchstart: 'onPitchStart',\n pitch: 'onPitch',\n pitchend: 'onPitchEnd',\n}\nconst otherEvents = {\n wheel: 'onWheel',\n boxzoomstart: 'onBoxZoomStart',\n boxzoomend: 'onBoxZoomEnd',\n boxzoomcancel: 'onBoxZoomCancel',\n resize: 'onResize',\n load: 'onLoad',\n render: 'onRender',\n idle: 'onIdle',\n remove: 'onRemove',\n data: 'onData',\n styledata: 'onStyleData',\n sourcedata: 'onSourceData',\n error: 'onError',\n}\nconst settingNames = [\n 'minZoom',\n 'maxZoom',\n 'minPitch',\n 'maxPitch',\n 'maxBounds',\n 'projection',\n 'renderWorldCopies',\n]\nconst handlerNames = [\n 'scrollZoom',\n 'boxZoom',\n 'dragRotate',\n 'dragPan',\n 'keyboard',\n 'doubleClickZoom',\n 'touchZoomRotate',\n 'touchPitch',\n]\n\n/**\n * A wrapper for mapbox-gl's Map class\n */\n\nexport default class Maplibre {\n private _MapClass: { new (options: unknown): MapInstance }\n // mapboxgl.Map instance\n private _map: MapInstance = null\n // User-supplied props\n props: MaplibreProps\n\n // Internal states\n private _internalUpdate: boolean = false\n private _hoveredFeatures: MapGeoJSONFeature[] = null\n private _propsedCameraUpdate: ViewState | null = null\n private _styleComponents: {\n light?: LightSpecification\n sky?: SkySpecification\n projection?: ProjectionSpecification\n terrain?: TerrainSpecification | null\n } = {}\n\n static savedMaps: Maplibre[] = []\n\n constructor(\n MapClass: { new (options: unknown): MapInstance },\n props: MaplibreProps,\n container: HTMLDivElement\n ) {\n this._MapClass = MapClass\n this.props = props\n this._initialize(container)\n }\n\n get map(): MapInstance {\n return this._map\n }\n\n setProps(props: MaplibreProps) {\n const oldProps = this.props\n this.props = props\n\n const settingsChanged = this._updateSettings(props, oldProps)\n const sizeChanged = this._updateSize(props)\n const viewStateChanged = this._updateViewState(props)\n this._updateStyle(props, oldProps)\n this._updateStyleComponents(props)\n this._updateHandlers(props, oldProps)\n\n // If 1) view state has changed to match props and\n // 2) the props change is not triggered by map events,\n // it's driven by an external state change. Redraw immediately\n if (settingsChanged || sizeChanged || (viewStateChanged && !this._map.isMoving())) {\n this.redraw()\n }\n }\n\n static reuse(props: MaplibreProps, container: HTMLDivElement): Maplibre {\n const that = Maplibre.savedMaps.pop()\n if (!that) {\n return null\n }\n\n const map = that.map\n // When reusing the saved map, we need to reparent the map(canvas) and other child nodes\n // intoto the new container from the props.\n // Step 1: reparenting child nodes from old container to new container\n const oldContainer = map.getContainer()\n container.className = oldContainer.className\n while (oldContainer.childNodes.length > 0) {\n container.appendChild(oldContainer.childNodes[0])\n }\n // Step 2: replace the internal container with new container from the react component\n const mapInternal = map as unknown as MapInternalProperties\n mapInternal._container = container\n\n // With maplibre-gl as mapLib, map uses ResizeObserver to observe when its container resizes.\n // When reusing the saved map, we need to disconnect the observer and observe the new container.\n // Step 3: telling the ResizeObserver to disconnect and observe the new container\n const resizeObserver = mapInternal._resizeObserver\n if (resizeObserver) {\n resizeObserver.disconnect()\n resizeObserver.observe(container)\n }\n\n // Step 4: apply new props\n that.setProps({ ...props, styleDiffing: false })\n map.resize()\n const { initialViewState } = props\n if (initialViewState) {\n if (initialViewState.bounds) {\n map.fitBounds(initialViewState.bounds, {\n ...initialViewState.fitBoundsOptions,\n duration: 0,\n })\n } else {\n that._updateViewState(initialViewState)\n }\n }\n\n // Simulate load event\n if (map.isStyleLoaded()) {\n map.fire('load')\n } else {\n map.once('style.load', () => map.fire('load'))\n }\n\n // Force reload\n const mapInternalForUpdate = map as unknown as MapInternalProperties\n mapInternalForUpdate._update()\n return that\n }\n\n private _initialize(container: HTMLDivElement) {\n const { props } = this\n const { mapStyle = DEFAULT_STYLE } = props\n const mapOptions = {\n ...props,\n ...props.initialViewState,\n container,\n style: normalizeStyle(mapStyle),\n }\n\n const viewState = mapOptions.initialViewState || mapOptions.viewState || mapOptions\n Object.assign(mapOptions, {\n center: [viewState.longitude || 0, viewState.latitude || 0],\n zoom: viewState.zoom || 0,\n pitch: viewState.pitch || 0,\n bearing: viewState.bearing || 0,\n })\n\n if (props.gl) {\n const getContext = HTMLCanvasElement.prototype.getContext\n // Hijack canvas.getContext to return our own WebGLContext\n // This will be called inside the mapboxgl.Map constructor\n // @ts-expect-error - temporarily overriding getContext to inject custom WebGL context\n HTMLCanvasElement.prototype.getContext = () => {\n // Unhijack immediately\n HTMLCanvasElement.prototype.getContext = getContext\n return props.gl\n }\n }\n\n const map = new this._MapClass(mapOptions)\n // Props that are not part of constructor options\n if (viewState.padding) {\n map.setPadding(viewState.padding)\n }\n if (props.cursor) {\n map.getCanvas().style.cursor = props.cursor\n }\n\n // add listeners\n map.transformCameraUpdate = this._onCameraUpdate\n map.on('style.load', () => {\n // Map style has changed, this would have wiped out all settings from props\n const mapWithProjection = map as unknown as MapWithProjection\n this._styleComponents = {\n light: map.getLight(),\n sky: map.getSky(),\n projection: mapWithProjection.getProjection?.(),\n terrain: map.getTerrain(),\n }\n this._updateStyleComponents(this.props)\n })\n map.on('sourcedata', () => {\n // Some sources have loaded, we may need them to attach terrain\n this._updateStyleComponents(this.props)\n })\n for (const eventName in pointerEvents) {\n map.on(eventName, this._onPointerEvent)\n }\n for (const eventName in cameraEvents) {\n map.on(eventName, this._onCameraEvent)\n }\n for (const eventName in otherEvents) {\n map.on(eventName, this._onEvent)\n }\n this._map = map\n }\n\n recycle() {\n // Clean up unnecessary elements before storing for reuse.\n const container = this.map.getContainer()\n const children = container.querySelector('[mapboxgl-children]')\n children?.remove()\n\n Maplibre.savedMaps.push(this)\n }\n\n destroy() {\n this._map.remove()\n }\n\n // Force redraw the map now. Typically resize() and jumpTo() is reflected in the next\n // render cycle, which is managed by Mapbox's animation loop.\n // This removes the synchronization issue caused by requestAnimationFrame.\n redraw() {\n const map = this._map as unknown as {\n style: unknown\n _frame: { cancel: () => void } | null\n _render: () => void\n }\n // map._render will throw error if style does not exist\n // https://github.com/mapbox/mapbox-gl-js/blob/fb9fc316da14e99ff4368f3e4faa3888fb43c513\n // /src/ui/map.js#L1834\n if (map.style) {\n // cancel the scheduled update\n if (map._frame) {\n map._frame.cancel()\n map._frame = null\n }\n // the order is important - render() may schedule another update\n map._render()\n }\n }\n\n /* Trigger map resize if size is controlled\n @param {object} nextProps\n @returns {bool} true if size has changed\n */\n private _updateSize(nextProps: MaplibreProps): boolean {\n // Check if size is controlled\n const { viewState } = nextProps\n if (viewState) {\n const map = this._map\n if (viewState.width !== map.transform.width || viewState.height !== map.transform.height) {\n map.resize()\n return true\n }\n }\n return false\n }\n\n // Adapted from map.jumpTo\n /* Update camera to match props\n @param {object} nextProps\n @param {bool} triggerEvents - should fire camera events\n @returns {bool} true if anything is changed\n */\n private _updateViewState(nextProps: MaplibreProps): boolean {\n const map = this._map\n const tr = map.transform\n const isMoving = map.isMoving()\n\n // Avoid manipulating the real transform when interaction/animation is ongoing\n // as it would interfere with Mapbox's handlers\n if (!isMoving) {\n const changes: Record<string, unknown> = applyViewStateToTransform(tr, nextProps)\n if (Object.keys(changes).length > 0) {\n this._internalUpdate = true\n map.jumpTo(changes)\n this._internalUpdate = false\n return true\n }\n }\n\n return false\n }\n\n /* Update camera constraints and projection settings to match props\n @param {object} nextProps\n @param {object} currProps\n @returns {bool} true if anything is changed\n */\n private _updateSettings(nextProps: MaplibreProps, currProps: MaplibreProps): boolean {\n const map = this._map\n let changed = false\n for (const propName of settingNames) {\n if (propName in nextProps && !deepEqual(nextProps[propName], currProps[propName])) {\n changed = true\n const setter = map[`set${propName[0].toUpperCase()}${propName.slice(1)}`]\n setter?.call(map, nextProps[propName])\n }\n }\n return changed\n }\n\n /* Update map style to match props */\n private _updateStyle(nextProps: MaplibreProps, currProps: MaplibreProps): void {\n if (nextProps.cursor !== currProps.cursor) {\n this._map.getCanvas().style.cursor = nextProps.cursor || ''\n }\n if (nextProps.mapStyle !== currProps.mapStyle) {\n const { mapStyle = DEFAULT_STYLE, styleDiffing = true } = nextProps\n const options: Record<string, unknown> = {\n diff: styleDiffing,\n }\n if ('localIdeographFontFamily' in nextProps) {\n // Mapbox specific prop not in maplibre types\n options.localIdeographFontFamily = nextProps.localIdeographFontFamily\n }\n this._map.setStyle(normalizeStyle(mapStyle), options)\n }\n }\n\n /* Update fog, light, projection and terrain to match props\n * These props are special because\n * 1. They can not be applied right away. Certain conditions (style loaded, source loaded, etc.) must be met\n * 2. They can be overwritten by mapStyle\n */\n private _updateStyleComponents({ light, projection, sky, terrain }: MaplibreProps): void {\n const map = this._map\n const currProps = this._styleComponents\n const mapWithProjection = map as unknown as MapWithProjection\n // We can safely manipulate map style once it's loaded\n if (map.style._loaded) {\n if (light && !deepEqual(light, currProps.light)) {\n currProps.light = light\n map.setLight(light)\n }\n if (\n projection &&\n !deepEqual(projection, currProps.projection) &&\n projection !== currProps.projection?.type\n ) {\n currProps.projection = typeof projection === 'string' ? { type: projection } : projection\n mapWithProjection.setProjection?.(currProps.projection)\n }\n if (sky && !deepEqual(sky, currProps.sky)) {\n currProps.sky = sky\n map.setSky(sky)\n }\n if (terrain !== undefined && !deepEqual(terrain, currProps.terrain)) {\n if (!terrain || map.getSource(terrain.source)) {\n currProps.terrain = terrain\n map.setTerrain(terrain)\n }\n }\n }\n }\n\n /* Update interaction handlers to match props */\n private _updateHandlers(nextProps: MaplibreProps, currProps: MaplibreProps): void {\n const map = this._map\n for (const propName of handlerNames) {\n const newValue = nextProps[propName] ?? true\n const oldValue = currProps[propName] ?? true\n if (!deepEqual(newValue, oldValue)) {\n if (newValue) {\n map[propName].enable(newValue)\n } else {\n map[propName].disable()\n }\n }\n }\n }\n\n private _onEvent = (e: MapEvent) => {\n const handlerName = otherEvents[e.type] as keyof MapCallbacks\n const cb = this.props[handlerName] as ((e: MapEvent) => void) | undefined\n if (cb) {\n cb(e)\n } else if (e.type === 'error') {\n console.error((e as ErrorEvent).error)\n }\n }\n\n private _onCameraEvent = (e: ViewStateChangeEvent) => {\n if (this._internalUpdate) {\n return\n }\n e.viewState = this._propsedCameraUpdate || transformToViewState(this._map.transform)\n const handlerName = cameraEvents[e.type] as keyof MapCallbacks\n const cb = this.props[handlerName] as ((e: ViewStateChangeEvent) => void) | undefined\n if (cb) {\n cb(e)\n }\n }\n\n private _onCameraUpdate = (tr: TransformLike) => {\n if (this._internalUpdate) {\n return tr\n }\n this._propsedCameraUpdate = transformToViewState(tr)\n return applyViewStateToTransform(tr, this.props) as TransformLike\n }\n\n private _queryRenderedFeatures(point: Point) {\n const map = this._map\n const { interactiveLayerIds = [] } = this.props\n try {\n return map.queryRenderedFeatures(point, {\n layers: interactiveLayerIds.filter(map.getLayer.bind(map)),\n })\n } catch {\n // May fail if style is not loaded\n return []\n }\n }\n\n private _updateHover(e: MapMouseEvent) {\n const { props } = this\n const shouldTrackHoveredFeatures =\n props.interactiveLayerIds && (props.onMouseMove || props.onMouseEnter || props.onMouseLeave)\n\n if (shouldTrackHoveredFeatures) {\n const eventType = e.type\n const wasHovering = this._hoveredFeatures?.length > 0\n const features = this._queryRenderedFeatures(e.point)\n const isHovering = features.length > 0\n\n if (!isHovering && wasHovering) {\n e.type = 'mouseleave'\n this._onPointerEvent(e)\n }\n this._hoveredFeatures = features\n if (isHovering && !wasHovering) {\n e.type = 'mouseenter'\n this._onPointerEvent(e)\n }\n e.type = eventType\n } else {\n this._hoveredFeatures = null\n }\n }\n\n private _onPointerEvent = (e: MapMouseEvent) => {\n if (e.type === 'mousemove' || e.type === 'mouseout') {\n this._updateHover(e)\n }\n\n const handlerName = pointerEvents[e.type as keyof typeof pointerEvents] as keyof MapCallbacks\n const cb = this.props[handlerName] as ((e: MapMouseEvent) => void) | undefined\n if (cb) {\n if (this.props.interactiveLayerIds && e.type !== 'mouseover' && e.type !== 'mouseout') {\n e.features = this._hoveredFeatures || this._queryRenderedFeatures(e.point)\n }\n cb(e)\n delete e.features\n }\n }\n}\n","import type { Map as MapInstance } from '../types/lib'\nimport type Maplibre from './maplibre'\n\n/** These methods may break the react binding if called directly */\nconst skipMethods = [\n 'setMaxBounds',\n 'setMinZoom',\n 'setMaxZoom',\n 'setMinPitch',\n 'setMaxPitch',\n 'setRenderWorldCopies',\n 'setProjection',\n 'setStyle',\n 'addSource',\n 'removeSource',\n 'addLayer',\n 'removeLayer',\n 'setLayerZoomRange',\n 'setFilter',\n 'setPaintProperty',\n 'setLayoutProperty',\n 'setLight',\n 'setTerrain',\n 'setFog',\n 'remove',\n] as const\n\nexport type MapRef = {\n getMap(): MapInstance\n} & Omit<MapInstance, (typeof skipMethods)[number]>\n\nexport default function createRef(mapInstance: Maplibre): MapRef | null {\n if (!mapInstance) {\n return null\n }\n\n const map = mapInstance.map\n\n const result: any = {\n getMap: () => map,\n }\n\n for (const key of getMethodNames(map)) {\n // @ts-expect-error - dynamically binding map methods to result object\n if (!(key in result) && !skipMethods.includes(key)) {\n result[key] = map[key].bind(map)\n }\n }\n\n return result\n}\n\nfunction getMethodNames(obj: object) {\n const result = new Set<string>()\n\n let proto = obj\n while (proto) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n if (\n key[0] !== '_' &&\n typeof obj[key] === 'function' &&\n key !== 'fire' &&\n key !== 'setEventedParent'\n ) {\n result.add(key)\n }\n }\n proto = Object.getPrototypeOf(proto)\n }\n return Array.from(result)\n}\n","// From https://github.com/streamich/react-use/blob/master/src/useIsomorphicLayoutEffect.ts\n// useLayoutEffect but does not trigger warning in server-side rendering\nimport { useEffect, useLayoutEffect } from 'react'\n\nconst useIsomorphicLayoutEffect = typeof document !== 'undefined' ? useLayoutEffect : useEffect\n\nexport default useIsomorphicLayoutEffect\n","export type GlobalSettings = {\n /** The maximum number of images (raster tiles, sprites, icons) to load in parallel.\n * @default 16\n */\n maxParallelImageRequests?: number\n /** The map's RTL text plugin. Necessary for supporting the Arabic and Hebrew languages, which are written right-to-left. */\n RTLTextPlugin?: string | { pluginUrl: string; lazy?: boolean }\n /** The number of web workers instantiated on a page with maplibre-gl maps.\n * @default 2\n */\n workerCount?: number\n /** Provides an interface for loading maplibre-gl's WebWorker bundle from a self-hosted URL.\n * This is useful if your site needs to operate in a strict CSP (Content Security Policy) environment\n * wherein you are not allowed to load JavaScript code from a Blob URL, which is default behavior. */\n workerUrl?: string\n}\n\n/**\n * Validates that a URL uses a safe protocol (http/https)\n */\nconst validateUrl = (url: string, settingName: string): boolean => {\n try {\n const parsed = new URL(url)\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n console.warn(`${settingName}: Only http/https protocols are allowed, got: ${parsed.protocol}`)\n return false\n }\n return true\n } catch {\n console.warn(`${settingName}: Invalid URL format: ${url}`)\n return false\n }\n}\n\nexport default function setGlobals(mapLib: any, props: GlobalSettings) {\n const { RTLTextPlugin, maxParallelImageRequests, workerCount, workerUrl } = props\n if (\n RTLTextPlugin &&\n mapLib.getRTLTextPluginStatus &&\n mapLib.getRTLTextPluginStatus() === 'unavailable'\n ) {\n const { pluginUrl, lazy = true } =\n typeof RTLTextPlugin === 'string' ? { pluginUrl: RTLTextPlugin } : RTLTextPlugin\n\n if (validateUrl(pluginUrl, 'RTLTextPlugin')) {\n mapLib.setRTLTextPlugin(\n pluginUrl,\n (error?: Error) => {\n if (error) {\n console.error(error)\n }\n },\n lazy\n )\n }\n }\n if (maxParallelImageRequests !== undefined) {\n mapLib.setMaxParallelImageRequests(maxParallelImageRequests)\n }\n if (workerCount !== undefined) {\n mapLib.setWorkerCount(workerCount)\n }\n if (workerUrl !== undefined) {\n if (validateUrl(workerUrl, 'workerUrl')) {\n mapLib.setWorkerUrl(workerUrl)\n }\n }\n}\n","import * as React from 'react'\nimport { useEffect, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type {\n ControlPosition,\n LogoControlOptions,\n IControl,\n Map as MaplibreMap,\n} from '../types/lib'\n\nexport type LogoControlProps = LogoControlOptions & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _LogoControl(props: LogoControlProps) {\n // Create custom control\n const ctrl = useControl(\n () => {\n const control: IControl & { _container?: HTMLElement } = {\n onAdd: (map: MaplibreMap): HTMLElement => {\n // Check if logo already exists\n if (map.getContainer) {\n const existingLogo = map\n .getContainer()\n .querySelector('a.maplibregl-ctrl-logo[href=\"https://www.barikoi.com\"]')\n if (existingLogo) {\n existingLogo.remove()\n }\n }\n\n const container = document.createElement('a')\n container.className = 'maplibregl-ctrl-logo'\n container.href = 'https://www.barikoi.com'\n container.target = '_blank'\n container.setAttribute('alt', 'Barikoi')\n container.setAttribute('aria-label', 'Barikoi logo')\n container.setAttribute('rel', 'noopener nofollow')\n control._container = container\n return container\n },\n onRemove: (): void => {\n delete control._container\n },\n }\n return control\n },\n { position: props.position }\n )\n\n useEffect(() => {\n applyReactStyle(ctrl._container, props.style)\n }, [props.style, ctrl._container])\n\n return null\n}\n\nexport const LogoControl: React.FC<LogoControlProps> = memo(_LogoControl)\n","import * as React from 'react'\n// This is a simplified version of\n// https://github.com/facebook/react/blob/4131af3e4bf52f3a003537ec95a1655147c81270/src/renderers/dom/shared/CSSPropertyOperations.js#L62\nconst unitlessNumber = /box|flex|grid|column|lineHeight|fontWeight|opacity|order|tabSize|zIndex/\n\nexport function applyReactStyle(element: HTMLElement, styles: React.CSSProperties) {\n if (!element || !styles) {\n return\n }\n const style = element.style\n\n for (const key in styles) {\n const value = styles[key]\n if (Number.isFinite(value) && !unitlessNumber.test(key)) {\n style[key] = `${value}px`\n } else {\n style[key] = value\n }\n }\n}\n","import { useContext, useMemo, useEffect } from 'react'\nimport type { IControl, ControlPosition, MapControl } from '../types/lib'\nimport { MapContext } from './map'\nimport type { MapContextValue } from './map'\n\ntype ControlOptions = {\n position?: ControlPosition\n}\n\nexport function useControl<T extends MapControl>(\n onCreate: (context: MapContextValue) => T,\n opts?: ControlOptions\n): T\n\nexport function useControl<T extends MapControl>(\n onCreate: (context: MapContextValue) => T,\n onRemove: (context: MapContextValue) => void,\n opts?: ControlOptions\n): T\n\nexport function useControl<T extends MapControl>(\n onCreate: (context: MapContextValue) => T,\n onAdd: (context: MapContextValue) => void,\n onRemove: (context: MapContextValue) => void,\n opts?: ControlOptions\n): T\n\nexport function useControl<T extends MapControl>(\n onCreate: (context: MapContextValue) => T,\n arg1?: ((context: MapContextValue) => void) | ControlOptions,\n arg2?: ((context: MapContextValue) => void) | ControlOptions,\n arg3?: ControlOptions\n): T {\n const context = useContext(MapContext)\n\n if (!context) {\n throw new Error('useControl must be used within a Map component')\n }\n\n const ctrl = useMemo(() => onCreate(context), [])\n\n useEffect(() => {\n const opts = (arg3 || arg2 || arg1) as ControlOptions\n const onAdd = typeof arg1 === 'function' && typeof arg2 === 'function' ? arg1 : null\n const onRemove = typeof arg2 === 'function' ? arg2 : typeof arg1 === 'function' ? arg1 : null\n\n const { map } = context\n const ctrlAsIControl = ctrl as unknown as IControl\n if (!map.hasControl(ctrlAsIControl)) {\n map.addControl(ctrlAsIControl, opts?.position)\n if (onAdd) {\n onAdd(context)\n }\n }\n\n return () => {\n if (onRemove) {\n onRemove(context)\n }\n // Map might have been removed (parent effects are destroyed before child ones)\n if (map.hasControl(ctrlAsIControl)) {\n map.removeControl(ctrlAsIControl)\n }\n }\n }, [])\n\n return ctrl\n}\n","import * as React from 'react'\nimport { useEffect, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\nimport { useMap } from './use-map'\n\nimport type { ControlPosition, AttributionControlOptions } from '../types/lib'\n\nexport type AttributionControlProps = AttributionControlOptions & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _AttributionControl(props: AttributionControlProps) {\n const { current: map } = useMap()\n\n const ctrl = useControl(\n ({ mapLib }) =>\n new mapLib.AttributionControl({\n compact: true,\n ...props,\n }),\n { position: props.position }\n )\n\n useEffect(() => {\n applyReactStyle(ctrl._container, props.style)\n\n if (!ctrl._container || !map) return\n\n const onLoad = () => {\n setTimeout(() => {\n const inner = ctrl._container.querySelector('.maplibregl-ctrl-attrib-inner')\n\n if (inner) {\n // Use DOM APIs instead of innerHTML for security\n inner.textContent = ''\n\n const createLink = (text: string, href: string) => {\n const a = document.createElement('a')\n a.href = href\n a.target = '_blank'\n a.rel = 'noopener noreferrer'\n a.textContent = text\n return a\n }\n\n inner.appendChild(createLink('Barikoi', 'https://barikoi.com'))\n inner.appendChild(document.createTextNode(' © '))\n inner.appendChild(createLink('OpenMapTiles', 'https://openmaptiles.org'))\n inner.appendChild(document.createTextNode(' © '))\n inner.appendChild(\n createLink('OpenStreetMap contributors', 'https://www.openstreetmap.org/copyright')\n )\n }\n }, 0)\n }\n\n if (map.loaded()) {\n onLoad()\n } else {\n map.once('load', onLoad)\n }\n\n return () => {\n map.off('load', onLoad)\n }\n }, [props.style, ctrl._container, map])\n\n return null\n}\n\nexport const AttributionControl: React.FC<AttributionControlProps> = memo(_AttributionControl)\n","/* global document */\nimport * as React from 'react'\nimport { createPortal } from 'react-dom'\nimport {\n useImperativeHandle,\n useEffect,\n useMemo,\n useRef,\n useContext,\n forwardRef,\n memo,\n} from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\n\nimport type { Popup as PopupInstance, Marker as MarkerInstance, MarkerOptions } from '../types/lib'\nimport type { MarkerEvent, MarkerDragEvent } from '../types/events'\n\nimport { MapContext } from './map'\nimport { arePointsEqual } from '../utils/deep-equal'\nimport { compareClassNames } from '../utils/compare-class-names'\n\nexport type MarkerProps = MarkerOptions & {\n /** Longitude of the anchor location */\n longitude: number\n /** Latitude of the anchor location */\n latitude: number\n\n popup?: PopupInstance\n\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n onClick?: (e: MarkerEvent<MouseEvent>) => void\n onDragStart?: (e: MarkerDragEvent) => void\n onDrag?: (e: MarkerDragEvent) => void\n onDragEnd?: (e: MarkerDragEvent) => void\n children?: React.ReactNode\n}\n\nexport const Marker: React.FC<MarkerProps> = memo(\n forwardRef((props: MarkerProps, ref: React.Ref<MarkerInstance>) => {\n const { map, mapLib } = useContext(MapContext)\n const callbackRef = useRef<{\n onClick?: MarkerProps['onClick']\n onDragStart?: MarkerProps['onDragStart']\n onDrag?: MarkerProps['onDrag']\n onDragEnd?: MarkerProps['onDragEnd']\n }>({})\n\n const marker: MarkerInstance = useMemo(() => {\n let hasChildren = false\n React.Children.forEach(props.children, el => {\n if (el) {\n hasChildren = true\n }\n })\n const options = {\n ...props,\n element: hasChildren ? document.createElement('div') : undefined,\n }\n\n const mk = new mapLib.Marker(options)\n mk.setLngLat([props.longitude, props.latitude])\n\n return mk\n }, [])\n\n useEffect(() => {\n callbackRef.current = {\n onClick: props.onClick,\n onDragStart: props.onDragStart,\n onDrag: props.onDrag,\n onDragEnd: props.onDragEnd,\n }\n })\n\n useEffect(() => {\n const clickHandler = (e: MouseEvent) => {\n callbackRef.current.onClick?.({\n type: 'click',\n target: marker,\n originalEvent: e,\n })\n }\n\n marker.getElement().addEventListener('click', clickHandler)\n\n const dragStartHandler = (e: MarkerDragEvent) => {\n e.lngLat = marker.getLngLat()\n callbackRef.current.onDragStart?.(e)\n }\n\n const dragHandler = (e: MarkerDragEvent) => {\n e.lngLat = marker.getLngLat()\n callbackRef.current.onDrag?.(e)\n }\n\n const dragEndHandler = (e: MarkerDragEvent) => {\n e.lngLat = marker.getLngLat()\n callbackRef.current.onDragEnd?.(e)\n }\n\n marker.on('dragstart', dragStartHandler)\n marker.on('drag', dragHandler)\n marker.on('dragend', dragEndHandler)\n\n marker.addTo(map.getMap())\n\n return () => {\n marker.getElement().removeEventListener('click', clickHandler)\n marker.off('dragstart', dragStartHandler)\n marker.off('drag', dragHandler)\n marker.off('dragend', dragEndHandler)\n marker.remove()\n }\n }, [])\n\n const {\n longitude,\n latitude,\n offset,\n style,\n draggable = false,\n popup = null,\n rotation = 0,\n rotationAlignment = 'auto',\n pitchAlignment = 'auto',\n className,\n } = props\n\n useEffect(() => {\n applyReactStyle(marker.getElement(), style)\n }, [style])\n\n useImperativeHandle(ref, () => marker, [])\n\n const prevClassNameRef = useRef(className)\n\n // Intentionally no dependency array - we need to update marker properties on every render\n // to ensure they reflect the latest props. This avoids stale prop issues and is safe\n // because the marker's setter methods are idempotent.\n useEffect(() => {\n if (marker.getLngLat().lng !== longitude || marker.getLngLat().lat !== latitude) {\n marker.setLngLat([longitude, latitude])\n }\n if (offset && !arePointsEqual(marker.getOffset(), offset)) {\n marker.setOffset(offset)\n }\n if (marker.isDraggable() !== draggable) {\n marker.setDraggable(draggable)\n }\n if (marker.getRotation() !== rotation) {\n marker.setRotation(rotation)\n }\n if (marker.getRotationAlignment() !== rotationAlignment) {\n marker.setRotationAlignment(rotationAlignment)\n }\n if (marker.getPitchAlignment() !== pitchAlignment) {\n marker.setPitchAlignment(pitchAlignment)\n }\n if (marker.getPopup() !== popup) {\n marker.setPopup(popup)\n }\n const classNameDiff = compareClassNames(prevClassNameRef.current, className)\n if (classNameDiff) {\n for (const c of classNameDiff) {\n marker.toggleClassName(c)\n }\n }\n prevClassNameRef.current = className\n })\n\n return createPortal(props.children, marker.getElement())\n })\n)\n","/** Compare two classNames string and return the difference */\nexport function compareClassNames(\n prevClassName: string | undefined,\n nextClassName: string | undefined\n): string[] | null {\n if (prevClassName === nextClassName) {\n return null\n }\n\n const prevClassList = getClassList(prevClassName)\n const nextClassList = getClassList(nextClassName)\n const diff: string[] = []\n\n for (const c of nextClassList) {\n if (!prevClassList.has(c)) {\n diff.push(c)\n }\n }\n for (const c of prevClassList) {\n if (!nextClassList.has(c)) {\n diff.push(c)\n }\n }\n return diff.length === 0 ? null : diff\n}\n\nfunction getClassList(className: string | undefined) {\n return new Set(className ? className.trim().split(/\\s+/) : [])\n}\n","/* global document */\nimport * as React from 'react'\nimport { createPortal } from 'react-dom'\nimport { useImperativeHandle, useEffect, useMemo, useContext, forwardRef, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\n\nimport type { Popup as PopupInstance, PopupOptions, MapMouseEventBase } from '../types/lib'\nimport type { PopupEvent } from '../types/events'\n\nimport { MapContext } from './map'\nimport { compareClassNames } from '../utils/compare-class-names'\n\nexport type PopupProps = PopupOptions & {\n /** Longitude of the anchor location */\n longitude: number\n /** Latitude of the anchor location */\n latitude: number\n\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n\n onOpen?: (e: PopupEvent) => void\n onClose?: (e: PopupEvent) => void\n children?: React.ReactNode\n}\n\nexport const Popup: React.FC<PopupProps> = memo(\n forwardRef((props: PopupProps, ref: React.Ref<PopupInstance>) => {\n const { map, mapLib } = useContext(MapContext)\n const container = useMemo(() => {\n return document.createElement('div')\n }, [])\n\n const popup: PopupInstance = useMemo(() => {\n const options = { ...props }\n const pp = new mapLib.Popup(options)\n pp.setLngLat([props.longitude, props.latitude])\n return pp\n }, [])\n\n useImperativeHandle(ref, () => popup, [])\n\n useEffect(() => {\n const onOpen = (e: MapMouseEventBase) => {\n props.onOpen?.(e as unknown as PopupEvent)\n }\n const onClose = (e: MapMouseEventBase) => {\n props.onClose?.(e as unknown as PopupEvent)\n }\n popup.on('open', onOpen)\n popup.on('close', onClose)\n popup.setDOMContent(container).addTo(map.getMap())\n\n return () => {\n // https://github.com/visgl/react-map-gl/issues/1825\n // onClose should not be fired if the popup is removed by unmounting\n // When using React strict mode, the component is mounted twice.\n // Firing the onClose callback here would be a false signal to remove the component.\n popup.off('open', onOpen)\n popup.off('close', onClose)\n if (popup.isOpen()) {\n popup.remove()\n }\n }\n }, [])\n\n useEffect(() => {\n applyReactStyle(popup.getElement(), props.style)\n }, [props.style])\n\n useEffect(() => {\n if (popup.isOpen()) {\n if (popup.getLngLat().lng !== props.longitude || popup.getLngLat().lat !== props.latitude) {\n popup.setLngLat([props.longitude, props.latitude])\n }\n }\n }, [props.longitude, props.latitude])\n\n useEffect(() => {\n if (popup.isOpen() && props.offset) {\n popup.setOffset(props.offset)\n }\n }, [props.offset])\n\n useEffect(() => {\n if (popup.isOpen() && props.maxWidth !== undefined) {\n popup.setMaxWidth(props.maxWidth)\n }\n }, [props.maxWidth])\n\n useEffect(() => {\n if (popup.isOpen() && props.className) {\n const currentClassName = popup.options.className || ''\n const classNameDiff = compareClassNames(currentClassName, props.className)\n if (classNameDiff) {\n for (const c of classNameDiff) {\n popup.toggleClassName(c)\n }\n }\n }\n }, [props.className])\n\n return createPortal(props.children, container)\n })\n)\n","/* global document */\nimport * as React from 'react'\nimport { useEffect, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type { ControlPosition, FullscreenControlOptions } from '../types/lib'\n\nexport type FullscreenControlProps = Omit<FullscreenControlOptions, 'container'> & {\n /** Id of the DOM element which should be made full screen. By default, the map container\n * element will be made full screen. */\n containerId?: string\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _FullscreenControl(props: FullscreenControlProps) {\n const ctrl = useControl(\n ({ mapLib }) =>\n new mapLib.FullscreenControl({\n container: props.containerId && document.getElementById(props.containerId),\n }),\n { position: props.position }\n )\n\n useEffect(() => {\n applyReactStyle(ctrl._controlContainer, props.style)\n }, [props.style])\n\n return null\n}\n\nexport const FullscreenControl: React.FC<FullscreenControlProps> = memo(_FullscreenControl)\n","import * as React from 'react'\nimport { useImperativeHandle, useRef, useEffect, forwardRef, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type {\n ControlPosition,\n GeolocateControl as GeolocateControlInstance,\n GeolocateControlOptions,\n} from '../types/lib'\nimport type { GeolocateEvent, GeolocateResultEvent, GeolocateErrorEvent } from '../types/events'\n\nexport type GeolocateControlProps = GeolocateControlOptions & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n\n /** Called on each Geolocation API position update that returned as success. */\n onGeolocate?: (e: GeolocateResultEvent) => void\n /** Called on each Geolocation API position update that returned as an error. */\n onError?: (e: GeolocateErrorEvent) => void\n /** Called on each Geolocation API position update that returned as success but user position\n * is out of map `maxBounds`. */\n onOutOfMaxBounds?: (e: GeolocateResultEvent) => void\n /** Called when the GeolocateControl changes to the active lock state. */\n onTrackUserLocationStart?: (e: GeolocateEvent) => void\n /** Called when the GeolocateControl changes to the background state. */\n onTrackUserLocationEnd?: (e: GeolocateEvent) => void\n}\n\nfunction _GeolocateControl(props: GeolocateControlProps, ref: React.Ref<GeolocateControlInstance>) {\n const thisRef = useRef({ props })\n\n const ctrl = useControl(\n ({ mapLib }) => {\n const gc = new mapLib.GeolocateControl(props)\n\n // Hack: fix GeolocateControl reuse\n // When using React strict mode, the component is mounted twice.\n // GeolocateControl's UI creation is asynchronous. Removing and adding it back causes the UI to be initialized twice.\n const setupUI = gc._setupUI\n gc._setupUI = () => {\n if (!gc._container.hasChildNodes()) {\n setupUI()\n }\n }\n\n gc.on('geolocate', e => {\n thisRef.current.props.onGeolocate?.(e as GeolocateResultEvent)\n })\n gc.on('error', e => {\n thisRef.current.props.onError?.(e as GeolocateErrorEvent)\n })\n gc.on('outofmaxbounds', e => {\n thisRef.current.props.onOutOfMaxBounds?.(e as GeolocateResultEvent)\n })\n gc.on('trackuserlocationstart', e => {\n thisRef.current.props.onTrackUserLocationStart?.(e as GeolocateEvent)\n })\n gc.on('trackuserlocationend', e => {\n thisRef.current.props.onTrackUserLocationEnd?.(e as GeolocateEvent)\n })\n\n return gc\n },\n { position: props.position }\n )\n\n thisRef.current.props = props\n\n useImperativeHandle(ref, () => ctrl, [])\n\n useEffect(() => {\n applyReactStyle(ctrl._container, props.style)\n }, [props.style])\n\n return null\n}\n\nexport const GeolocateControl: React.FC<GeolocateControlProps> = memo(forwardRef(_GeolocateControl))\n","import * as React from 'react'\nimport { useEffect, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type { ControlPosition, NavigationControlOptions } from '../types/lib'\n\nexport type NavigationControlProps = NavigationControlOptions & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _NavigationControl(props: NavigationControlProps) {\n const ctrl = useControl(({ mapLib }) => new mapLib.NavigationControl(props), {\n position: props.position,\n })\n\n useEffect(() => {\n applyReactStyle(ctrl._container, props.style)\n }, [props.style])\n\n return null\n}\n\nexport const NavigationControl: React.FC<NavigationControlProps> = memo(_NavigationControl)\n","import * as React from 'react'\nimport { useEffect, useRef, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type { ControlPosition, ScaleControlOptions } from '../types/lib'\n\nexport type ScaleControlProps = ScaleControlOptions & {\n // These props will be further constraint by OptionsT\n unit?: string\n maxWidth?: number\n\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _ScaleControl(props: ScaleControlProps) {\n const ctrl = useControl(({ mapLib }) => new mapLib.ScaleControl(props), {\n position: props.position,\n })\n const propsRef = useRef<ScaleControlProps>(props)\n\n const prevProps = propsRef.current\n propsRef.current = props\n\n const { style, maxWidth, unit } = props\n\n // Move prop updates to useEffect to avoid render-phase side effects\n useEffect(() => {\n if (maxWidth !== undefined && maxWidth !== prevProps.maxWidth) {\n ctrl.options.maxWidth = maxWidth\n }\n if (unit !== undefined && unit !== prevProps.unit) {\n ctrl.setUnit(unit)\n }\n }, [ctrl, maxWidth, unit, prevProps.maxWidth, prevProps.unit])\n\n useEffect(() => {\n applyReactStyle(ctrl._container, style)\n }, [ctrl, style])\n\n return null\n}\n\nexport const ScaleControl: React.FC<ScaleControlProps> = memo(_ScaleControl)\n","import * as React from 'react'\nimport { useEffect, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type { ControlPosition } from '../types/lib'\nimport type { TerrainSpecification } from '../types/style-spec'\n\nexport type TerrainControlProps = TerrainSpecification & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _TerrainControl(props: TerrainControlProps) {\n const ctrl = useControl(({ mapLib }) => new mapLib.TerrainControl(props), {\n position: props.position,\n })\n\n useEffect(() => {\n applyReactStyle(ctrl._container, props.style)\n }, [props.style])\n\n return null\n}\n\nexport const TerrainControl: React.FC<TerrainControlProps> = memo(_TerrainControl)\n","/**\n * @fileoverview Source component for adding data sources to a MapLibre GL map.\n *\n * Sources define the data that layers can render. This component supports all\n * MapLibre GL source types including GeoJSON, vector tiles, raster tiles. image. and video.\n *\n * @module components/source\n * @see {@link https://maplibre.org/maplibre-gl-js/docs/sources/}\n */\n\nimport * as React from 'react'\nimport {\n useContext,\n useEffect,\n useMemo,\n useState,\n useRef,\n cloneElement,\n memo,\n useId,\n forwardRef,\n useImperativeHandle,\n} from 'react'\nimport { MapContext } from './map'\nimport assert from '../utils/assert'\nimport { deepEqual } from '../utils/deep-equal'\n\nimport type {\n GeoJSONSourceImplementation,\n ImageSourceImplementation,\n AnySourceImplementation,\n MapInternalProperties,\n SourceWithOptionalMethods,\n LayerWithSource,\n} from '../types/internal'\nimport type { SourceSpecification } from '../types/style-spec'\nimport type { Map as MapInstance } from '../types/lib'\n\n/**\n * Props for the Source component.\n *\n * @typedef {Object} SourceProps\n * @property {string} [id] - Unique identifier for the source. If not provided. one will be generated automatically.\n * @property {React.ReactNode} [children] - Child Layer components that will use this source.\n * @extends {SourceSpecification}\n *\n * @example\n * ```tsx\n * // GeoJSON source with a layer\n * <Source id=\"my-data\" type=\"geojson\" data={geojsonData}>\n * <Layer id=\"points-layer\" type=\"circle\" paint={{ 'circle-radius': 8 }} />\n * </Source>\n *\n * // Vector tile source\n * <Source id=\"streets\" type=\"vector\" url=\"mapbox://streets-v11\" />\n *\n * // Raster source\n * <Source id=\"satellite\" type=\"raster\" tiles={['https://example.com/tiles/{z}/{x}/{y}.png']} tileSize={256} />\n * ```\n */\nexport type SourceProps = SourceSpecification & {\n /** Unique identifier for the source. If not provided. one will be generated automatically. */\n id?: string\n\n /** Child Layer components that will use this source. */\n children?: any\n}\n\n/**\n * Creates a new source on the map.\n *\n * @param {MapInstance} map - The MapLibre GL map instance\n * @param {string} id - Unique identifier for the source\n * @param {SourceProps} props - Source properties\n * @returns {AnySourceImplementation | null} The created source or null if style not loaded\n * @private\n */\nfunction createSource(\n map: MapInstance,\n id: string,\n props: SourceProps\n): AnySourceImplementation | null {\n const mapInternal = map as unknown as MapInternalProperties\n if (mapInternal.style && mapInternal.style._loaded) {\n const options = { ...props }\n delete options.id\n delete options.children\n map.addSource(id, options as SourceSpecification)\n return map.getSource(id)\n }\n return null\n}\n\n/**\n * Updates an existing source with new properties.\n *\n * Handles updates for different source types:\n * - GeoJSON sources: updates data via setData()\n * - Image sources: updates via updateImage()\n * - Other sources: uses optional setCoordinates. setUrl. or setTiles methods\n *\n * @param {AnySourceImplementation} source - The source to update\n * @param {SourceProps} props - New properties\n * @param {SourceProps} prevProps - Previous properties\n * @throws {Error} If source id or type changes\n * @private\n */\nfunction updateSource(\n source: AnySourceImplementation,\n props: SourceProps,\n prevProps: SourceProps\n): void {\n assert(props.id === prevProps.id, 'source id changed')\n assert(props.type === prevProps.type, 'source type changed')\n\n let changedKey = ''\n let changedKeyCount = 0\n\n for (const key in props) {\n if (key !== 'children' && key !== 'id' && !deepEqual(prevProps[key], props[key])) {\n changedKey = key\n changedKeyCount++\n }\n }\n\n if (!changedKeyCount) {\n return\n }\n\n const type = props.type\n\n if (type === 'geojson') {\n ;(source as GeoJSONSourceImplementation).setData(props.data)\n } else if (type === 'image') {\n ;(source as ImageSourceImplementation).updateImage({\n url: props.url,\n coordinates: props.coordinates,\n })\n } else {\n const sourceWithMethods = source as unknown as SourceWithOptionalMethods\n const propsWithOptional = props as Record<string, unknown>\n switch (changedKey) {\n case 'coordinates':\n sourceWithMethods.setCoordinates?.(propsWithOptional.coordinates)\n break\n case 'url':\n sourceWithMethods.setUrl?.(propsWithOptional.url as string)\n break\n case 'tiles':\n sourceWithMethods.setTiles?.(propsWithOptional.tiles as string[])\n break\n default:\n console.warn(`Unable to update <Source> prop: ${changedKey}`)\n }\n }\n}\n\n/**\n * Source component for adding data sources to a MapLibre GL map.\n *\n * Sources define the data that layers render. Supports all MapLibre GL source\n * types including GeoJSON. vector tiles. raster tiles. image. and video.\n *\n * @component\n * @example\n * ```tsx\n * // GeoJSON source with a layer\n * <Source id=\"my-data\" type=\"geojson\" data={geojsonData}>\n * <Layer id=\"points-layer\" type=\"circle\" paint={{ 'circle-radius': 8 }} />\n * </Source>\n *\n * // Vector tile source\n * <Source id=\"streets\" type=\"vector\" url=\"mapbox://streets-v11\" />\n *\n * // Raster source\n * <Source id=\"satellite\" type=\"raster\" tiles={['https://example.com/tiles/{z}/{x}/{y}.png']} tileSize={256} />\n *\n * // With ref forwarding\n * const sourceRef = useRef(null);\n * <Source ref={sourceRef} id=\"my-data\" type=\"geojson\" data={data}>\n * <Layer type=\"circle\" />\n * </Source>\n *\n * // Access source methods\n * useEffect(() => {\n * if (sourceRef.current) {\n * sourceRef.current.setData(newData);\n * }\n * }, [newData]);\n * ```\n */\nfunction _Source(props: SourceProps, ref: React.Ref<AnySourceImplementation | null>) {\n const map = useContext(MapContext).map.getMap()\n const propsRef = useRef(props)\n const sourceRef = useRef<AnySourceImplementation | null>(null)\n const [, setStyleLoaded] = useState(0)\n\n // Generate a stable ID once on mount\n // Note: props.id changes after mount will trigger an error in updateSource\n const generatedId = useId()\n const id = useMemo(\n () => props.id || `jsx-source-${generatedId.replace(/:/g, '-')}`,\n // Empty deps - id is set once on mount and should not change\n []\n )\n\n useEffect(() => {\n if (map) {\n /* global setTimeout */\n const forceUpdate = () => setTimeout(() => setStyleLoaded(version => version + 1), 0)\n map.on('styledata', forceUpdate)\n forceUpdate()\n\n return () => {\n map.off('styledata', forceUpdate)\n const mapInternal = map as unknown as MapInternalProperties\n if (mapInternal.style && mapInternal.style._loaded && map.getSource(id)) {\n // Parent effects are destroyed before child ones. see\n // https://github.com/facebook/react/issues/16728\n // Source can only be removed after all child layers are removed\n const allLayers = map.getStyle()?.layers\n if (allLayers) {\n for (const layer of allLayers) {\n const layerWithSource = layer as unknown as LayerWithSource\n if (layerWithSource.source === id) {\n map.removeLayer(layer.id)\n }\n }\n }\n map.removeSource(id)\n }\n }\n }\n return undefined\n }, [map])\n\n const mapInternal = map as unknown as MapInternalProperties\n let source = map && mapInternal.style && map.getSource(id)\n if (source) {\n updateSource(source, props, propsRef.current)\n } else {\n source = createSource(map, id, props)\n }\n\n // Update source ref for imperative handle\n sourceRef.current = source\n propsRef.current = props\n\n // Expose source instance via ref\n useImperativeHandle(ref, () => sourceRef.current, [source])\n\n return (\n (source &&\n React.Children.map(\n props.children,\n child =>\n child &&\n cloneElement(child, {\n source: id,\n })\n )) ||\n null\n )\n}\n\nexport const Source = memo(React.forwardRef(_Source))\n","export default function assert(condition: unknown, message: string) {\n if (!condition) {\n throw new Error(message)\n }\n}\n","/**\n * @fileoverview CanvasSource component for adding canvas-based data sources to a MapLibre GL map.\n *\n * Canvas sources allow rendering custom HTML canvas elements as map layers.\n * This is useful for dynamic, animated, or custom-rendered data overlays.\n *\n * @module components/canvas-source\n * @see {@link https://maplibre.org/maplibre-gl-js/docs/sources/}\n */\n\nimport * as React from 'react'\nimport { useContext, useEffect, useMemo, useRef, useState, memo } from 'react'\nimport { MapContext } from './map'\n\nimport type { Map as MapInstance } from '../types/lib'\nimport type { MapInternalProperties, SourceWithOptionalMethods } from '../types/internal'\n\n/**\n * Coordinates for the canvas corners [top-left, top-right, bottom-right, bottom-left]\n */\nexport type CanvasCoordinates = [\n [number, number], // top-left [lng, lat]\n [number, number], // top-right [lng, lat]\n [number, number], // bottom-right [lng, lat]\n [number, number], // bottom-left [lng, lat]\n]\n\n/**\n * Props for the CanvasSource component.\n *\n * @typedef {Object} CanvasSourceProps\n * @property {string} [id] - Unique identifier for the source.\n * @property {CanvasCoordinates} coordinates - Corner coordinates of the canvas.\n * @property {HTMLCanvasElement} canvas - The canvas element to render.\n * @property {boolean} [animate] - Whether to animate the canvas (re-render on each frame).\n * @property {number} [width] - Width of the canvas context.\n * @property {number} [height] - Height of the canvas context.\n * @property {React.ReactNode} [children] - Child Layer components.\n *\n * @example\n * ```tsx\n * // Canvas source with dynamic content\n * const canvasRef = useRef<HTMLCanvasElement>(null);\n * const [canvasEl, setCanvasEl] = useState<HTMLCanvasElement | null>(null);\n *\n * useEffect(() => {\n * const canvas = canvasRef.current;\n * if (!canvas) return;\n * const ctx = canvas.getContext('2d');\n * if (ctx) {\n * ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';\n * ctx.fillRect(0, 0, 100, 100);\n * }\n * setCanvasEl(canvas);\n * }, []);\n *\n * {canvasEl && (\n * <CanvasSource\n * id=\"canvas-source\"\n * coordinates={[\n * [90.39, 23.83], // top-left\n * [90.41, 23.83], // top-right\n * [90.41, 23.81], // bottom-right\n * [90.39, 23.81] // bottom-left\n * ]}\n * canvas={canvasEl}\n * >\n * <Layer type=\"raster\" paint={{ 'raster-opacity': 0.8 }} />\n * </CanvasSource>\n * )}\n * ```\n */\nexport type CanvasSourceProps = {\n /** Unique identifier for the source */\n id?: string\n /** Corner coordinates of the canvas [top-left, top-right, bottom-right, bottom-left] */\n coordinates: CanvasCoordinates\n /** The canvas element to render */\n canvas: HTMLCanvasElement\n /** Whether to animate the canvas (re-render on each frame) */\n animate?: boolean\n /** Width of the canvas context */\n width?: number\n /** Height of the canvas context */\n height?: number\n /** Child Layer components */\n children?: React.ReactNode\n}\n\n/**\n * CanvasSource component for adding canvas-based data sources to a MapLibre GL map.\n *\n * Canvas sources allow rendering custom HTML canvas elements as map layers.\n * This is useful for dynamic, animated, or custom-rendered data overlays.\n *\n * @component\n * @example\n * ```tsx\n * import { Map, CanvasSource, Layer } from 'react-bkoi-gl';\n * import \"react-bkoi-gl/styles\";\n * import { useRef, useEffect, useState } from 'react';\n *\n * function CanvasExample() {\n * const canvasRef = useRef<HTMLCanvasElement>(null);\n * const [canvasEl, setCanvasEl] = useState<HTMLCanvasElement | null>(null);\n *\n * useEffect(() => {\n * const canvas = canvasRef.current;\n * if (!canvas) return;\n *\n * const ctx = canvas.getContext('2d');\n * if (ctx) {\n * ctx.fillStyle = 'rgba(0, 100, 255, 0.5)';\n * ctx.fillRect(0, 0, 256, 256);\n * ctx.fillStyle = 'rgba(255, 0, 0, 0.8)';\n * ctx.beginPath();\n * ctx.arc(128, 128, 50, 0, 2 * Math.PI);\n * ctx.fill();\n * }\n *\n * setCanvasEl(canvas);\n * }, []);\n *\n * return (\n * <Map\n * mapStyle={`https://map.barikoi.com/styles/osm-liberty/style.json?key=${API_KEY}`}\n * initialViewState={{\n * longitude: 90.3938,\n * latitude: 23.8216,\n * zoom: 12\n * }}\n * >\n * <canvas ref={canvasRef} width={256} height={256} style={{ display: 'none' }} />\n * {canvasEl && (\n * <CanvasSource\n * id=\"my-canvas\"\n * coordinates={[\n * [90.38, 23.83],\n * [90.41, 23.83],\n * [90.41, 23.81],\n * [90.38, 23.81]\n * ]}\n * canvas={canvasEl}\n * >\n * <Layer type=\"raster\" paint={{ 'raster-opacity': 0.8 }} />\n * </CanvasSource>\n * )}\n * </Map>\n * );\n * }\n * ```\n */\nfunction _CanvasSource(props: CanvasSourceProps) {\n const map = useContext(MapContext).map.getMap()\n const propsRef = useRef(props)\n\n const id = useMemo(() => props.id || `canvas-source-${Date.now()}`, [props.id])\n\n useEffect(() => {\n if (!map) return undefined\n\n const mapInternal = map as unknown as MapInternalProperties\n let source: maplibregl.CanvasSource | null = null\n\n const addSource = () => {\n if (!mapInternal.style || !mapInternal.style._loaded) return\n if (map.getSource(id)) return\n\n const { coordinates, canvas, animate } = props\n\n // Add canvas source\n ;(map as any).addSource(id, {\n type: 'canvas',\n coordinates,\n canvas,\n animate: animate || false,\n })\n\n source = map.getSource(id) as maplibregl.CanvasSource\n }\n\n const updateSource = () => {\n if (!source) return\n\n const { coordinates, canvas } = props\n const prevProps = propsRef.current\n\n // Update coordinates if changed\n if (JSON.stringify(coordinates) !== JSON.stringify(prevProps.coordinates)) {\n const sourceWithMethods = source as unknown as SourceWithOptionalMethods\n sourceWithMethods.setCoordinates?.(coordinates)\n }\n }\n\n // Wait for style to load\n if (mapInternal.style && mapInternal.style._loaded) {\n addSource()\n } else {\n map.once('styledata', addSource)\n }\n\n return () => {\n map.off('styledata', addSource)\n const mapInternalForCleanup = map as unknown as MapInternalProperties\n if (mapInternalForCleanup.style && mapInternalForCleanup.style._loaded && map.getSource(id)) {\n // Remove all layers using this source first\n const allLayers = map.getStyle()?.layers\n if (allLayers) {\n for (const layer of allLayers) {\n if ((layer as any).source === id) {\n map.removeLayer(layer.id)\n }\n }\n }\n map.removeSource(id)\n }\n }\n }, [map, id])\n\n // Update source when props change\n useEffect(() => {\n if (!map) return\n\n const source = map.getSource(id) as maplibregl.CanvasSource | undefined\n if (!source) return\n\n const { coordinates } = props\n const prevProps = propsRef.current\n\n // Update coordinates if changed\n if (JSON.stringify(coordinates) !== JSON.stringify(prevProps.coordinates)) {\n const sourceWithMethods = source as unknown as SourceWithOptionalMethods\n sourceWithMethods.setCoordinates?.(coordinates)\n }\n\n propsRef.current = props\n }, [map, id, props.coordinates, props.canvas])\n\n // Render children with source id\n if (!map) return null\n\n const mapInternal = map as unknown as MapInternalProperties\n if (!mapInternal.style || !mapInternal.style._loaded || !map.getSource(id)) {\n return null\n }\n\n // Clone children and pass source id\n return (\n (props.children &&\n React.Children.map(\n props.children,\n child =>\n child &&\n React.cloneElement(child as React.ReactElement, {\n source: id,\n })\n )) ||\n null\n )\n}\n\nexport const CanvasSource = memo<CanvasSourceProps>(_CanvasSource)\n","/**\n * @fileoverview Layer component for adding visual layers to a MapLibre GL map.\n *\n * Layers define how data from sources is rendered on the map. This component supports\n * all MapLibre GL layer types including fill, line, circle, symbol. raster. and more.\n *\n * @module components/layer\n * @see {@link https://maplibre.org/maplibre-gl-js/docs/layers/}\n */\n\nimport { useContext, useEffect, useMemo, useState, useRef, memo, useId } from 'react'\nimport { MapContext } from './map'\nimport assert from '../utils/assert'\nimport { deepEqual } from '../utils/deep-equal'\n\nimport type { FilterSpecification, MapLayerMouseEvent } from 'maplibre-gl'\n\nimport type { Map as MapInstance, CustomLayerInterface } from '../types/lib'\nimport type { LayerSpecification } from '../types/style-spec'\nimport type { MapInternalProperties } from '../types/internal'\n\n/**\n * Type for layer with filter property (not all layer types have filter)\n * @private\n */\ntype LayerWithFilter = {\n filter?: FilterSpecification | null\n layout?: Record<string, unknown>\n paint?: Record<string, unknown>\n minzoom?: number\n maxzoom?: number\n beforeId?: string\n type?: string\n id?: string\n source?: string\n}\n\n/**\n * Event handlers for layer interactions\n * @private\n */\ntype LayerEventHandlers = {\n onClick?: (e: MapLayerMouseEvent) => void\n onMouseEnter?: (e: MapLayerMouseEvent) => void\n onMouseLeave?: (e: MapLayerMouseEvent) => void\n onMouseMove?: (e: MapLayerMouseEvent) => void\n onMouseDown?: (e: MapLayerMouseEvent) => void\n onMouseUp?: (e: MapLayerMouseEvent) => void\n onContextMenu?: (e: MapLayerMouseEvent) => void\n onDoubleClick?: (e: MapLayerMouseEvent) => void\n}\n\n/**\n * Utility type to make id optional in layer specification.\n * @private\n */\ntype OptionalId<T> = T extends { id: string } ? Omit<T, 'id'> & { id?: string } : T\n\n/**\n * Utility type to make source optional in layer specification.\n * @private\n */\ntype OptionalSource<T> = T extends { source: string } ? Omit<T, 'source'> & { source?: string } : T\n\n/**\n * Props for the Layer component.\n *\n * @typedef {Object} LayerProps\n * @property {string} [id] - Unique identifier for the layer. If not provided, one will be generated automatically.\n * @property {string} [source] - The source ID this layer should use (inherited from parent Source component).\n * @property {string} [beforeId] - If set, the layer will be inserted before the specified layer.\n * @property {function} [onClick] - Called when the layer is clicked.\n * @property {function} [onMouseEnter] - Called when the mouse enters the layer.\n * @property {function} [onMouseLeave] - Called when the mouse leaves the layer.\n * @property {function} [onMouseMove] - Called when the mouse moves over the layer.\n * @property {function} [onMouseDown] - Called when mouse button is pressed on the layer.\n * @property {function} [onMouseUp] - Called when mouse button is released on the layer.\n * @property {function} [onContextMenu] - Called on right-click context menu.\n * @property {function} [onDoubleClick] - Called on double click.\n * @extends {LayerSpecification | CustomLayerInterface}\n *\n * @example\n * ```tsx\n * // Circle layer with paint properties\n * <Layer\n * id=\"points-layer\"\n * type=\"circle\"\n * paint={{\n * 'circle-radius': 8,\n * 'circle-color': '#007cbf'\n * }}\n * />\n *\n * // Line layer with filter\n * <Layer\n * id=\"roads-layer\"\n * type=\"line\"\n * source=\"streets\"\n * source-layer=\"road\"\n * filter={['==', ['get', 'type'], 'primary']}\n * paint={{ 'line-width': 2 }}\n * />\n *\n * // Interactive layer with events\n * <Layer\n * id=\"interactive-layer\"\n * type=\"fill\"\n * paint={{ 'fill-color': '#088' }}\n * onClick={(e) => console.log('Clicked:', e.features)}\n * onMouseEnter={(e) => console.log('Hover:', e.features)}\n * onMouseLeave={() => console.log('Left layer')}\n * />\n *\n * // Custom layer\n * <Layer\n * type=\"custom\"\n * renderingMode=\"2d\"\n * onAdd={(map) => { ... }}\n * render={(gl, matrix) => { ... }}\n * />\n * ```\n */\nexport type LayerProps = (OptionalSource<OptionalId<LayerSpecification>> | CustomLayerInterface) & {\n /** If set, the layer will be inserted before the specified layer */\n beforeId?: string\n /** Called when the layer is clicked */\n onClick?: (e: MapLayerMouseEvent) => void\n /** Called when the mouse enters the layer */\n onMouseEnter?: (e: MapLayerMouseEvent) => void\n /** Called when the mouse leaves the layer */\n onMouseLeave?: () => void\n /** Called when the mouse moves over the layer */\n onMouseMove?: (e: MapLayerMouseEvent) => void\n /** Called when mouse button is pressed on the layer */\n onMouseDown?: (e: MapLayerMouseEvent) => void\n /** Called when mouse button is released on the layer */\n onMouseUp?: (e: MapLayerMouseEvent) => void\n /** Called on right-click context menu */\n onContextMenu?: (e: MapLayerMouseEvent) => void\n /** Called on double click */\n onDoubleClick?: (e: MapLayerMouseEvent) => void\n}\n\n/**\n * Updates an existing layer with new properties.\n *\n * Handles updates for:\n * - Layout properties via setLayoutProperty()\n * - Paint properties via setPaintProperty()\n * - Filter via setFilter()\n * - Zoom range via setLayerZoomRange()\n * - Layer order via moveLayer()\n *\n * @param {MapInstance} map - The MapLibre GL map instance\n * @param {string} id - Unique identifier for the layer\n * @param {LayerProps} props - New properties\n * @param {LayerProps} prevProps - Previous properties\n * @throws {Error} If layer id or type changes\n * @private\n */\nfunction updateLayer(map: MapInstance, id: string, props: LayerProps, prevProps: LayerProps): void {\n assert(props.id === prevProps.id, 'layer id changed')\n assert(props.type === prevProps.type, 'layer type changed')\n\n if (props.type === 'custom' || prevProps.type === 'custom') {\n return\n }\n\n const propsWithFilter = props as unknown as LayerWithFilter\n const prevPropsWithFilter = prevProps as unknown as LayerWithFilter\n const { layout = {}, paint = {}, filter, minzoom, maxzoom, beforeId } = propsWithFilter\n\n if (beforeId !== prevPropsWithFilter.beforeId) {\n map.moveLayer(id, beforeId)\n }\n if (layout !== prevPropsWithFilter.layout) {\n const prevLayout = prevPropsWithFilter.layout || {}\n for (const key in layout) {\n if (!deepEqual(layout[key], prevLayout[key])) {\n map.setLayoutProperty(id, key, layout[key])\n }\n }\n for (const key in prevLayout) {\n if (!Object.prototype.hasOwnProperty.call(layout, key)) {\n map.setLayoutProperty(id, key, undefined)\n }\n }\n }\n if (paint !== prevPropsWithFilter.paint) {\n const prevPaint = prevPropsWithFilter.paint || {}\n for (const key in paint) {\n if (!deepEqual(paint[key], prevPaint[key])) {\n map.setPaintProperty(id, key, paint[key])\n }\n }\n for (const key in prevPaint) {\n if (!Object.prototype.hasOwnProperty.call(paint, key)) {\n map.setPaintProperty(id, key, undefined)\n }\n }\n }\n\n if (!deepEqual(filter, prevPropsWithFilter.filter)) {\n map.setFilter(id, filter ?? null)\n }\n if (minzoom !== prevPropsWithFilter.minzoom || maxzoom !== prevPropsWithFilter.maxzoom) {\n map.setLayerZoomRange(id, minzoom, maxzoom)\n }\n}\n\n/**\n * Creates a new layer on the map.\n *\n * @param {MapInstance} map - The MapLibre GL map instance\n * @param {string} id - Unique identifier for the layer\n * @param {LayerProps} props - Layer properties\n * @private\n */\nfunction createLayer(map: MapInstance, id: string, props: LayerProps): void {\n const mapInternal = map as unknown as MapInternalProperties\n if (\n mapInternal.style &&\n mapInternal.style._loaded &&\n (!('source' in props) || map.getSource(props.source as string))\n ) {\n const options: LayerProps = { ...props, id }\n delete options.beforeId\n\n map.addLayer(options as LayerSpecification, props.beforeId)\n }\n}\n\n/**\n * Layer component for adding visual layers to a MapLibre GL map.\n *\n * Layers define how data from sources is rendered on the map. Supports all\n * MapLibre GL layer types including fill, line, circle, symbol, raster,\n * hillshade, heatmap, and custom layers.\n *\n * Must be a child of a Source component (for data layers) or used standalone\n * with a source prop for pre-existing sources.\n *\n * @component\n * @example\n * ```tsx\n * // Circle layer with paint properties\n * <Layer\n * id=\"points-layer\"\n * type=\"circle\"\n * paint={{\n * 'circle-radius': 8,\n * 'circle-color': '#007cbf'\n * }}\n * />\n *\n * // Line layer with filter\n * <Layer\n * id=\"roads-layer\"\n * type=\"line\"\n * source=\"streets\"\n * source-layer=\"road\"\n * filter={['==', ['get', 'type'], 'primary']}\n * paint={{ 'line-width': 2 }}\n * />\n *\n * // Inside a Source component\n * <Source id=\"geojson\" type=\"geojson\" data={data}>\n * <Layer type=\"circle\" paint={{ 'circle-radius': 6 }} />\n * </Source>\n * ```\n */\nfunction _Layer(props: LayerProps) {\n const map = useContext(MapContext).map.getMap()\n const propsRef = useRef(props)\n const [, setStyleLoaded] = useState(0)\n\n // Generate a stable ID once on mount\n // Note: props.id changes after mount will trigger an error in updateLayer\n const generatedId = useId()\n const id = useMemo(\n () => props.id || `jsx-layer-${generatedId.replace(/:/g, '-')}`,\n // Empty deps - id is set once on mount and should not change\n []\n )\n\n // Extract event handlers\n const {\n onClick,\n onMouseEnter,\n onMouseLeave,\n onMouseMove,\n onMouseDown,\n onMouseUp,\n onContextMenu,\n onDoubleClick,\n } = props\n\n // Store callbacks in refs to avoid re-registering events\n const callbacksRef = useRef({\n onClick,\n onMouseEnter,\n onMouseLeave,\n onMouseMove,\n onMouseDown,\n onMouseUp,\n onContextMenu,\n onDoubleClick,\n })\n\n // Update refs when callbacks change\n useEffect(() => {\n callbacksRef.current = {\n onClick,\n onMouseEnter,\n onMouseLeave,\n onMouseMove,\n onMouseDown,\n onMouseUp,\n onContextMenu,\n onDoubleClick,\n }\n }, [\n onClick,\n onMouseEnter,\n onMouseLeave,\n onMouseMove,\n onMouseDown,\n onMouseUp,\n onContextMenu,\n onDoubleClick,\n ])\n\n useEffect(() => {\n if (map) {\n const forceUpdate = () => setStyleLoaded(version => version + 1)\n map.on('styledata', forceUpdate)\n forceUpdate()\n\n return () => {\n map.off('styledata', forceUpdate)\n const mapInternal = map as unknown as MapInternalProperties\n if (mapInternal.style && mapInternal.style._loaded && map.getLayer(id)) {\n map.removeLayer(id)\n }\n }\n }\n return undefined\n }, [map])\n\n // Register layer event handlers\n useEffect(() => {\n if (!map) return undefined\n\n const hasEventHandler =\n onClick ||\n onMouseEnter ||\n onMouseLeave ||\n onMouseMove ||\n onMouseDown ||\n onMouseUp ||\n onContextMenu ||\n onDoubleClick\n\n if (!hasEventHandler) return undefined\n\n // Event handlers\n const handleClick = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onClick?.(e)\n }\n\n const handleMouseEnter = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onMouseEnter?.(e)\n // Change cursor to pointer\n if (callbacksRef.current.onClick) {\n map.getCanvas().style.cursor = 'pointer'\n }\n }\n\n const handleMouseLeave = () => {\n callbacksRef.current.onMouseLeave?.()\n // Reset cursor\n map.getCanvas().style.cursor = ''\n }\n\n const handleMouseMove = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onMouseMove?.(e)\n }\n\n const handleMouseDown = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onMouseDown?.(e)\n }\n\n const handleMouseUp = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onMouseUp?.(e)\n }\n\n const handleContextMenu = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onContextMenu?.(e)\n }\n\n const handleDoubleClick = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onDoubleClick?.(e)\n }\n\n // Register events\n if (onClick) map.on('click', id, handleClick)\n if (onMouseEnter) map.on('mouseenter', id, handleMouseEnter)\n if (onMouseLeave) map.on('mouseleave', id, handleMouseLeave)\n if (onMouseMove) map.on('mousemove', id, handleMouseMove)\n if (onMouseDown) map.on('mousedown', id, handleMouseDown)\n if (onMouseUp) map.on('mouseup', id, handleMouseUp)\n if (onContextMenu) map.on('contextmenu', id, handleContextMenu)\n if (onDoubleClick) map.on('dblclick', id, handleDoubleClick)\n\n // Cleanup\n return () => {\n if (onClick) map.off('click', id, handleClick)\n if (onMouseEnter) map.off('mouseenter', id, handleMouseEnter)\n if (onMouseLeave) map.off('mouseleave', id, handleMouseLeave)\n if (onMouseMove) map.off('mousemove', id, handleMouseMove)\n if (onMouseDown) map.off('mousedown', id, handleMouseDown)\n if (onMouseUp) map.off('mouseup', id, handleMouseUp)\n if (onContextMenu) map.off('contextmenu', id, handleContextMenu)\n if (onDoubleClick) map.off('dblclick', id, handleDoubleClick)\n }\n }, [\n map,\n id,\n onClick,\n onMouseEnter,\n onMouseLeave,\n onMouseMove,\n onMouseDown,\n onMouseUp,\n onContextMenu,\n onDoubleClick,\n ])\n\n const mapInternal = map as unknown as MapInternalProperties\n const layer = map && mapInternal.style && map.getLayer(id)\n if (layer) {\n try {\n updateLayer(map, id, props, propsRef.current)\n } catch (error) {\n console.warn(error)\n }\n } else {\n createLayer(map, id, props)\n }\n\n // Store last rendered props\n propsRef.current = props\n\n return null\n}\n\nexport const Layer = memo(_Layer)\n","import * as React from 'react'\nimport { useEffect, useMemo, memo, useRef, useState, useContext } from 'react'\nimport MapboxDraw from 'maplibre-gl-draw'\nimport { MapContext } from './map'\n\nimport type { ControlPosition, IControl, Map as MapInstance } from '../types/lib'\n\n/**\n * Draw event types\n */\nexport interface DrawEvent {\n type: string\n features?: GeoJSON.Feature<GeoJSON.Geometry>[]\n featureIds?: string[]\n mode?: string\n originalEvent?: unknown\n}\n\n/**\n * Draw control options - extends maplibre-gl-draw options\n */\nexport interface DrawControlOptions {\n /** Whether controls are displayed by default */\n displayControlsDefault?: boolean\n /** Control configuration */\n controls?: {\n point?: boolean\n line_string?: boolean\n polygon?: boolean\n trash?: boolean\n combine_features?: boolean\n uncombine_features?: boolean\n }\n /** Custom styles for draw layers */\n styles?: unknown[]\n /** Available modes */\n modes?: Record<string, unknown>\n /** Default mode */\n defaultMode?: string\n}\n\nexport type DrawControlProps = DrawControlOptions & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n /** Callback fired when a feature is created */\n onDrawCreate?: (e: DrawEvent) => void\n /** Callback fired when a feature is deleted */\n onDrawDelete?: (e: DrawEvent) => void\n /** Callback fired when a feature is updated */\n onDrawUpdate?: (e: DrawEvent) => void\n /** Callback fired when the selection changes */\n onDrawSelectionChange?: (e: DrawEvent) => void\n /** Callback fired when the draw mode changes */\n onDrawModeChange?: (e: DrawEvent) => void\n /** Callback fired when features are combined */\n onDrawCombine?: (e: DrawEvent) => void\n /** Callback fired when features are uncombined */\n onDrawUncombine?: (e: DrawEvent) => void\n /** Callback fired when rendering */\n onDrawRender?: (e: DrawEvent) => void\n}\n\n/**\n * Default draw options - enables polygon and trash controls\n */\nconst defaultDrawOptions: DrawControlOptions = {\n displayControlsDefault: false,\n controls: {\n polygon: true,\n trash: true,\n },\n}\n\nfunction _DrawControl(props: DrawControlProps) {\n const {\n position,\n style,\n onDrawCreate,\n onDrawDelete,\n onDrawUpdate,\n onDrawSelectionChange,\n onDrawModeChange,\n onDrawCombine,\n onDrawUncombine,\n onDrawRender,\n ...drawOptions\n } = props\n\n const context = useContext(MapContext)\n\n if (!context) {\n throw new Error('DrawControl must be used within a Map component')\n }\n\n // Deep merge user options with defaults to preserve nested object properties\n const options = useMemo<DrawControlOptions>(\n () => ({\n ...defaultDrawOptions,\n ...drawOptions,\n controls: {\n ...defaultDrawOptions.controls,\n ...drawOptions.controls,\n },\n }),\n [\n drawOptions.displayControlsDefault,\n drawOptions.controls,\n drawOptions.styles,\n drawOptions.modes,\n drawOptions.defaultMode,\n ]\n )\n\n // Create a stable key for the options to detect changes\n const optionsKey = useMemo(() => JSON.stringify(options), [options])\n\n // Track callbacks in refs to avoid recreating the control for callback changes\n const callbacksRef = useRef({\n onDrawCreate,\n onDrawDelete,\n onDrawUpdate,\n onDrawSelectionChange,\n onDrawModeChange,\n onDrawCombine,\n onDrawUncombine,\n onDrawRender,\n })\n\n useEffect(() => {\n callbacksRef.current = {\n onDrawCreate,\n onDrawDelete,\n onDrawUpdate,\n onDrawSelectionChange,\n onDrawModeChange,\n onDrawCombine,\n onDrawUncombine,\n onDrawRender,\n }\n }, [\n onDrawCreate,\n onDrawDelete,\n onDrawUpdate,\n onDrawSelectionChange,\n onDrawModeChange,\n onDrawCombine,\n onDrawUncombine,\n onDrawRender,\n ])\n\n // Store control reference\n const ctrlRef = useRef<(IControl & { getMode: () => string }) | null>(null)\n const listenersRef = useRef<{\n handleCreate?: (e: DrawEvent) => void\n handleUpdate?: (e: DrawEvent) => void\n handleDelete?: (e: DrawEvent) => void\n handleSelectionChange?: (e: DrawEvent) => void\n handleModeChange?: (e: DrawEvent) => void\n handleCombine?: (e: DrawEvent) => void\n handleUncombine?: (e: DrawEvent) => void\n handleRender?: (e: DrawEvent) => void\n }>({})\n\n useEffect(() => {\n const { map } = context\n if (!map) return\n\n const mapInstance = map.getMap() as MapInstance\n if (!mapInstance) return\n\n const DrawClass = MapboxDraw as typeof MapboxDraw & {\n new (options: DrawControlOptions): IControl & { getMode: () => string }\n }\n\n // Helper to reset cursor when not in drawing mode\n const resetCursorIfNeeded = () => {\n if (ctrlRef.current) {\n const currentMode = ctrlRef.current.getMode()\n if (currentMode === 'simple_select') {\n mapInstance.getCanvas().style.cursor = ''\n }\n }\n }\n\n // Event handlers\n const handleCreate = (e: DrawEvent) => {\n resetCursorIfNeeded()\n callbacksRef.current.onDrawCreate?.(e)\n }\n\n const handleUpdate = (e: DrawEvent) => {\n resetCursorIfNeeded()\n callbacksRef.current.onDrawUpdate?.(e)\n }\n\n const handleDelete = (e: DrawEvent) => {\n resetCursorIfNeeded()\n callbacksRef.current.onDrawDelete?.(e)\n }\n\n const handleSelectionChange = (e: DrawEvent) => {\n resetCursorIfNeeded()\n callbacksRef.current.onDrawSelectionChange?.(e)\n }\n\n const handleModeChange = (e: DrawEvent) => {\n resetCursorIfNeeded()\n callbacksRef.current.onDrawModeChange?.(e)\n }\n\n const handleCombine = (e: DrawEvent) => {\n callbacksRef.current.onDrawCombine?.(e)\n }\n\n const handleUncombine = (e: DrawEvent) => {\n callbacksRef.current.onDrawUncombine?.(e)\n }\n\n const handleRender = (e: DrawEvent) => {\n callbacksRef.current.onDrawRender?.(e)\n }\n\n // Create new control\n const ctrl = new DrawClass(options)\n ctrlRef.current = ctrl\n\n // Add control to map\n map.addControl(ctrl, position)\n\n // Store listeners for cleanup\n listenersRef.current = {\n handleCreate,\n handleUpdate,\n handleDelete,\n handleSelectionChange,\n handleModeChange,\n handleCombine,\n handleUncombine,\n handleRender,\n }\n\n // Add event listeners\n mapInstance.on('draw.create', handleCreate)\n mapInstance.on('draw.update', handleUpdate)\n mapInstance.on('draw.delete', handleDelete)\n mapInstance.on('draw.selectionchange', handleSelectionChange)\n mapInstance.on('draw.modechange', handleModeChange)\n mapInstance.on('draw.combine', handleCombine)\n mapInstance.on('draw.uncombine', handleUncombine)\n mapInstance.on('draw.render', handleRender)\n\n // Cleanup function\n return () => {\n // Remove event listeners\n if (listenersRef.current.handleCreate) {\n mapInstance.off('draw.create', listenersRef.current.handleCreate)\n }\n if (listenersRef.current.handleUpdate) {\n mapInstance.off('draw.update', listenersRef.current.handleUpdate)\n }\n if (listenersRef.current.handleDelete) {\n mapInstance.off('draw.delete', listenersRef.current.handleDelete)\n }\n if (listenersRef.current.handleSelectionChange) {\n mapInstance.off('draw.selectionchange', listenersRef.current.handleSelectionChange)\n }\n if (listenersRef.current.handleModeChange) {\n mapInstance.off('draw.modechange', listenersRef.current.handleModeChange)\n }\n if (listenersRef.current.handleCombine) {\n mapInstance.off('draw.combine', listenersRef.current.handleCombine)\n }\n if (listenersRef.current.handleUncombine) {\n mapInstance.off('draw.uncombine', listenersRef.current.handleUncombine)\n }\n if (listenersRef.current.handleRender) {\n mapInstance.off('draw.render', listenersRef.current.handleRender)\n }\n\n // Remove control from map\n if (ctrlRef.current && map.hasControl(ctrlRef.current)) {\n map.removeControl(ctrlRef.current)\n }\n ctrlRef.current = null\n }\n }, [context, optionsKey, position])\n\n return null\n}\n\nexport const DrawControl = memo(_DrawControl)\n","/**\n * @fileoverview GlobeControl component for switching between 3D globe and 2D map views.\n *\n * Provides a control button to toggle between mercator (2D flat map) and\n * globe (3D) projections in MapLibre GL 3.x+.\n *\n * @module components/globe-control\n * @see {@link https://maplibre.org/maplibre-gl-js/docs/layers/}\n */\n\nimport { useEffect, memo, useRef } from 'react'\nimport { useControl } from './use-control'\n\nimport type { ControlPosition, IControl, Map as MapInstance } from '../types/lib'\n\n/**\n * Options for the GlobeControl\n */\nexport interface GlobeControlOptions {\n /** Custom button element */\n buttonElement?: HTMLElement\n /** Custom button class name */\n buttonClassName?: string\n /** Button title/tooltip text */\n buttonTitle?: string\n /** Custom CSS for the button */\n buttonStyle?: React.CSSProperties\n}\n\nexport type GlobeControlProps = GlobeControlOptions & {\n /** Position of the control on the map */\n position?: ControlPosition\n /** Called when projection changes */\n onProjectionChange?: (isGlobe: boolean) => void\n}\n\n/**\n * Default button SVG icons\n */\nconst GLOBE_SVG = `<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" stroke=\"currentColor\" stroke-width=\"2\">\n <circle cx=\"12\" cy=\"12\" r=\"9\" fill=\"none\"/>\n <path d=\"M12 21a9 9-9 0 0-9 9-9 0 0 9h0c2.2a8.2 2.3 5.1 5.8-5.5c-.4-.4-.5-.9-.5-1.5v-1.3c0-2.3 1.8-4.2 4-4.5V5.5c-1.8.5-3.5 2-4.5 2.8 0 5.2 2.3 5.2 5 0z\"/>\n <path d=\"M12 3c-2.8 0-5.2 2.3-5.2 5h2c0-1.5.1-1.1.5-1.5L5.8 9 2.3 5.1 8.2 2c.4 0 .9-.5 1.5-.5h1.3c2.3 0 4.2-1.8 4.5-4h-2c0 1.5-1.8 3.5-4 4.5V21c2.8 0 5.2-2.3 5.2-5h-2c0 1.5-.1 1.1-.5 1.5L18.2 15 14.8l2.7-5.1c-.4 0-.9.5-1.5.5h-1.3c-2.3 0-4.2 1.8-4.5 4h2c0-1.5 1.8-3.5 4-4.5V3z\"/>\n</svg>`\n\nconst MAP_SVG = `<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" stroke=\"currentColor\" stroke-width=\"2\">\n <rect x=\"3\" y=\"3\" width=\"18\" height=\"18\" rx=\"2\" fill=\"none\"/>\n <path d=\"M3 9h18M3 15h18M9 3v18M15 3v18\"/>\n</svg>`\n\n/**\n * GlobeControlImpl class implementing IControl interface\n */\nclass GlobeControlImpl implements IControl {\n private _container: HTMLDivElement\n private _button: HTMLButtonElement\n private _map: MapInstance | null = null\n private _isGlobe: boolean = false\n private _options: GlobeControlOptions\n private _onProjectionChange?: (isGlobe: boolean) => void\n\n constructor(\n options: GlobeControlOptions,\n callbacks: {\n onProjectionChange?: (isGlobe: boolean) => void\n }\n ) {\n this._options = options\n this._onProjectionChange = callbacks.onProjectionChange\n this._container = document.createElement('div')\n this._container.className = 'maplibregl-ctrl maplibregl-ctrl-group'\n this._button = this._createButton()\n this._container.appendChild(this._button)\n }\n\n private _createButton(): HTMLButtonElement {\n const button =\n (this._options.buttonElement as HTMLButtonElement) || document.createElement('button')\n\n if (!this._options.buttonElement) {\n button.className = this._options.buttonClassName || 'maplibregl-ctrl-globe'\n button.type = 'button'\n button.title = this._options.buttonTitle || 'Toggle Globe View'\n button.setAttribute('aria-label', 'Toggle Globe View')\n button.innerHTML = this._isGlobe ? MAP_SVG : GLOBE_SVG\n\n // Apply custom styles\n Object.assign(button.style, {\n padding: '5px',\n border: 'none',\n background: 'white',\n cursor: 'pointer',\n borderRadius: '4px',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n ...this._options.buttonStyle,\n })\n }\n\n button.addEventListener('click', () => this._toggleGlobe())\n\n return button\n }\n\n private _toggleGlobe(): void {\n if (!this._map) return\n\n this._isGlobe = !this._isGlobe\n\n // Update button icon\n this._button.innerHTML = this._isGlobe ? MAP_SVG : GLOBE_SVG\n this._button.title = this._isGlobe ? 'Switch to Map View' : 'Switch to Globe View'\n\n // Set projection\n try {\n const projection = this._isGlobe ? { type: 'globe' } : { type: 'mercator' }\n ;(this._map as any).setProjection(projection)\n this._onProjectionChange?.(this._isGlobe)\n } catch (error) {\n console.warn('GlobeControl: setProjection not available', error)\n }\n }\n\n onAdd(map: MapInstance): HTMLElement {\n this._map = map\n\n // Check if globe projection is available\n try {\n const currentProjection = (map as any).getProjection?.()\n this._isGlobe = currentProjection?.type === 'globe'\n this._button.innerHTML = this._isGlobe ? MAP_SVG : GLOBE_SVG\n } catch {\n // Globe projection not available, default to map view\n this._isGlobe = false\n }\n\n return this._container\n }\n\n onRemove(): void {\n this._container.parentNode?.removeChild(this._container)\n this._map = null\n }\n\n /**\n * Check if currently in globe view\n */\n isGlobe(): boolean {\n return this._isGlobe\n }\n\n /**\n * Set the projection programmatically\n */\n setGlobe(isGlobe: boolean): void {\n if (this._isGlobe !== isGlobe) {\n this._toggleGlobe()\n }\n }\n}\n\n/**\n * GlobeControl component for toggling between 3D globe and 2D map views.\n *\n * This control works with MapLibre GL 3.x+ which supports globe projection.\n * Adds a button to the map that toggles between mercator (flat) and globe (3D) projections.\n *\n * @component\n * @example\n * ```tsx\n * import { Map, GlobeControl } from 'react-bkoi-gl';\n * import \"react-bkoi-gl/styles\";\n *\n * function GlobeExample() {\n * const handleProjectionChange = (isGlobe) => {\n * console.log('Globe view:', isGlobe);\n * };\n *\n * return (\n * <Map\n * mapStyle={`https://map.barikoi.com/styles/osm-liberty/style.json?key=${API_KEY}`}\n * initialViewState={{\n * longitude: 90.3938,\n * latitude: 23.8216,\n * zoom: 12\n * }}\n * >\n * <GlobeControl\n * position=\"top-right\"\n * onProjectionChange={handleProjectionChange}\n * />\n * </Map>\n * );\n * }\n * ```\n */\nfunction _GlobeControl(props: GlobeControlProps) {\n const { position, onProjectionChange, ...options } = props\n\n // Store callback in ref to avoid recreating control\n const callbacksRef = useRef({ onProjectionChange })\n\n // Update callback ref when it changes\n useEffect(() => {\n callbacksRef.current = { onProjectionChange }\n }, [onProjectionChange])\n\n useControl(\n () => {\n return new GlobeControlImpl(options, {\n onProjectionChange: isGlobe => callbacksRef.current.onProjectionChange?.(isGlobe),\n })\n },\n { position }\n )\n\n return null\n}\n\nexport const GlobeControl = memo(_GlobeControl)\n","import * as React from 'react'\nimport { useEffect, memo } from 'react'\nimport {\n Map,\n type IControl,\n type GeoJSONSource,\n type ControlPosition,\n type StyleSpecification,\n} from 'maplibre-gl'\nimport { useControl } from './use-control'\n\ntype MapLibreMap = Map\n\n/**\n * Map interaction types that can be disabled/enabled\n */\nexport type MapInteractions =\n | 'dragPan'\n | 'scrollZoom'\n | 'boxZoom'\n | 'dragRotate'\n | 'keyboard'\n | 'doubleClickZoom'\n | 'touchZoomRotate'\n\n/**\n * Configuration for minimap interactions\n */\nexport type MinimapInteractions = Record<MapInteractions, boolean>\n\n/**\n * Configuration for the parent rectangle overlay\n */\nexport interface ParentRectConfig {\n /** Layout properties for the line layer */\n lineLayout?: Record<string, unknown>\n /** Paint properties for the line layer */\n linePaint?: Record<string, unknown>\n /** Paint properties for the fill layer */\n fillPaint?: Record<string, unknown>\n}\n\n/**\n * Configuration for the toggle button\n */\nexport interface ToggleButtonConfig {\n /** Custom SVG icon */\n icon?: string\n /** Custom CSS class */\n className?: string\n /** Custom inline styles */\n style?: Record<string, string>\n /** Background color of the icon */\n iconBackgroundColor?: string\n /** Hover color */\n hoverColor?: string\n /** Enable rotation based on position */\n enableRotation?: boolean\n /** Custom rotation angle */\n rotationAngle?: number\n}\n\n/**\n * Minimap control options\n */\nexport interface MinimapControlOptions {\n /** Initial center coordinates */\n center?: [number, number]\n /** Barikoi API access token */\n accessToken?: string\n /** Map style for the minimap */\n style?: string | StyleSpecification\n /** Zoom level difference from parent */\n zoomAdjust?: number\n /** Lock to specific zoom level */\n lockZoom?: number\n /** Sync pitch with parent */\n pitchAdjust?: boolean\n /** Custom container styles */\n containerStyle?: Record<string, string>\n /** Position on map */\n position?: ControlPosition\n /** Parent rectangle configuration */\n parentRect?: ParentRectConfig\n /** Whether minimap can be toggled */\n toggleable?: boolean\n /** Toggle button configuration */\n toggleButton?: ToggleButtonConfig\n /** Start minimized */\n initialMinimized?: boolean\n /** Width when minimized */\n collapsedWidth?: string\n /** Height when minimized */\n collapsedHeight?: string\n /** Border radius */\n borderRadius?: string\n /** Interaction configuration */\n interactions?: Partial<MinimapInteractions>\n /** Toggle callback */\n onToggle?: (isMinimized: boolean) => void\n /** Hide tooltip text */\n hideText?: string\n /** Show tooltip text */\n showText?: string\n /** Enable responsive sizing */\n responsive?: boolean\n /** Responsive width */\n responsiveWidth?: string\n /** Responsive height */\n responsiveHeight?: string\n /** Minimum width */\n minWidth?: string\n /** Minimum height */\n minHeight?: string\n /** Maximum width */\n maxWidth?: string\n /** Maximum height */\n maxHeight?: string\n}\n\nexport type MinimapControlProps = MinimapControlOptions\n\n// Named constants for default values\nconst DEFAULT_ZOOM_ADJUST = -4\nconst DEFAULT_COLLAPSED_SIZE = '29px'\nconst DEFAULT_BORDER_RADIUS = '3px'\nconst TRANSITION_DURATION_MS = 600\nconst RESIZE_DEBOUNCE_MS = 100\nconst DEFAULT_WIDTH = '400px'\nconst DEFAULT_HEIGHT = '300px'\n\n/**\n * Default interactions (dragPan enabled for navigation)\n */\nconst defaultInteractions: MinimapInteractions = {\n dragPan: true,\n scrollZoom: false,\n boxZoom: false,\n dragRotate: false,\n keyboard: false,\n doubleClickZoom: false,\n touchZoomRotate: false,\n}\n\n/**\n * Default SVG icon for toggle button\n */\nconst DEFAULT_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path d=\"M17.6 18L8 8.4V17H6V5h12v2H9.4l9.6 9.6l-1.4 1.4Z\" /></svg>`\n\n/**\n * Generate a random UUID using crypto API\n */\nfunction getRandomUUID(): string {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID()\n }\n // Fallback for older environments\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n const array = new Uint8Array(1)\n crypto.getRandomValues(array)\n const r = array[0] % 16\n const v = c === 'x' ? r : (r & 0x3) | 0x8\n return v.toString(16)\n })\n}\n\n/**\n * Sanitize SVG string to prevent XSS attacks\n */\nfunction sanitizeSVG(svgString: string): string {\n // Only allow valid SVG structure\n const svgPattern = /^<svg[^>]*>[\\s\\S]*<\\/svg>$/i\n if (!svgPattern.test(svgString)) {\n console.warn('Invalid SVG format, using default icon')\n return DEFAULT_ICON\n }\n\n // Remove potentially dangerous elements and attributes\n return svgString\n .replace(/<script[\\s\\S]*?<\\/script>/gi, '')\n .replace(/\\s*on\\w+\\s*=\\s*[\"'][^\"']*[\"']/gi, '')\n .replace(/javascript:/gi, '')\n}\n\n/**\n * Internal minimap options\n */\ninterface InternalMinimapOptions extends MinimapControlOptions {\n container?: HTMLElement\n zoom?: number\n minZoom?: number\n maxZoom?: number\n bearing?: number\n pitch?: number\n attributionControl: boolean\n logoPosition?: string\n}\n\n/**\n * Minimap class - wraps MapLibre Map as a control\n */\nclass Minimap implements IControl {\n private options: InternalMinimapOptions\n private map!: MapLibreMap\n private parentMap!: MapLibreMap\n private container!: HTMLElement\n private readonly id: string\n private parentRect?: GeoJSON.Feature<GeoJSON.Polygon>\n private differentStyle = false\n private desync?: () => void\n private toggleButtonCleanup?: () => void\n private isMinimized = false\n private resizeHandler?: () => void\n\n constructor(options: MinimapControlOptions = {}) {\n this.id = `minimap-${getRandomUUID()}`\n\n if (options.style !== undefined) {\n this.differentStyle = true\n }\n\n const interactions = { ...defaultInteractions, ...(options.interactions ?? {}) }\n\n const containerStyle = this.validateContainerStyle(options.containerStyle)\n\n this.options = {\n zoomAdjust: DEFAULT_ZOOM_ADJUST,\n position: 'top-right',\n pitchAdjust: false,\n attributionControl: false,\n logoPosition: 'bottom-left',\n toggleable: true,\n initialMinimized: false,\n collapsedWidth: DEFAULT_COLLAPSED_SIZE,\n collapsedHeight: DEFAULT_COLLAPSED_SIZE,\n borderRadius: DEFAULT_BORDER_RADIUS,\n hideText: 'Hide minimap',\n showText: 'Show minimap',\n responsive: true,\n responsiveWidth: '20vw',\n responsiveHeight: '20vh',\n minWidth: '200px',\n minHeight: '150px',\n maxWidth: DEFAULT_WIDTH,\n maxHeight: DEFAULT_HEIGHT,\n interactions,\n ...options,\n containerStyle,\n } as InternalMinimapOptions\n\n if (options.lockZoom !== undefined) {\n this.options.minZoom = options.lockZoom\n this.options.maxZoom = options.lockZoom\n }\n\n this.isMinimized = this.options.initialMinimized ?? false\n }\n\n onAdd(parentMap: MapLibreMap): HTMLElement {\n this.parentMap = parentMap\n\n this.container = this.createContainer()\n\n this.options.container = this.container\n this.options.zoom = parentMap.getZoom() + (this.options.zoomAdjust ?? DEFAULT_ZOOM_ADJUST)\n this.options.center ??= parentMap.getCenter().toArray() as [number, number]\n this.options.bearing = parentMap.getBearing()\n this.options.pitch = this.options.pitchAdjust ? parentMap.getPitch() : 0\n\n if (!this.differentStyle) {\n this.options.style = parentMap.getStyle()\n }\n\n this.map = new Map(this.options as unknown as ConstructorParameters<typeof Map>[0])\n\n this.map.once('style.load', () => {\n this.map.resize()\n })\n\n this.map.once('load', () => {\n this.configureInteractions()\n this.addParentRect(this.options.parentRect)\n this.desync = this.syncMaps()\n this.setupToggleButton()\n this.setupResponsiveSizing()\n })\n\n return this.container\n }\n\n onRemove(): void {\n if (this.resizeHandler) {\n window.removeEventListener('resize', this.resizeHandler)\n this.resizeHandler = undefined\n }\n this.toggleButtonCleanup?.()\n this.desync?.()\n this.container.remove()\n }\n\n private createContainer(): HTMLElement {\n const container = document.createElement('div')\n container.id = this.id\n container.className =\n 'maplibregl-ctrl maplibregl-ctrl-group maplibregl-ctrl-minimap custom-ctrl-minimap'\n\n if (this.isMinimized) {\n container.classList.add('minimized')\n }\n\n const styleEl = document.createElement('style')\n styleEl.innerHTML = this.getContainerStyles()\n container.appendChild(styleEl)\n\n if (this.options.containerStyle) {\n for (const [key, value] of Object.entries(this.options.containerStyle)) {\n container.style.setProperty(key, value)\n }\n }\n\n if (this.isMinimized) {\n container.style.width = this.options.collapsedWidth || DEFAULT_COLLAPSED_SIZE\n container.style.height = this.options.collapsedHeight || DEFAULT_COLLAPSED_SIZE\n }\n\n const preventDefault = (e: Event) => e.preventDefault()\n container.addEventListener('contextmenu', preventDefault)\n\n return container\n }\n\n private getContainerStyles(): string {\n const width = this.options.containerStyle?.width || DEFAULT_WIDTH\n const height = this.options.containerStyle?.height || DEFAULT_HEIGHT\n const collapsedWidth = this.options.collapsedWidth || DEFAULT_COLLAPSED_SIZE\n const collapsedHeight = this.options.collapsedHeight || DEFAULT_COLLAPSED_SIZE\n const borderRadius = this.options.borderRadius || DEFAULT_BORDER_RADIUS\n\n return `\n #${this.id}.custom-ctrl-minimap {\n cursor: default !important;\n box-shadow: 0 1px 5px rgba(0, 0, 0, 0.65);\n transition: width 0.6s ease-in, height 0.6s ease-in, border-color 0s ease-in;\n border-style: solid;\n border-radius: ${borderRadius};\n border-width: 4px;\n border-color: white;\n width: ${width};\n height: ${height};\n overflow: hidden;\n background: #fff;\n position: relative;\n }\n #${this.id}.minimized {\n border-radius: 3px !important;\n width: ${collapsedWidth};\n height: ${collapsedHeight};\n }\n #${this.id} canvas {\n width: 100% !important;\n height: 100% !important;\n display: block;\n }\n @media (prefers-color-scheme: dark) {\n #${this.id}.custom-ctrl-minimap {\n border-color: hsl(0, 0%, 15.2%);\n }\n }\n `\n }\n\n private validateContainerStyle(style?: Record<string, string>): Record<string, string> {\n const defaults = { border: '1px solid #000', width: DEFAULT_WIDTH, height: DEFAULT_HEIGHT }\n if (!style) return defaults\n\n const validated: Record<string, string> = {}\n if (style.width) {\n validated.width = CSS.supports('width', style.width) ? style.width : defaults.width\n } else {\n validated.width = defaults.width\n }\n if (style.height) {\n validated.height = CSS.supports('height', style.height) ? style.height : defaults.height\n } else {\n validated.height = defaults.height\n }\n for (const [key, value] of Object.entries(style)) {\n if (key !== 'width' && key !== 'height') {\n validated[key] = value\n }\n }\n return validated\n }\n\n private configureInteractions(): void {\n const interactions = this.options.interactions || defaultInteractions\n for (const [interaction, enabled] of Object.entries(interactions)) {\n if (!enabled) {\n const interactionMethod = interaction as keyof MinimapInteractions\n const interactionObj = this.map[interactionMethod] as { disable: () => void } | undefined\n interactionObj?.disable()\n }\n }\n }\n\n private setupToggleButton(): void {\n if (!this.options.toggleable) return\n\n const el = document.createElement('button')\n const elId = 'btn-' + getRandomUUID()\n\n el.innerHTML = sanitizeSVG(this.options.toggleButton?.icon || DEFAULT_ICON)\n el.setAttribute('id', elId)\n el.setAttribute('type', 'button')\n el.setAttribute('aria-label', this.options.hideText || 'Hide minimap')\n el.setAttribute('title', this.options.hideText || 'Hide minimap')\n\n if (this.options.toggleButton?.className) {\n const classes = this.options.toggleButton.className.split(' ')\n classes.forEach(cls => el.classList.add(cls))\n }\n\n const iconBackgroundColor = this.options.toggleButton?.iconBackgroundColor || 'black'\n const hoverColor = this.options.toggleButton?.hoverColor || '#e5e7e3'\n\n const styleEl = document.createElement('style')\n styleEl.innerHTML = `\n button#${elId} {\n border-radius: 0 !important;\n color: black;\n background-color: ${iconBackgroundColor};\n border: none;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n transition: all 0.2s ease-in;\n position: absolute;\n width: 24px;\n height: 24px;\n z-index: 2;\n padding: 0;\n left: 0;\n top: 0;\n }\n button#${elId}:hover {\n background-color: ${hoverColor} !important;\n }\n button#${elId} svg {\n fill: white;\n width: 16px;\n height: 16px;\n }\n .minimized > button#${elId} > * {\n transform: rotate(-180deg);\n }\n `\n\n const clickHandler = () => {\n this.toggle()\n const minimized = this.container.classList.contains('minimized')\n const text = minimized\n ? this.options.showText || 'Show minimap'\n : this.options.hideText || 'Hide minimap'\n el.setAttribute('aria-label', text)\n el.setAttribute('title', text)\n }\n\n el.addEventListener('click', clickHandler)\n document.head.appendChild(styleEl)\n this.container.appendChild(el)\n\n this.toggleButtonCleanup = () => {\n el.removeEventListener('click', clickHandler)\n styleEl.remove()\n this.container.removeChild(el)\n }\n }\n\n private setupResponsiveSizing(): void {\n if (!this.options.responsive) return\n\n const updateSize = () => {\n if (this.isMinimized) return\n\n const vw = window.innerWidth / 100\n const vh = window.innerHeight / 100\n\n const responsiveWidth = this.options.responsiveWidth || '20vw'\n const responsiveHeight = this.options.responsiveHeight || '20vh'\n\n let width: number\n let height: number\n\n if (responsiveWidth.endsWith('vw')) {\n width = parseFloat(responsiveWidth) * vw\n } else if (responsiveWidth.endsWith('%')) {\n width = (parseFloat(responsiveWidth) / 100) * window.innerWidth\n } else {\n width = parseFloat(responsiveWidth)\n }\n\n if (responsiveHeight.endsWith('vh')) {\n height = parseFloat(responsiveHeight) * vh\n } else if (responsiveHeight.endsWith('%')) {\n height = (parseFloat(responsiveHeight) / 100) * window.innerHeight\n } else {\n height = parseFloat(responsiveHeight)\n }\n\n const minW = parseFloat(this.options.minWidth || '200px')\n const minH = parseFloat(this.options.minHeight || '150px')\n const maxW = parseFloat(this.options.maxWidth || DEFAULT_WIDTH)\n const maxH = parseFloat(this.options.maxHeight || DEFAULT_HEIGHT)\n\n width = Math.max(minW, Math.min(maxW, width))\n height = Math.max(minH, Math.min(maxH, height))\n\n this.container.style.width = `${width}px`\n this.container.style.height = `${height}px`\n\n this.map.resize()\n this.setParentBounds()\n }\n\n updateSize()\n\n let resizeTimeout: ReturnType<typeof setTimeout>\n this.resizeHandler = () => {\n clearTimeout(resizeTimeout)\n resizeTimeout = setTimeout(updateSize, RESIZE_DEBOUNCE_MS)\n }\n\n window.addEventListener('resize', this.resizeHandler)\n }\n\n toggle(): void {\n this.isMinimized = !this.isMinimized\n\n const collapsedWidth = this.options.collapsedWidth || DEFAULT_COLLAPSED_SIZE\n const collapsedHeight = this.options.collapsedHeight || DEFAULT_COLLAPSED_SIZE\n\n if (this.isMinimized) {\n this.container.classList.add('minimized')\n this.container.style.width = collapsedWidth\n this.container.style.height = collapsedHeight\n } else {\n this.container.classList.remove('minimized')\n if (this.options.responsive && this.resizeHandler) {\n this.resizeHandler()\n } else {\n const expandedWidth = this.options.containerStyle?.width || DEFAULT_WIDTH\n const expandedHeight = this.options.containerStyle?.height || DEFAULT_HEIGHT\n this.container.style.width = expandedWidth\n this.container.style.height = expandedHeight\n }\n }\n\n this.options.onToggle?.(this.isMinimized)\n\n setTimeout(() => {\n this.map.resize()\n this.setParentBounds()\n }, TRANSITION_DURATION_MS)\n }\n\n isMinimizedState(): boolean {\n return this.isMinimized\n }\n\n private addParentRect(rect?: ParentRectConfig): void {\n if (rect === undefined || (rect.linePaint === undefined && rect.fillPaint === undefined)) {\n return\n }\n\n this.parentRect = {\n type: 'Feature',\n properties: { name: 'parentRect' },\n geometry: {\n type: 'Polygon',\n coordinates: [[[], [], [], [], []]],\n },\n }\n\n this.map.addSource('parentRect', {\n type: 'geojson',\n data: this.parentRect,\n })\n\n if (rect.lineLayout !== undefined || rect.linePaint !== undefined) {\n this.map.addLayer({\n id: 'parentRectOutline',\n type: 'line',\n source: 'parentRect',\n layout: { ...(rect.lineLayout || {}) },\n paint: {\n 'line-color': '#FFF',\n 'line-width': 1,\n 'line-opacity': 0.85,\n ...(rect.linePaint || {}),\n },\n })\n }\n\n if (rect.fillPaint !== undefined) {\n this.map.addLayer({\n id: 'parentRectFill',\n type: 'fill',\n source: 'parentRect',\n layout: {},\n paint: {\n 'fill-color': '#08F',\n 'fill-opacity': 0.135,\n ...(rect.fillPaint || {}),\n },\n })\n }\n\n this.setParentBounds()\n }\n\n private setParentBounds(): void {\n if (this.parentRect === undefined || this.isMinimized) return\n\n const { devicePixelRatio } = window\n const canvas = this.parentMap.getCanvas()\n const width = canvas.width / devicePixelRatio\n const height = canvas.height / devicePixelRatio\n\n const unproject = this.parentMap.unproject.bind(this.parentMap)\n const northWest = unproject([0, 0])\n const northEast = unproject([width, 0])\n const southWest = unproject([0, height])\n const southEast = unproject([width, height])\n\n this.parentRect.geometry.coordinates = [\n [\n southWest.toArray(),\n southEast.toArray(),\n northEast.toArray(),\n northWest.toArray(),\n southWest.toArray(),\n ],\n ]\n\n const source = this.map.getSource<GeoJSONSource>('parentRect')\n if (source !== undefined) {\n source.setData(this.parentRect)\n }\n }\n\n private syncMaps(): () => void {\n const { pitchAdjust } = this.options\n\n const parentCallback = () => {\n if (!this.isMinimized) {\n sync('parent')\n }\n }\n const minimapCallback = () => {\n if (!this.isMinimized) {\n sync('minimap')\n }\n }\n\n const on = () => {\n this.parentMap.on('move', parentCallback)\n this.map.on('move', minimapCallback)\n }\n\n const off = () => {\n this.parentMap.off('move', parentCallback)\n this.map.off('move', minimapCallback)\n }\n\n const sync = (which: 'parent' | 'minimap') => {\n off()\n\n const from = which === 'parent' ? this.parentMap : this.map\n const to = which === 'parent' ? this.map : this.parentMap\n\n const center = from.getCenter()\n const zoom =\n from.getZoom() +\n (this.options.zoomAdjust ?? DEFAULT_ZOOM_ADJUST) * (which === 'parent' ? 1 : -1)\n const bearing = from.getBearing()\n const pitch = from.getPitch()\n\n to.jumpTo({\n center,\n zoom,\n bearing,\n pitch: pitchAdjust ? pitch : 0,\n })\n\n this.setParentBounds()\n on()\n }\n\n on()\n\n return () => {\n off()\n }\n }\n}\n\nfunction _MinimapControl(props: MinimapControlProps) {\n const { position, ...options } = props\n\n // Create minimap control using useControl\n useControl<Minimap>(() => new Minimap(options), { position })\n\n return null\n}\n\nexport const MinimapControl = memo(_MinimapControl)\n\n// Also export the Minimap class for direct use\nexport { Minimap }\n","import { Map } from './components/map'\n\nexport { Map }\nexport default Map\n\nexport { Marker } from './components/marker'\nexport { Popup } from './components/popup'\nexport { AttributionControl } from './components/attribution-control'\nexport { FullscreenControl } from './components/fullscreen-control'\nexport { GeolocateControl } from './components/geolocate-control'\nexport { NavigationControl } from './components/navigation-control'\nexport { ScaleControl } from './components/scale-control'\nexport { TerrainControl } from './components/terrain-control'\nexport { LogoControl } from './components/logo-control'\nexport { Source } from './components/source'\nexport { CanvasSource } from './components/canvas-source'\nexport { Layer } from './components/layer'\nexport { useControl } from './components/use-control'\nexport { MapProvider, useMap } from './components/use-map'\nexport { DrawControl } from './components/draw-control'\nexport { GlobeControl } from './components/globe-control'\nexport {\n MinimapControl,\n Minimap,\n type MinimapControlOptions,\n type MinimapControlProps,\n type MinimapInteractions,\n type MapInteractions,\n type ParentRectConfig,\n type ToggleButtonConfig,\n} from './components/minimap-control'\n\nexport type { MapProps } from './components/map'\nexport type { MapRef } from './maplibre/create-ref'\nexport type { MarkerProps } from './components/marker'\nexport type { PopupProps } from './components/popup'\nexport type { AttributionControlProps } from './components/attribution-control'\nexport type { FullscreenControlProps } from './components/fullscreen-control'\nexport type { GeolocateControlProps } from './components/geolocate-control'\nexport type { NavigationControlProps } from './components/navigation-control'\nexport type { ScaleControlProps } from './components/scale-control'\nexport type { TerrainControlProps } from './components/terrain-control'\nexport type { LogoControlProps } from './components/logo-control'\nexport type { SourceProps } from './components/source'\nexport type { CanvasSourceProps, CanvasCoordinates } from './components/canvas-source'\nexport type { LayerProps } from './components/layer'\n\n// Re-export MapLayerMouseEvent for layer event typing\nexport type { MapLayerMouseEvent } from 'maplibre-gl'\nexport type { DrawControlProps, DrawControlOptions } from './components/draw-control'\nexport type { GlobeControlProps, GlobeControlOptions } from './components/globe-control'\n\n// Types\nexport * from './types/common'\nexport * from './types/events'\nexport * from './types/lib'\nexport * from './types/style-spec'\n"],"mappings":";AAAA,YAAYA,YAAW;AACvB,SAAS,YAAAC,WAAU,QAAQ,aAAAC,YAAW,cAAAC,aAAY,WAAAC,UAAS,2BAA2B;;;ACDtF,YAAY,WAAW;AACvB,SAAS,UAAU,aAAa,SAAS,kBAAkB;AAWpD,IAAM,qBAA2B,oBAAuC,IAAI;AAE5E,IAAM,cAAwD,WAAS;AAC5E,QAAM,CAAC,MAAM,OAAO,IAAI,SAAmC,CAAC,CAAC;AAE7D,QAAM,aAAa,YAAY,CAAC,KAAa,KAAa,cAAc;AACtE,YAAQ,cAAY;AAClB,UAAI,OAAO,WAAW;AACpB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UAAM,OAAO,CAAC,UAAgC;AAC5C,UAAI;AAEJ,YAAM,OAAO,UAAU,WAAW,KAAK,YAAY,KAAK;AACxD,YAAM,KAAK,UAAU,WAAW,KAAK,MAAM,KAAK;AAEhD,YAAM,SAAS,KAAK,UAAU;AAC9B,YAAM,OACJ,KAAK,QAAQ,KACZ,KAAK,QAAQ,cAAc,wBAAwB,UAAU,WAAW,IAAI;AAC/E,YAAM,UAAU,KAAK,WAAW;AAChC,YAAM,QAAQ,KAAK,SAAS;AAE5B,SAAG,OAAO;AAAA,QACR;AAAA,QACA;AAAA,QACA;AAAA,QACA,OAAO,cAAc,QAAQ;AAAA,MAC/B,CAAC;AAED,WAAK,gBAAgB;AACrB,SAAG;AAAA,IACL;AAEA,OAAG;AAEH,WAAO,MAAM;AACX,UAAI;AAAA,IACN;AAAA,EACF;AACF;AAEA,SAAS,gBAAgB,OAA4B;AACnD,QAAM,EAAE,UAAU,GAAG,QAAQ,IAAI;AAGjC,aAAoB,MAAM,IAAI,QAAQ,OAAO,GAAG,EAAE,SAAS,CAAC;AAE5D,SAAO;AACT;AAEO,IAAM,iBAAiBC,OAAK,eAAe;;;ACzsBlD,IAAO,8BAAQ;","names":["React","useState","useEffect","useContext","useMemo","useEffect","useContext","useMemo","useEffect","useContext","useMemo","useEffect","useEffect","useEffect","memo","useEffect","memo","useContext","useState","useEffect","useMemo","React","useImperativeHandle","useEffect","useMemo","useRef","useContext","forwardRef","memo","memo","forwardRef","useContext","useRef","useMemo","useEffect","useImperativeHandle","createPortal","useImperativeHandle","useEffect","useMemo","useContext","forwardRef","memo","memo","forwardRef","useContext","useMemo","useImperativeHandle","useEffect","createPortal","useEffect","memo","useEffect","memo","useImperativeHandle","useRef","useEffect","forwardRef","memo","useRef","useImperativeHandle","useEffect","memo","forwardRef","useEffect","memo","useEffect","memo","useEffect","useRef","memo","useRef","useEffect","memo","useEffect","memo","useEffect","memo","React","useContext","useEffect","useMemo","useState","useRef","memo","useImperativeHandle","useContext","useRef","useState","useMemo","useEffect","mapInternal","useImperativeHandle","memo","React","useContext","useEffect","useMemo","useRef","memo","useContext","useRef","useMemo","useEffect","mapInternal","updateSource","memo","useContext","useEffect","useMemo","useState","useRef","memo","useId","useContext","useRef","useState","useId","useMemo","useEffect","mapInternal","memo","useEffect","useMemo","memo","useRef","useContext","useContext","useMemo","useRef","useEffect","memo","useEffect","memo","useRef","useRef","useEffect","memo","memo","Map","Map","memo"]}
1
+ {"version":3,"sources":["../src/components/map.tsx","../src/components/use-map.tsx","../src/utils/deep-equal.ts","../src/utils/transform.ts","../src/utils/style-utils.ts","../src/utils/logger.ts","../src/maplibre/maplibre.ts","../src/maplibre/create-ref.ts","../src/utils/use-isomorphic-layout-effect.ts","../src/utils/set-globals.ts","../src/components/logo-control.ts","../src/utils/apply-react-style.ts","../src/components/use-control.ts","../src/components/attribution-control.ts","../src/components/marker.ts","../src/utils/compare-class-names.ts","../src/components/popup.ts","../src/components/fullscreen-control.ts","../src/components/geolocate-control.ts","../src/components/navigation-control.ts","../src/components/scale-control.ts","../src/components/terrain-control.ts","../src/components/source.ts","../src/utils/assert.ts","../src/utils/warn.ts","../src/components/canvas-source.ts","../src/components/layer.ts","../src/components/draw-control.ts","../node_modules/maplibre-gl-draw/src/lib/mode_handler.js","../node_modules/maplibre-gl-draw/node_modules/wgs84/index.js","../node_modules/maplibre-gl-draw/node_modules/@mapbox/geojson-area/index.js","../node_modules/maplibre-gl-draw/src/constants.js","../node_modules/maplibre-gl-draw/src/lib/sort_features.js","../node_modules/maplibre-gl-draw/src/lib/map_event_to_bounding_box.js","../node_modules/maplibre-gl-draw/src/lib/string_set.js","../node_modules/maplibre-gl-draw/src/lib/features_at.js","../node_modules/maplibre-gl-draw/src/lib/get_features_and_set_cursor.js","../node_modules/maplibre-gl-draw/src/lib/euclidean_distance.js","../node_modules/maplibre-gl-draw/src/lib/is_click.js","../node_modules/maplibre-gl-draw/src/lib/is_tap.js","../node_modules/maplibre-gl-draw/node_modules/hat/index.js","../node_modules/maplibre-gl-draw/src/feature_types/feature.js","../node_modules/maplibre-gl-draw/src/feature_types/point.js","../node_modules/maplibre-gl-draw/src/feature_types/line_string.js","../node_modules/maplibre-gl-draw/src/feature_types/polygon.js","../node_modules/maplibre-gl-draw/src/feature_types/multi_feature.js","../node_modules/maplibre-gl-draw/src/modes/mode_interface_accessors.js","../node_modules/maplibre-gl-draw/src/modes/mode_interface.js","../node_modules/maplibre-gl-draw/src/modes/object_to_mode.js","../node_modules/maplibre-gl-draw/src/lib/SRCenter.js","../node_modules/maplibre-gl-draw/src/events.js","../node_modules/maplibre-gl-draw/src/lib/to_dense_array.js","../node_modules/maplibre-gl-draw/src/render.js","../node_modules/maplibre-gl-draw/src/store.js","../node_modules/maplibre-gl-draw/node_modules/xtend/immutable.js","../node_modules/maplibre-gl-draw/src/ui.js","../node_modules/maplibre-gl-draw/src/setup.js","../node_modules/maplibre-gl-draw/src/lib/theme.js","../node_modules/maplibre-gl-draw/src/lib/common_selectors.js","../node_modules/maplibre-gl-draw/node_modules/@mapbox/point-geometry/index.js","../node_modules/maplibre-gl-draw/src/lib/mouse_event_point.js","../node_modules/maplibre-gl-draw/src/lib/create_vertex.js","../node_modules/maplibre-gl-draw/src/lib/create_midpoint.js","../node_modules/maplibre-gl-draw/src/lib/create_supplementary_points.js","../node_modules/maplibre-gl-draw/src/lib/double_click_zoom.js","../node_modules/maplibre-gl-draw/node_modules/@mapbox/geojson-normalize/index.js","../node_modules/maplibre-gl-draw/node_modules/geojson-flatten/dist/index.es.js","../node_modules/maplibre-gl-draw/node_modules/@mapbox/geojson-coords/flatten.js","../node_modules/maplibre-gl-draw/node_modules/@mapbox/geojson-coords/index.js","../node_modules/maplibre-gl-draw/node_modules/traverse/index.js","../node_modules/maplibre-gl-draw/node_modules/@mapbox/extent/index.js","../node_modules/maplibre-gl-draw/node_modules/@mapbox/geojson-extent/index.js","../node_modules/maplibre-gl-draw/src/lib/constrain_feature_movement.js","../node_modules/maplibre-gl-draw/src/lib/move_features.js","../node_modules/maplibre-gl-draw/src/modes/simple_select.js","../node_modules/maplibre-gl-draw/src/modes/direct_select.js","../node_modules/maplibre-gl-draw/src/modes/draw_point.js","../node_modules/maplibre-gl-draw/src/lib/is_event_at_coordinates.js","../node_modules/maplibre-gl-draw/src/modes/draw_polygon.js","../node_modules/maplibre-gl-draw/src/modes/draw_line_string.js","../node_modules/maplibre-gl-draw/node_modules/@turf/helpers/dist/es/index.js","../node_modules/maplibre-gl-draw/node_modules/@turf/bearing/node_modules/@turf/helpers/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/bearing/node_modules/@turf/invariant/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/bearing/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/bbox/node_modules/@turf/meta/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/bbox/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/center/node_modules/@turf/helpers/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/center/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/destination/node_modules/@turf/helpers/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/destination/node_modules/@turf/invariant/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/destination/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/distance/node_modules/@turf/helpers/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/distance/node_modules/@turf/invariant/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/distance/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/midpoint/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/transform-rotate/node_modules/@turf/helpers/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/transform-rotate/node_modules/@turf/meta/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/transform-rotate/node_modules/@turf/centroid/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/rhumb-bearing/node_modules/@turf/helpers/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/rhumb-bearing/node_modules/@turf/invariant/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/rhumb-bearing/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/rhumb-distance/node_modules/@turf/helpers/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/rhumb-distance/node_modules/@turf/invariant/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/rhumb-distance/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/rhumb-destination/node_modules/@turf/helpers/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/rhumb-destination/node_modules/@turf/invariant/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/rhumb-destination/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/clone/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/transform-rotate/node_modules/@turf/invariant/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/transform-rotate/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/transform-scale/node_modules/@turf/helpers/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/transform-scale/node_modules/@turf/meta/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/transform-scale/node_modules/@turf/centroid/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/transform-scale/node_modules/@turf/invariant/main.es.js","../node_modules/maplibre-gl-draw/node_modules/@turf/transform-scale/main.es.js","../node_modules/maplibre-gl-draw/src/modes/img/rotate.png","../node_modules/maplibre-gl-draw/src/modes/img/scale.png","../node_modules/maplibre-gl-draw/src/modes/SRMode.js","../node_modules/maplibre-gl-draw/src/modes/index.js","../node_modules/maplibre-gl-draw/src/lib/SRStyle.js","../node_modules/maplibre-gl-draw/src/options.js","../node_modules/maplibre-gl-draw/node_modules/lodash.isequal/index.js","../node_modules/maplibre-gl-draw/src/lib/string_sets_are_equal.js","../node_modules/maplibre-gl-draw/src/api.js","../node_modules/maplibre-gl-draw/index.js","../src/components/globe-control.ts","../src/components/minimap-control.ts","../src/exports-maplibre-gl.ts"],"sourcesContent":["import * as React from 'react'\nimport { useState, useRef, useEffect, useContext, useMemo, useImperativeHandle } from 'react'\n\nimport { MountedMapsContext } from './use-map'\nimport Maplibre, { MaplibreProps } from '../maplibre/maplibre'\nimport createRef, { MapRef } from '../maplibre/create-ref'\n\nimport type { CSSProperties } from 'react'\nimport useIsomorphicLayoutEffect from '../utils/use-isomorphic-layout-effect'\nimport setGlobals, { GlobalSettings } from '../utils/set-globals'\nimport type { MapLib, MapOptions } from '../types/lib'\nimport type { MapOptionsInternal } from '../types/internal'\nimport type { ErrorEvent } from '../types/events'\nimport { LogoControl } from './logo-control'\nimport { AttributionControl } from './attribution-control'\nimport { logger } from '../utils/logger'\n\nexport type MapContextValue = {\n mapLib: MapLib\n map: MapRef\n /** Consumer-supplied warning handler, propagated to child components so they\n * can surface non-fatal warnings without touching console directly. */\n onWarning?: (e: ErrorEvent) => void\n}\n\nexport const MapContext = React.createContext<MapContextValue>(null)\n\ntype MapInitOptions = Omit<\n MapOptions,\n 'style' | 'container' | 'bounds' | 'fitBoundsOptions' | 'center'\n>\n\nexport type MapProps = MapInitOptions &\n MaplibreProps &\n GlobalSettings & {\n mapLib?: MapLib | Promise<MapLib>\n reuseMaps?: boolean\n /** Map container id */\n id?: string\n /** Map container CSS style */\n style?: CSSProperties\n children?: React.ReactNode\n /** Whether to render the Barikoi logo control.\n * @default true */\n showBarikoiLogo?: boolean\n /** Whether to render the map attribution control.\n * @default true\n * @remarks Attribution is required by the OpenStreetMap and MapLibre\n * license terms; keep this enabled unless you provide attribution elsewhere. */\n showAttribution?: boolean\n } & React.RefAttributes<MapRef>\n\nfunction _Map(props: MapProps, ref: React.Ref<MapRef>) {\n const mountedMapsContext = useContext(MountedMapsContext)\n const [mapInstance, setMapInstance] = useState<Maplibre>(null)\n const containerRef = useRef<HTMLDivElement>(null)\n\n const propsRef = useRef(props)\n propsRef.current = props\n\n const prevPropsRef = useRef<MapProps>(props)\n\n const { current: contextValue } = useRef<MapContextValue>({\n mapLib: null,\n map: null,\n })\n\n useEffect(() => {\n const initialMapLib = propsRef.current.mapLib\n const initialId = propsRef.current.id\n const initialReuseMaps = propsRef.current.reuseMaps\n\n let isMounted = true\n let maplibre: Maplibre | null = null\n\n Promise.resolve(initialMapLib || import('maplibre-gl'))\n .then((module: MapLib | { default: MapLib }) => {\n if (!isMounted) {\n return\n }\n if (!module) {\n throw new Error('Invalid mapLib')\n }\n const mapboxgl = 'Map' in module ? module : module.default\n if (!mapboxgl.Map) {\n throw new Error('Invalid mapLib')\n }\n\n setGlobals(mapboxgl, propsRef.current)\n if (initialReuseMaps) {\n maplibre = Maplibre.reuse(propsRef.current, containerRef.current)\n }\n if (!maplibre) {\n maplibre = new Maplibre(\n mapboxgl.Map as any,\n {\n ...propsRef.current,\n attributionControl: false,\n } as MapOptions & MapOptionsInternal & MaplibreProps,\n containerRef.current\n )\n }\n if (maplibre) {\n contextValue.map = createRef(maplibre)\n contextValue.mapLib = mapboxgl\n setMapInstance(maplibre)\n }\n mountedMapsContext?.onMapMount(contextValue.map, propsRef.current.id || initialId)\n })\n .catch(error => {\n const { onError } = propsRef.current\n if (onError) {\n onError({\n type: 'error',\n target: null,\n originalEvent: null,\n error,\n })\n } else {\n logger.error(error)\n }\n })\n\n return () => {\n isMounted = false\n if (maplibre) {\n mountedMapsContext?.onMapUnmount(propsRef.current.id || initialId)\n if (initialReuseMaps) {\n maplibre.recycle()\n } else {\n maplibre.destroy()\n }\n }\n }\n }, [])\n\n // Keep latest props in a ref so this effect doesn't re-subscribe every render.\n const latestPropsRef = useRef(props)\n latestPropsRef.current = props\n\n useIsomorphicLayoutEffect(() => {\n if (!mapInstance) return\n const prevProps = prevPropsRef.current\n const currentProps = latestPropsRef.current\n if (!prevProps) {\n prevPropsRef.current = currentProps\n return\n }\n\n let propsChanged = false\n for (const key in currentProps) {\n if (key !== 'children' && key !== 'mapLib') {\n if (currentProps[key] !== prevProps[key]) {\n propsChanged = true\n break\n }\n }\n }\n if (!propsChanged) {\n for (const key in prevProps) {\n if (key !== 'children' && key !== 'mapLib') {\n if (!(key in currentProps)) {\n propsChanged = true\n break\n }\n }\n }\n }\n\n if (propsChanged) {\n mapInstance.setProps(currentProps)\n }\n prevPropsRef.current = currentProps\n }, [mapInstance])\n\n useImperativeHandle(ref, () => contextValue.map, [mapInstance])\n\n const style: CSSProperties = useMemo(\n () => ({\n position: 'relative',\n width: '100%',\n height: '100%',\n ...props.style,\n }),\n [props.style]\n )\n\n const CHILD_CONTAINER_STYLE = {\n height: '100%',\n }\n\n // Propagate the warning handler to children via the (stable) context value.\n contextValue.onWarning = props.onWarning\n\n // The outer container holds the MapLibre map. MapLibre automatically assigns\n // role=\"region\" and aria-label=\"Map\" to the internal canvas element.\n // Note: For keyboard accessibility (arrow keys for panning, +/- for zooming),\n // the `keyboard` option must remain enabled (defaults to true).\n return (\n <div id={props.id} ref={containerRef} style={style}>\n {mapInstance && (\n <MapContext.Provider value={contextValue}>\n <div style={CHILD_CONTAINER_STYLE}>\n {/* Automatically include Barikoi Logo and Attribution controls.\n Both default to true; set showBarikoiLogo / showAttribution to\n false to opt out. */}\n {props.showBarikoiLogo !== false && <LogoControl position='bottom-left' />}\n {props.showAttribution !== false && <AttributionControl position='bottom-right' />}\n {props.children}\n </div>\n </MapContext.Provider>\n )}\n </div>\n )\n}\n\n/**\n * Interactive Map component using MapLibre GL.\n *\n * @remarks\n * For keyboard navigation and accessibility, the `keyboard` prop must be set to `true` (which is default).\n * If explicitly disabled (e.g. `keyboard={false}`), keyboard access (such as panning/zooming via arrow keys)\n * will be unavailable to screen reader and keyboard-only users.\n */\nexport const Map: React.FC<MapProps> = React.forwardRef(_Map)\n","import * as React from 'react'\nimport { useState, useCallback, useMemo, useContext } from 'react'\n\nimport { MapRef } from '../maplibre/create-ref'\nimport { MapContext } from './map'\n\ntype MountedMapsContextValue = {\n maps: { [id: string]: MapRef }\n onMapMount: (map: MapRef, id: string) => void\n onMapUnmount: (id: string) => void\n}\n\nexport const MountedMapsContext = React.createContext<MountedMapsContextValue>(null)\n\nexport const MapProvider: React.FC<{ children?: React.ReactNode }> = props => {\n const [maps, setMaps] = useState<{ [id: string]: MapRef }>({})\n\n const onMapMount = useCallback((map: MapRef, id: string = 'default') => {\n setMaps(currMaps => {\n if (id === 'current') {\n throw new Error(\"'current' cannot be used as map id\")\n }\n if (currMaps[id]) {\n throw new Error(`Multiple maps with the same id: ${id}`)\n }\n return { ...currMaps, [id]: map }\n })\n }, [])\n\n const onMapUnmount = useCallback((id: string = 'default') => {\n setMaps(currMaps => {\n if (currMaps[id]) {\n const nextMaps = { ...currMaps }\n delete nextMaps[id]\n return nextMaps\n }\n return currMaps\n })\n }, [])\n\n return (\n <MountedMapsContext.Provider\n value={{\n maps,\n onMapMount,\n onMapUnmount,\n }}\n >\n {props.children}\n </MountedMapsContext.Provider>\n )\n}\n\nexport type MapCollection = {\n [id: string]: MapRef | undefined\n current?: MapRef\n}\n\nexport function useMap(): MapCollection {\n const maps = useContext(MountedMapsContext)?.maps\n const currentMap = useContext(MapContext)\n\n const mapsWithCurrent = useMemo(() => {\n // If currentMap is available from MapContext, use it\n // Otherwise, fall back to the first registered map from MountedMapsContext\n const current = currentMap?.map || (maps ? Object.values(maps)[0] : undefined)\n return { ...maps, current }\n }, [maps, currentMap])\n\n return mapsWithCurrent as MapCollection\n}\n","import type { PointLike } from '../types/common'\n\n/**\n * Compare two points\n * @param a\n * @param b\n * @returns true if the points are equal\n */\nexport function arePointsEqual(a?: PointLike, b?: PointLike): boolean {\n const ax = Array.isArray(a) ? a[0] : a ? a.x : 0\n const ay = Array.isArray(a) ? a[1] : a ? a.y : 0\n const bx = Array.isArray(b) ? b[0] : b ? b.x : 0\n const by = Array.isArray(b) ? b[1] : b ? b.y : 0\n return ax === bx && ay === by\n}\n\n/**\n * Compare any two objects\n * @param a\n * @param b\n * @returns true if the objects are deep equal\n */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) {\n return true\n }\n if (!a || !b) {\n return false\n }\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) {\n return false\n }\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) {\n return false\n }\n }\n return true\n } else if (Array.isArray(b)) {\n return false\n }\n if (typeof a === 'object' && typeof b === 'object') {\n const aKeys = Object.keys(a)\n const bKeys = Object.keys(b)\n if (aKeys.length !== bKeys.length) {\n return false\n }\n for (const key of aKeys) {\n if (!Object.prototype.hasOwnProperty.call(b, key)) {\n return false\n }\n if (!deepEqual(a[key], b[key])) {\n return false\n }\n }\n return true\n }\n return false\n}\n","import type { MaplibreProps } from '../maplibre/maplibre'\nimport type { ViewState } from '../types/common'\nimport type { TransformLike } from '../types/internal'\nimport { deepEqual } from './deep-equal'\n\n/**\n * Capture a transform's current state\n * @param transform\n * @returns descriptor of the view state\n */\nexport function transformToViewState(tr: TransformLike): ViewState {\n return {\n longitude: tr.center.lng,\n latitude: tr.center.lat,\n zoom: tr.zoom,\n pitch: tr.pitch,\n bearing: tr.bearing,\n padding: tr.padding,\n }\n}\n\n/**\n * Applies requested view state to a transform\n * @returns an object containing detected changes\n */\nexport function applyViewStateToTransform(\n /** An object that describes Maplibre's camera state */\n tr: TransformLike,\n /** Props from Map component */\n props: MaplibreProps\n): Partial<TransformLike> {\n const v: Partial<ViewState> = props.viewState || props\n const changes: Partial<TransformLike> = {}\n\n if (\n 'longitude' in v &&\n 'latitude' in v &&\n (v.longitude !== tr.center.lng || v.latitude !== tr.center.lat)\n ) {\n const LngLat = tr.center.constructor\n // @ts-expect-error we should not import LngLat class from maplibre-gl because we don't know the source of mapLib\n changes.center = new LngLat(v.longitude, v.latitude)\n }\n if ('zoom' in v && v.zoom !== tr.zoom) {\n changes.zoom = v.zoom\n }\n if ('bearing' in v && v.bearing !== tr.bearing) {\n changes.bearing = v.bearing\n }\n if ('pitch' in v && v.pitch !== tr.pitch) {\n changes.pitch = v.pitch\n }\n if (v.padding && tr.padding && !deepEqual(v.padding, tr.padding)) {\n changes.padding = v.padding\n }\n return changes\n}\n","import type { StyleSpecification } from '../types/style-spec'\nimport type { ImmutableLike } from '../types/common'\n\nconst refProps = ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout']\n\n// Legacy layer type with optional fields not in current type definitions\ninterface LegacyLayer {\n id: string\n interactive?: boolean\n ref?: string\n [key: string]: unknown\n}\n\n// Prepare a map style object for diffing\n// If immutable - convert to plain object\n// Work around some issues in older styles that would fail Mapbox's diffing\nexport function normalizeStyle(\n style: string | StyleSpecification | ImmutableLike<StyleSpecification>\n): string | StyleSpecification | null {\n if (!style) {\n return null\n }\n if (typeof style === 'string') {\n return style\n }\n if ('toJS' in style) {\n style = style.toJS()\n }\n if (!style.layers) {\n return style\n }\n const layerIndex: Record<string, LegacyLayer> = {}\n\n for (const layer of style.layers) {\n layerIndex[layer.id] = layer as LegacyLayer\n }\n\n const layers = style.layers.map(layer => {\n const legacyLayer = layer as LegacyLayer\n let normalizedLayer: LegacyLayer | null = null\n\n if ('interactive' in legacyLayer) {\n normalizedLayer = Object.assign({}, legacyLayer)\n // Breaks style diffing :(\n delete normalizedLayer.interactive\n }\n\n // Style diffing doesn't work with refs so expand them out manually before diffing.\n const layerRef = layerIndex[legacyLayer.ref as string]\n if (layerRef) {\n normalizedLayer = normalizedLayer || Object.assign({}, legacyLayer)\n delete normalizedLayer.ref\n // https://github.com/mapbox/mapbox-gl-js/blob/master/src/style-spec/deref.js\n for (const propName of refProps) {\n if (propName in layerRef) {\n normalizedLayer[propName] = layerRef[propName]\n }\n }\n }\n\n return (normalizedLayer || layer) as typeof layer\n })\n\n // Do not mutate the style object provided by the user\n return { ...style, layers }\n}\n","export interface Logger {\n warn: (message: any, ...args: any[]) => void\n error: (message: any, ...args: any[]) => void\n}\n\nlet activeLogger: Logger = {\n warn: (message, ...args) => console.warn(message, ...args),\n error: (message, ...args) => console.error(message, ...args),\n}\n\nexport const logger = {\n warn(message: any, ...args: any[]) {\n activeLogger.warn(message, ...args)\n },\n error(message: any, ...args: any[]) {\n activeLogger.error(message, ...args)\n },\n}\n\nexport function setLogger(customLogger: Partial<Logger>) {\n activeLogger = {\n warn:\n typeof customLogger.warn === 'function'\n ? customLogger.warn\n : (m, ...a) => console.warn(m, ...a),\n error:\n typeof customLogger.error === 'function'\n ? customLogger.error\n : (m, ...a) => console.error(m, ...a),\n }\n}\n","import { transformToViewState, applyViewStateToTransform } from '../utils/transform'\nimport { normalizeStyle } from '../utils/style-utils'\nimport { deepEqual } from '../utils/deep-equal'\nimport { logger } from '../utils/logger'\n\nimport type { TransformLike, MapInternalProperties, MapWithProjection } from '../types/internal'\nimport type {\n ViewState,\n Point,\n PointLike,\n PaddingOptions,\n ImmutableLike,\n LngLatBoundsLike,\n MapGeoJSONFeature,\n} from '../types/common'\nimport type {\n StyleSpecification,\n SkySpecification,\n LightSpecification,\n TerrainSpecification,\n ProjectionSpecification,\n} from '../types/style-spec'\nimport type { Map as MapInstance } from '../types/lib'\nimport type {\n MapCallbacks,\n ViewStateChangeEvent,\n MapEvent,\n ErrorEvent,\n MapMouseEvent,\n} from '../types/events'\n\nexport type MaplibreProps = Partial<ViewState> &\n MapCallbacks & {\n /** Camera options used when constructing the Map instance */\n initialViewState?: Partial<ViewState> & {\n /** The initial bounds of the map. If bounds is specified, it overrides longitude, latitude and zoom options. */\n bounds?: LngLatBoundsLike\n /** A fitBounds options object to use only when setting the bounds option. */\n fitBoundsOptions?: {\n offset?: PointLike\n minZoom?: number\n maxZoom?: number\n padding?: number | PaddingOptions\n }\n }\n\n /** If provided, render into an external WebGL context */\n gl?: WebGLRenderingContext\n\n /** For external controller to override the camera state */\n viewState?: ViewState & {\n width: number\n height: number\n }\n\n // Styling\n\n /** Mapbox style */\n mapStyle?: string | StyleSpecification | ImmutableLike<StyleSpecification>\n /** Enable diffing when the map style changes\n * @default true\n */\n styleDiffing?: boolean\n /** The projection property of the style. Must conform to the Projection Style Specification.\n * @default 'mercator'\n */\n projection?: ProjectionSpecification | 'mercator' | 'globe'\n /** Light properties of the map. */\n light?: LightSpecification\n /** Terrain property of the style. Must conform to the Terrain Style Specification.\n * If `undefined` is provided, removes terrain from the map. */\n terrain?: TerrainSpecification\n /** Sky properties of the map. Must conform to the Sky Style Specification. */\n sky?: SkySpecification\n\n /** Default layers to query on pointer events */\n interactiveLayerIds?: string[]\n /** CSS cursor */\n cursor?: string\n\n /** Called with non-fatal warnings (e.g. transient errors before the style\n * has finished loading). When omitted, warnings fall back to `console.warn`. */\n onWarning?: (e: ErrorEvent) => void\n }\n\nconst DEFAULT_STYLE = {\n version: 8,\n sources: {},\n layers: [],\n} as StyleSpecification\n\nconst pointerEvents = {\n mousedown: 'onMouseDown',\n mouseup: 'onMouseUp',\n mouseover: 'onMouseOver',\n mousemove: 'onMouseMove',\n click: 'onClick',\n dblclick: 'onDblClick',\n mouseenter: 'onMouseEnter',\n mouseleave: 'onMouseLeave',\n mouseout: 'onMouseOut',\n contextmenu: 'onContextMenu',\n touchstart: 'onTouchStart',\n touchend: 'onTouchEnd',\n touchmove: 'onTouchMove',\n touchcancel: 'onTouchCancel',\n}\nconst cameraEvents = {\n movestart: 'onMoveStart',\n move: 'onMove',\n moveend: 'onMoveEnd',\n dragstart: 'onDragStart',\n drag: 'onDrag',\n dragend: 'onDragEnd',\n zoomstart: 'onZoomStart',\n zoom: 'onZoom',\n zoomend: 'onZoomEnd',\n rotatestart: 'onRotateStart',\n rotate: 'onRotate',\n rotateend: 'onRotateEnd',\n pitchstart: 'onPitchStart',\n pitch: 'onPitch',\n pitchend: 'onPitchEnd',\n}\nconst otherEvents = {\n wheel: 'onWheel',\n boxzoomstart: 'onBoxZoomStart',\n boxzoomend: 'onBoxZoomEnd',\n boxzoomcancel: 'onBoxZoomCancel',\n resize: 'onResize',\n load: 'onLoad',\n render: 'onRender',\n idle: 'onIdle',\n remove: 'onRemove',\n data: 'onData',\n styledata: 'onStyleData',\n sourcedata: 'onSourceData',\n error: 'onError',\n}\nconst settingNames = [\n 'minZoom',\n 'maxZoom',\n 'minPitch',\n 'maxPitch',\n 'maxBounds',\n 'projection',\n 'renderWorldCopies',\n]\nconst handlerNames = [\n 'scrollZoom',\n 'boxZoom',\n 'dragRotate',\n 'dragPan',\n 'keyboard',\n 'doubleClickZoom',\n 'touchZoomRotate',\n 'touchPitch',\n]\n\n/**\n * A wrapper for mapbox-gl's Map class\n */\n\nexport default class Maplibre {\n private _MapClass: { new (options: unknown): MapInstance }\n // mapboxgl.Map instance\n private _map: MapInstance = null\n // User-supplied props\n props: MaplibreProps\n\n // Internal states\n private _internalUpdate: boolean = false\n private _hoveredFeatures: MapGeoJSONFeature[] = null\n private _propsedCameraUpdate: ViewState | null = null\n // Suppresses repeated queryRenderedFeatures warnings while the style loads\n private _warnedQueryFeatures: boolean = false\n private _styleComponents: {\n light?: LightSpecification\n sky?: SkySpecification\n projection?: ProjectionSpecification\n terrain?: TerrainSpecification | null\n } = {}\n\n static savedMaps: Maplibre[] = []\n\n constructor(\n MapClass: { new (options: unknown): MapInstance },\n props: MaplibreProps,\n container: HTMLDivElement\n ) {\n this._MapClass = MapClass\n this.props = props\n this._initialize(container)\n }\n\n get map(): MapInstance {\n return this._map\n }\n\n setProps(props: MaplibreProps) {\n const oldProps = this.props\n this.props = props\n\n const settingsChanged = this._updateSettings(props, oldProps)\n const sizeChanged = this._updateSize(props)\n const viewStateChanged = this._updateViewState(props)\n this._updateStyle(props, oldProps)\n this._updateStyleComponents(props)\n this._updateHandlers(props, oldProps)\n\n // If 1) view state has changed to match props and\n // 2) the props change is not triggered by map events,\n // it's driven by an external state change. Redraw immediately\n if (settingsChanged || sizeChanged || (viewStateChanged && !this._map.isMoving())) {\n this.redraw()\n }\n }\n\n static reuse(props: MaplibreProps, container: HTMLDivElement): Maplibre {\n const that = Maplibre.savedMaps.pop()\n if (!that) {\n return null\n }\n\n const map = that.map\n // When reusing the saved map, we need to reparent the map(canvas) and other child nodes\n // intoto the new container from the props.\n // Step 1: reparenting child nodes from old container to new container\n const oldContainer = map.getContainer()\n container.className = oldContainer.className\n while (oldContainer.childNodes.length > 0) {\n container.appendChild(oldContainer.childNodes[0])\n }\n // Step 2: replace the internal container with new container from the react component\n const mapInternal = map as unknown as MapInternalProperties\n if (mapInternal && '_container' in mapInternal) {\n mapInternal._container = container\n }\n\n // With maplibre-gl as mapLib, map uses ResizeObserver to observe when its container resizes.\n // When reusing the saved map, we need to disconnect the observer and observe the new container.\n // Step 3: telling the ResizeObserver to disconnect and observe the new container\n const resizeObserver = mapInternal?._resizeObserver\n if (\n resizeObserver &&\n typeof resizeObserver.disconnect === 'function' &&\n typeof resizeObserver.observe === 'function'\n ) {\n resizeObserver.disconnect()\n resizeObserver.observe(container)\n }\n\n // Step 4: apply new props\n that.setProps({ ...props, styleDiffing: false })\n map.resize()\n const { initialViewState } = props\n if (initialViewState) {\n if (initialViewState.bounds) {\n map.fitBounds(initialViewState.bounds, {\n ...initialViewState.fitBoundsOptions,\n duration: 0,\n })\n } else {\n that._updateViewState(initialViewState)\n }\n }\n\n // Simulate load event. isStyleLoaded() throws if no style is set\n // (deferred or errored), so guard with a style check first.\n if (map.style && map.isStyleLoaded()) {\n map.fire('load')\n } else {\n map.once('style.load', () => map.fire('load'))\n }\n\n // Force reload\n const mapInternalForUpdate = map as unknown as MapInternalProperties\n if (mapInternalForUpdate && typeof mapInternalForUpdate._update === 'function') {\n mapInternalForUpdate._update()\n }\n return that\n }\n\n private _initialize(container: HTMLDivElement) {\n const { props } = this\n const { mapStyle = DEFAULT_STYLE } = props\n const mapOptions = {\n ...props,\n ...props.initialViewState,\n container,\n style: normalizeStyle(mapStyle),\n }\n\n const viewState = mapOptions.initialViewState || mapOptions.viewState || mapOptions\n Object.assign(mapOptions, {\n center: [viewState.longitude || 0, viewState.latitude || 0],\n zoom: viewState.zoom || 0,\n pitch: viewState.pitch || 0,\n bearing: viewState.bearing || 0,\n })\n\n let savedGetContext: typeof HTMLCanvasElement.prototype.getContext | null = null\n if (props.gl) {\n savedGetContext = HTMLCanvasElement.prototype.getContext\n // Hijack canvas.getContext to return our own WebGLContext.\n // This will be called inside the mapboxgl.Map constructor.\n // @ts-expect-error - temporarily overriding getContext to inject custom WebGL context\n HTMLCanvasElement.prototype.getContext = () => props.gl\n }\n\n let map: MapInstance\n try {\n map = new this._MapClass(mapOptions)\n } finally {\n // Always restore the original getContext — if the constructor threw before\n // calling getContext, every other <canvas> on the page would otherwise stay\n // permanently hijacked.\n if (savedGetContext) {\n HTMLCanvasElement.prototype.getContext = savedGetContext\n }\n }\n // Props that are not part of constructor options\n if (viewState.padding) {\n map.setPadding(viewState.padding)\n }\n if (props.cursor) {\n map.getCanvas().style.cursor = props.cursor\n }\n\n // add listeners\n map.transformCameraUpdate = this._onCameraUpdate\n map.on('style.load', () => {\n // Map style has changed, this would have wiped out all settings from props\n const mapWithProjection = map as unknown as MapWithProjection\n this._styleComponents = {\n light: map.getLight(),\n sky: map.getSky(),\n projection: mapWithProjection.getProjection?.(),\n terrain: map.getTerrain(),\n }\n this._updateStyleComponents(this.props)\n })\n map.on('sourcedata', () => {\n // Some sources have loaded, we may need them to attach terrain\n this._updateStyleComponents(this.props)\n })\n for (const eventName in pointerEvents) {\n map.on(eventName, this._onPointerEvent)\n }\n for (const eventName in cameraEvents) {\n map.on(eventName, this._onCameraEvent)\n }\n for (const eventName in otherEvents) {\n map.on(eventName, this._onEvent)\n }\n this._map = map\n }\n\n recycle() {\n // Clean up unnecessary elements before storing for reuse.\n const container = this.map.getContainer()\n const children = container.querySelector('[mapboxgl-children]')\n children?.remove()\n\n Maplibre.savedMaps.push(this)\n }\n\n destroy() {\n this._map.remove()\n }\n\n // Force redraw the map now. Typically resize() and jumpTo() is reflected in the next\n // render cycle, which is managed by Mapbox's animation loop.\n // This removes the synchronization issue caused by requestAnimationFrame.\n redraw() {\n const map = this._map as unknown as MapInternalProperties\n // map._render will throw error if style does not exist\n // https://github.com/mapbox/mapbox-gl-js/blob/fb9fc316da14e99ff4368f3e4faa3888fb43c513\n // /src/ui/map.js#L1834\n if (map && map.style) {\n if (typeof map._render === 'function') {\n // cancel the scheduled update\n if (map._frame && typeof map._frame.cancel === 'function') {\n map._frame.cancel()\n map._frame = null\n }\n // the order is important - render() may schedule another update\n map._render()\n } else if (typeof this._map.triggerRepaint === 'function') {\n this._map.triggerRepaint()\n }\n }\n }\n\n /* Trigger map resize if size is controlled\n @param {object} nextProps\n @returns {bool} true if size has changed\n */\n private _updateSize(nextProps: MaplibreProps): boolean {\n // Check if size is controlled\n const { viewState } = nextProps\n if (viewState) {\n const map = this._map\n if (viewState.width !== map.transform.width || viewState.height !== map.transform.height) {\n map.resize()\n return true\n }\n }\n return false\n }\n\n // Adapted from map.jumpTo\n /* Update camera to match props\n @param {object} nextProps\n @param {bool} triggerEvents - should fire camera events\n @returns {bool} true if anything is changed\n */\n private _updateViewState(nextProps: MaplibreProps): boolean {\n const map = this._map\n const tr = map.transform\n const isMoving = map.isMoving()\n\n // Avoid manipulating the real transform when interaction/animation is ongoing\n // as it would interfere with Mapbox's handlers\n if (!isMoving) {\n const changes: Record<string, unknown> = applyViewStateToTransform(tr, nextProps)\n if (Object.keys(changes).length > 0) {\n this._internalUpdate = true\n map.jumpTo(changes)\n this._internalUpdate = false\n return true\n }\n }\n\n return false\n }\n\n /* Update camera constraints and projection settings to match props\n @param {object} nextProps\n @param {object} currProps\n @returns {bool} true if anything is changed\n */\n private _updateSettings(nextProps: MaplibreProps, currProps: MaplibreProps): boolean {\n const map = this._map\n let changed = false\n for (const propName of settingNames) {\n if (propName in nextProps && !deepEqual(nextProps[propName], currProps[propName])) {\n changed = true\n const setter = map[`set${propName[0].toUpperCase()}${propName.slice(1)}`]\n setter?.call(map, nextProps[propName])\n }\n }\n return changed\n }\n\n /* Update map style to match props */\n private _updateStyle(nextProps: MaplibreProps, currProps: MaplibreProps): void {\n if (nextProps.cursor !== currProps.cursor) {\n this._map.getCanvas().style.cursor = nextProps.cursor || ''\n }\n if (nextProps.mapStyle !== currProps.mapStyle) {\n const { mapStyle = DEFAULT_STYLE, styleDiffing = true } = nextProps\n const options: Record<string, unknown> = {\n diff: styleDiffing,\n }\n if ('localIdeographFontFamily' in nextProps) {\n // Mapbox specific prop not in maplibre types\n options.localIdeographFontFamily = nextProps.localIdeographFontFamily\n }\n this._map.setStyle(normalizeStyle(mapStyle), options)\n }\n }\n\n /* Update fog, light, projection and terrain to match props\n * These props are special because\n * 1. They can not be applied right away. Certain conditions (style loaded, source loaded, etc.) must be met\n * 2. They can be overwritten by mapStyle\n */\n private _updateStyleComponents({ light, projection, sky, terrain }: MaplibreProps): void {\n const map = this._map\n const currProps = this._styleComponents\n const mapWithProjection = map as unknown as MapWithProjection\n // We can safely manipulate map style once it's loaded.\n // isStyleLoaded() throws when no style is set, so guard explicitly.\n if (map.style && map.isStyleLoaded()) {\n if (light && !deepEqual(light, currProps.light)) {\n currProps.light = light\n map.setLight(light)\n }\n if (\n projection &&\n !deepEqual(projection, currProps.projection) &&\n projection !== currProps.projection?.type\n ) {\n currProps.projection = typeof projection === 'string' ? { type: projection } : projection\n mapWithProjection.setProjection?.(currProps.projection)\n }\n if (sky && !deepEqual(sky, currProps.sky)) {\n currProps.sky = sky\n map.setSky(sky)\n }\n if (terrain !== undefined && !deepEqual(terrain, currProps.terrain)) {\n if (!terrain || map.getSource(terrain.source)) {\n currProps.terrain = terrain\n map.setTerrain(terrain)\n }\n }\n }\n }\n\n /* Update interaction handlers to match props */\n private _updateHandlers(nextProps: MaplibreProps, currProps: MaplibreProps): void {\n const map = this._map\n for (const propName of handlerNames) {\n const newValue = nextProps[propName] ?? true\n const oldValue = currProps[propName] ?? true\n if (!deepEqual(newValue, oldValue)) {\n if (newValue) {\n map[propName].enable(newValue)\n } else {\n map[propName].disable()\n }\n }\n }\n }\n\n private _onEvent = (e: MapEvent) => {\n const handlerName = otherEvents[e.type] as keyof MapCallbacks\n const cb = this.props[handlerName] as ((e: MapEvent) => void) | undefined\n if (cb) {\n cb(e)\n } else if (e.type === 'error') {\n logger.error((e as ErrorEvent).error)\n }\n }\n\n private _onCameraEvent = (e: ViewStateChangeEvent) => {\n if (this._internalUpdate) {\n return\n }\n e.viewState = this._propsedCameraUpdate || transformToViewState(this._map.transform)\n const handlerName = cameraEvents[e.type] as keyof MapCallbacks\n const cb = this.props[handlerName] as ((e: ViewStateChangeEvent) => void) | undefined\n if (cb) {\n cb(e)\n }\n }\n\n private _onCameraUpdate = (tr: TransformLike) => {\n if (this._internalUpdate) {\n return tr\n }\n this._propsedCameraUpdate = transformToViewState(tr)\n return applyViewStateToTransform(tr, this.props) as TransformLike\n }\n\n /** Surface a non-fatal warning via the consumer's onWarning callback,\n * falling back to console.warn when none is provided. */\n private _warn(error: Error) {\n const cb = this.props.onWarning\n if (cb) {\n cb({ type: 'error', target: this._map, originalEvent: null, error })\n } else {\n logger.warn(error)\n }\n }\n\n private _queryRenderedFeatures(point: Point) {\n const map = this._map\n const { interactiveLayerIds = [] } = this.props\n try {\n return map.queryRenderedFeatures(point, {\n layers: interactiveLayerIds.filter(map.getLayer.bind(map)),\n })\n } catch (err) {\n // queryRenderedFeatures runs on the hover hot-path and throws\n // transiently before the style finishes loading. Warn once per\n // instance to avoid console spam, and surface via onWarning if set.\n if (!this._warnedQueryFeatures) {\n this._warnedQueryFeatures = true\n this._warn(err instanceof Error ? err : new Error(String(err)))\n }\n return []\n }\n }\n\n private _updateHover(e: MapMouseEvent) {\n const { props } = this\n const shouldTrackHoveredFeatures =\n props.interactiveLayerIds && (props.onMouseMove || props.onMouseEnter || props.onMouseLeave)\n\n if (shouldTrackHoveredFeatures) {\n const eventType = e.type\n const wasHovering = this._hoveredFeatures?.length > 0\n const features = this._queryRenderedFeatures(e.point)\n const isHovering = features.length > 0\n\n if (!isHovering && wasHovering) {\n e.type = 'mouseleave'\n this._onPointerEvent(e)\n }\n this._hoveredFeatures = features\n if (isHovering && !wasHovering) {\n e.type = 'mouseenter'\n this._onPointerEvent(e)\n }\n e.type = eventType\n } else {\n this._hoveredFeatures = null\n }\n }\n\n private _onPointerEvent = (e: MapMouseEvent) => {\n if (e.type === 'mousemove' || e.type === 'mouseout') {\n this._updateHover(e)\n }\n\n const handlerName = pointerEvents[e.type as keyof typeof pointerEvents] as keyof MapCallbacks\n const cb = this.props[handlerName] as ((e: MapMouseEvent) => void) | undefined\n if (cb) {\n if (this.props.interactiveLayerIds && e.type !== 'mouseover' && e.type !== 'mouseout') {\n e.features = this._hoveredFeatures || this._queryRenderedFeatures(e.point)\n }\n cb(e)\n delete e.features\n }\n }\n}\n","import type { Map as MapInstance } from '../types/lib'\nimport type Maplibre from './maplibre'\n\n/** These methods may break the react binding if called directly */\nconst skipMethods = [\n 'setMaxBounds',\n 'setMinZoom',\n 'setMaxZoom',\n 'setMinPitch',\n 'setMaxPitch',\n 'setRenderWorldCopies',\n 'setProjection',\n 'setStyle',\n 'addSource',\n 'removeSource',\n 'addLayer',\n 'removeLayer',\n 'setLayerZoomRange',\n 'setFilter',\n 'setPaintProperty',\n 'setLayoutProperty',\n 'setLight',\n 'setTerrain',\n 'setFog',\n 'remove',\n] as const\n\nexport type MapRef = {\n getMap(): MapInstance\n} & Omit<MapInstance, (typeof skipMethods)[number]>\n\nexport default function createRef(mapInstance: Maplibre): MapRef | null {\n if (!mapInstance) {\n return null\n }\n\n const map = mapInstance.map\n\n const result: any = {\n getMap: () => map,\n }\n\n for (const key of getMethodNames(map)) {\n // @ts-expect-error - dynamically binding map methods to result object\n if (!(key in result) && !skipMethods.includes(key)) {\n result[key] = map[key].bind(map)\n }\n }\n\n return result\n}\n\nfunction getMethodNames(obj: object) {\n const result = new Set<string>()\n\n let proto = obj\n while (proto) {\n for (const key of Object.getOwnPropertyNames(proto)) {\n if (\n key[0] !== '_' &&\n typeof obj[key] === 'function' &&\n key !== 'fire' &&\n key !== 'setEventedParent'\n ) {\n result.add(key)\n }\n }\n proto = Object.getPrototypeOf(proto)\n }\n return Array.from(result)\n}\n","// From https://github.com/streamich/react-use/blob/master/src/useIsomorphicLayoutEffect.ts\n// useLayoutEffect but does not trigger warning in server-side rendering\nimport { useEffect, useLayoutEffect } from 'react'\n\nconst useIsomorphicLayoutEffect = typeof document !== 'undefined' ? useLayoutEffect : useEffect\n\nexport default useIsomorphicLayoutEffect\n","import type { MapLib } from '../types/lib'\nimport { logger } from './logger'\n\nexport type GlobalSettings = {\n /** The maximum number of images (raster tiles, sprites, icons) to load in parallel.\n * @default 16\n */\n maxParallelImageRequests?: number\n /** The map's RTL text plugin. Necessary for supporting the Arabic and Hebrew languages, which are written right-to-left. */\n RTLTextPlugin?: string | { pluginUrl: string; lazy?: boolean }\n /** The number of web workers instantiated on a page with maplibre-gl maps.\n * @default 2\n */\n workerCount?: number\n /** Provides an interface for loading maplibre-gl's WebWorker bundle from a self-hosted URL.\n * This is useful if your site needs to operate in a strict CSP (Content Security Policy) environment\n * wherein you are not allowed to load JavaScript code from a Blob URL, which is default behavior. */\n workerUrl?: string\n}\n\n/**\n * Validates that a URL uses a safe protocol (http/https)\n */\nconst validateUrl = (url: string, settingName: string): boolean => {\n try {\n const parsed = new URL(url)\n if (!['http:', 'https:'].includes(parsed.protocol)) {\n logger.warn(`${settingName}: Only http/https protocols are allowed, got: ${parsed.protocol}`)\n return false\n }\n return true\n } catch {\n logger.warn(`${settingName}: Invalid URL format: ${url}`)\n return false\n }\n}\n\n/**\n * The `mapLib` argument augmented with the module-level global setters it uses.\n * These exist on both mapbox-gl and maplibre-gl but are intentionally omitted\n * from the shared `MapLib` interface, so they are declared optional here and\n * invoked with optional chaining at the call sites.\n */\ntype GlobalSettingsMapLib = MapLib & {\n getRTLTextPluginStatus?: () => string\n setRTLTextPlugin?: (pluginUrl: string, callback: (error?: Error) => void, lazy: boolean) => void\n setMaxParallelImageRequests?: (count: number) => void\n setWorkerCount?: (count: number) => void\n setWorkerUrl?: (url: string) => void\n}\n\nexport default function setGlobals(mapLib: GlobalSettingsMapLib, props: GlobalSettings) {\n const { RTLTextPlugin, maxParallelImageRequests, workerCount, workerUrl } = props\n if (\n RTLTextPlugin &&\n mapLib.getRTLTextPluginStatus &&\n mapLib.getRTLTextPluginStatus() === 'unavailable'\n ) {\n const { pluginUrl, lazy = true } =\n typeof RTLTextPlugin === 'string' ? { pluginUrl: RTLTextPlugin } : RTLTextPlugin\n\n if (validateUrl(pluginUrl, 'RTLTextPlugin')) {\n if (typeof mapLib.setRTLTextPlugin !== 'function') {\n logger.warn(\n `RTLTextPlugin was configured but the provided mapLib does not expose setRTLTextPlugin. Right-to-left scripts (Arabic, Hebrew) will not render correctly.`\n )\n } else {\n mapLib.setRTLTextPlugin(\n pluginUrl,\n (error?: Error) => {\n if (error) {\n logger.error(error)\n }\n },\n lazy\n )\n }\n }\n }\n if (maxParallelImageRequests !== undefined) {\n mapLib.setMaxParallelImageRequests?.(maxParallelImageRequests)\n }\n if (workerCount !== undefined) {\n mapLib.setWorkerCount?.(workerCount)\n }\n if (workerUrl !== undefined) {\n if (validateUrl(workerUrl, 'workerUrl')) {\n mapLib.setWorkerUrl?.(workerUrl)\n }\n }\n}\n","import * as React from 'react'\nimport { useEffect, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type {\n ControlPosition,\n LogoControlOptions,\n IControl,\n Map as MaplibreMap,\n} from '../types/lib'\n\nexport type LogoControlProps = LogoControlOptions & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _LogoControl(props: LogoControlProps) {\n // Create custom control\n const ctrl = useControl(\n () => {\n const control: IControl & { _container?: HTMLElement } = {\n onAdd: (map: MaplibreMap): HTMLElement => {\n // Check if logo already exists\n if (map.getContainer) {\n const existingLogo = map\n .getContainer()\n .querySelector('a.maplibregl-ctrl-logo[href=\"https://www.barikoi.com\"]')\n if (existingLogo) {\n existingLogo.remove()\n }\n }\n\n const container = document.createElement('a')\n container.className = 'maplibregl-ctrl-logo'\n container.href = 'https://www.barikoi.com'\n container.target = '_blank'\n container.setAttribute('alt', 'Barikoi')\n container.setAttribute('aria-label', 'Barikoi logo')\n container.setAttribute('rel', 'noopener nofollow')\n control._container = container\n return container\n },\n onRemove: (): void => {\n delete control._container\n },\n }\n return control\n },\n { position: props.position }\n )\n\n useEffect(() => {\n applyReactStyle(ctrl._container, props.style)\n }, [props.style, ctrl._container])\n\n return null\n}\n\nexport const LogoControl: React.FC<LogoControlProps> = memo(_LogoControl)\n","import * as React from 'react'\n// This is a simplified version of\n// https://github.com/facebook/react/blob/4131af3e4bf52f3a003537ec95a1655147c81270/src/renderers/dom/shared/CSSPropertyOperations.js#L62\nconst unitlessNumber = /box|flex|grid|column|lineHeight|fontWeight|opacity|order|tabSize|zIndex/\n\nexport function applyReactStyle(element: HTMLElement, styles: React.CSSProperties) {\n if (!element || !styles) {\n return\n }\n const style = element.style\n\n for (const key in styles) {\n const value = styles[key]\n if (Number.isFinite(value) && !unitlessNumber.test(key)) {\n style[key] = `${value}px`\n } else {\n style[key] = value\n }\n }\n}\n","import { useContext, useMemo, useEffect } from 'react'\nimport type { IControl, ControlPosition, MapControl } from '../types/lib'\nimport { MapContext } from './map'\nimport type { MapContextValue } from './map'\n\ntype ControlOptions = {\n position?: ControlPosition\n}\n\nexport function useControl<T extends MapControl>(\n onCreate: (context: MapContextValue) => T,\n opts?: ControlOptions\n): T\n\nexport function useControl<T extends MapControl>(\n onCreate: (context: MapContextValue) => T,\n onRemove: (context: MapContextValue) => void,\n opts?: ControlOptions\n): T\n\nexport function useControl<T extends MapControl>(\n onCreate: (context: MapContextValue) => T,\n onAdd: (context: MapContextValue) => void,\n onRemove: (context: MapContextValue) => void,\n opts?: ControlOptions\n): T\n\nexport function useControl<T extends MapControl>(\n onCreate: (context: MapContextValue) => T,\n arg1?: ((context: MapContextValue) => void) | ControlOptions,\n arg2?: ((context: MapContextValue) => void) | ControlOptions,\n arg3?: ControlOptions\n): T {\n const context = useContext(MapContext)\n\n if (!context) {\n throw new Error('useControl must be used within a Map component')\n }\n\n const ctrl = useMemo(() => onCreate(context), [])\n\n useEffect(() => {\n const opts = (arg3 || arg2 || arg1) as ControlOptions\n const onAdd = typeof arg1 === 'function' && typeof arg2 === 'function' ? arg1 : null\n const onRemove = typeof arg2 === 'function' ? arg2 : typeof arg1 === 'function' ? arg1 : null\n\n const { map } = context\n const ctrlAsIControl = ctrl as unknown as IControl\n if (!map.hasControl(ctrlAsIControl)) {\n map.addControl(ctrlAsIControl, opts?.position)\n if (onAdd) {\n onAdd(context)\n }\n }\n\n return () => {\n if (onRemove) {\n onRemove(context)\n }\n // Map might have been removed (parent effects are destroyed before child ones)\n if (map.hasControl(ctrlAsIControl)) {\n map.removeControl(ctrlAsIControl)\n }\n }\n }, [])\n\n return ctrl\n}\n","import * as React from 'react'\nimport { useEffect, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\nimport { useMap } from './use-map'\nimport { logger } from '../utils/logger'\n\nimport type { ControlPosition, AttributionControlOptions } from '../types/lib'\n\nexport type AttributionControlProps = AttributionControlOptions & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _AttributionControl(props: AttributionControlProps) {\n const { current: map } = useMap()\n\n const ctrl = useControl(\n ({ mapLib }) =>\n new mapLib.AttributionControl({\n compact: true,\n ...props,\n }),\n { position: props.position }\n )\n\n useEffect(() => {\n applyReactStyle(ctrl._container, props.style)\n\n if (!ctrl._container || !map) return\n\n const onLoad = () => {\n setTimeout(() => {\n const inner = ctrl._container.querySelector('.maplibregl-ctrl-attrib-inner')\n\n if (inner instanceof HTMLElement) {\n // Use DOM APIs instead of innerHTML for security\n inner.textContent = ''\n\n const createLink = (text: string, href: string) => {\n const a = document.createElement('a')\n a.href = href\n a.target = '_blank'\n a.rel = 'noopener noreferrer'\n a.textContent = text\n return a\n }\n\n inner.appendChild(createLink('Barikoi', 'https://barikoi.com'))\n inner.appendChild(document.createTextNode(' © '))\n inner.appendChild(createLink('OpenMapTiles', 'https://openmaptiles.org'))\n inner.appendChild(document.createTextNode(' © '))\n inner.appendChild(\n createLink('OpenStreetMap contributors', 'https://www.openstreetmap.org/copyright')\n )\n } else {\n logger.warn(\n 'AttributionControl: .maplibregl-ctrl-attrib-inner element not found in control container. Legally-required attribution styling was not applied.'\n )\n }\n }, 0)\n }\n\n if (map.loaded()) {\n onLoad()\n } else {\n map.once('load', onLoad)\n }\n\n return () => {\n map.off('load', onLoad)\n }\n }, [props.style, ctrl._container, map])\n\n return null\n}\n\nexport const AttributionControl: React.FC<AttributionControlProps> = memo(_AttributionControl)\n","/* global document */\nimport * as React from 'react'\nimport { createPortal } from 'react-dom'\nimport {\n useImperativeHandle,\n useEffect,\n useMemo,\n useRef,\n useContext,\n forwardRef,\n memo,\n} from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\n\nimport type { Popup as PopupInstance, Marker as MarkerInstance, MarkerOptions } from '../types/lib'\nimport type { MarkerEvent, MarkerDragEvent } from '../types/events'\n\nimport { MapContext } from './map'\nimport { arePointsEqual } from '../utils/deep-equal'\nimport { compareClassNames } from '../utils/compare-class-names'\n\nexport type MarkerProps = MarkerOptions & {\n /** Longitude of the anchor location */\n longitude: number\n /** Latitude of the anchor location */\n latitude: number\n\n popup?: PopupInstance\n\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n onClick?: (e: MarkerEvent<MouseEvent>) => void\n onDragStart?: (e: MarkerDragEvent) => void\n onDrag?: (e: MarkerDragEvent) => void\n onDragEnd?: (e: MarkerDragEvent) => void\n children?: React.ReactNode\n}\n\nexport const Marker: React.FC<MarkerProps> = memo(\n forwardRef((props: MarkerProps, ref: React.Ref<MarkerInstance>) => {\n const { map, mapLib } = useContext(MapContext)\n const callbackRef = useRef<{\n onClick?: MarkerProps['onClick']\n onDragStart?: MarkerProps['onDragStart']\n onDrag?: MarkerProps['onDrag']\n onDragEnd?: MarkerProps['onDragEnd']\n }>({})\n\n const marker: MarkerInstance = useMemo(() => {\n let hasChildren = false\n React.Children.forEach(props.children, el => {\n if (el) {\n hasChildren = true\n }\n })\n const options = {\n ...props,\n element: hasChildren ? document.createElement('div') : undefined,\n }\n\n const mk = new mapLib.Marker(options)\n mk.setLngLat([props.longitude, props.latitude])\n\n return mk\n }, [])\n\n useEffect(() => {\n callbackRef.current = {\n onClick: props.onClick,\n onDragStart: props.onDragStart,\n onDrag: props.onDrag,\n onDragEnd: props.onDragEnd,\n }\n })\n\n useEffect(() => {\n const clickHandler = (e: MouseEvent) => {\n callbackRef.current.onClick?.({\n type: 'click',\n target: marker,\n originalEvent: e,\n })\n }\n\n marker.getElement().addEventListener('click', clickHandler)\n\n const dragStartHandler = (e: MarkerDragEvent) => {\n e.lngLat = marker.getLngLat()\n callbackRef.current.onDragStart?.(e)\n }\n\n const dragHandler = (e: MarkerDragEvent) => {\n e.lngLat = marker.getLngLat()\n callbackRef.current.onDrag?.(e)\n }\n\n const dragEndHandler = (e: MarkerDragEvent) => {\n e.lngLat = marker.getLngLat()\n callbackRef.current.onDragEnd?.(e)\n }\n\n marker.on('dragstart', dragStartHandler)\n marker.on('drag', dragHandler)\n marker.on('dragend', dragEndHandler)\n\n marker.addTo(map.getMap())\n\n return () => {\n marker.getElement().removeEventListener('click', clickHandler)\n marker.off('dragstart', dragStartHandler)\n marker.off('drag', dragHandler)\n marker.off('dragend', dragEndHandler)\n marker.remove()\n }\n }, [])\n\n const {\n longitude,\n latitude,\n offset,\n style,\n draggable = false,\n popup = null,\n rotation = 0,\n rotationAlignment = 'auto',\n pitchAlignment = 'auto',\n className,\n } = props\n\n useEffect(() => {\n applyReactStyle(marker.getElement(), style)\n }, [style])\n\n useImperativeHandle(ref, () => marker, [])\n\n const prevClassNameRef = useRef(className)\n\n // Intentionally no dependency array - we need to update marker properties on every render\n // to ensure they reflect the latest props. This avoids stale prop issues and is safe\n // because the marker's setter methods are idempotent.\n useEffect(() => {\n if (marker.getLngLat().lng !== longitude || marker.getLngLat().lat !== latitude) {\n marker.setLngLat([longitude, latitude])\n }\n if (offset && !arePointsEqual(marker.getOffset(), offset)) {\n marker.setOffset(offset)\n }\n if (marker.isDraggable() !== draggable) {\n marker.setDraggable(draggable)\n }\n if (marker.getRotation() !== rotation) {\n marker.setRotation(rotation)\n }\n if (marker.getRotationAlignment() !== rotationAlignment) {\n marker.setRotationAlignment(rotationAlignment)\n }\n if (marker.getPitchAlignment() !== pitchAlignment) {\n marker.setPitchAlignment(pitchAlignment)\n }\n if (marker.getPopup() !== popup) {\n marker.setPopup(popup)\n }\n const classNameDiff = compareClassNames(prevClassNameRef.current, className)\n if (classNameDiff) {\n for (const c of classNameDiff) {\n marker.toggleClassName(c)\n }\n }\n prevClassNameRef.current = className\n })\n\n return createPortal(props.children, marker.getElement())\n })\n)\n","/** Compare two classNames string and return the difference */\nexport function compareClassNames(\n prevClassName: string | undefined,\n nextClassName: string | undefined\n): string[] | null {\n if (prevClassName === nextClassName) {\n return null\n }\n\n const prevClassList = getClassList(prevClassName)\n const nextClassList = getClassList(nextClassName)\n const diff: string[] = []\n\n for (const c of nextClassList) {\n if (!prevClassList.has(c)) {\n diff.push(c)\n }\n }\n for (const c of prevClassList) {\n if (!nextClassList.has(c)) {\n diff.push(c)\n }\n }\n return diff.length === 0 ? null : diff\n}\n\nfunction getClassList(className: string | undefined) {\n return new Set(className ? className.trim().split(/\\s+/) : [])\n}\n","/* global document */\nimport * as React from 'react'\nimport { createPortal } from 'react-dom'\nimport { useImperativeHandle, useEffect, useMemo, useContext, forwardRef, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\n\nimport type { Popup as PopupInstance, PopupOptions, MapMouseEventBase } from '../types/lib'\nimport type { PopupEvent } from '../types/events'\n\nimport { MapContext } from './map'\nimport { compareClassNames } from '../utils/compare-class-names'\n\nexport type PopupProps = PopupOptions & {\n /** Longitude of the anchor location */\n longitude: number\n /** Latitude of the anchor location */\n latitude: number\n\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n\n onOpen?: (e: PopupEvent) => void\n onClose?: (e: PopupEvent) => void\n children?: React.ReactNode\n}\n\nexport const Popup: React.FC<PopupProps> = memo(\n forwardRef((props: PopupProps, ref: React.Ref<PopupInstance>) => {\n const { map, mapLib } = useContext(MapContext)\n const container = useMemo(() => {\n return document.createElement('div')\n }, [])\n\n const popup: PopupInstance = useMemo(() => {\n const options = { ...props }\n const pp = new mapLib.Popup(options)\n pp.setLngLat([props.longitude, props.latitude])\n return pp\n }, [])\n\n useImperativeHandle(ref, () => popup, [])\n\n useEffect(() => {\n const onOpen = (e: MapMouseEventBase) => {\n props.onOpen?.(e as unknown as PopupEvent)\n }\n const onClose = (e: MapMouseEventBase) => {\n props.onClose?.(e as unknown as PopupEvent)\n }\n popup.on('open', onOpen)\n popup.on('close', onClose)\n popup.setDOMContent(container).addTo(map.getMap())\n\n return () => {\n // https://github.com/visgl/react-map-gl/issues/1825\n // onClose should not be fired if the popup is removed by unmounting\n // When using React strict mode, the component is mounted twice.\n // Firing the onClose callback here would be a false signal to remove the component.\n popup.off('open', onOpen)\n popup.off('close', onClose)\n if (popup.isOpen()) {\n popup.remove()\n }\n }\n }, [])\n\n useEffect(() => {\n applyReactStyle(popup.getElement(), props.style)\n }, [props.style])\n\n useEffect(() => {\n if (popup.isOpen()) {\n if (popup.getLngLat().lng !== props.longitude || popup.getLngLat().lat !== props.latitude) {\n popup.setLngLat([props.longitude, props.latitude])\n }\n }\n }, [props.longitude, props.latitude])\n\n useEffect(() => {\n if (popup.isOpen() && props.offset) {\n popup.setOffset(props.offset)\n }\n }, [props.offset])\n\n useEffect(() => {\n if (popup.isOpen() && props.maxWidth !== undefined) {\n popup.setMaxWidth(props.maxWidth)\n }\n }, [props.maxWidth])\n\n useEffect(() => {\n if (popup.isOpen() && props.className) {\n const currentClassName = popup.options.className || ''\n const classNameDiff = compareClassNames(currentClassName, props.className)\n if (classNameDiff) {\n for (const c of classNameDiff) {\n popup.toggleClassName(c)\n }\n }\n }\n }, [props.className])\n\n return createPortal(props.children, container)\n })\n)\n","/* global document */\nimport * as React from 'react'\nimport { useEffect, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type { ControlPosition, FullscreenControlOptions } from '../types/lib'\n\nexport type FullscreenControlProps = Omit<FullscreenControlOptions, 'container'> & {\n /** Id of the DOM element which should be made full screen. By default, the map container\n * element will be made full screen. */\n containerId?: string\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _FullscreenControl(props: FullscreenControlProps) {\n const ctrl = useControl(\n ({ mapLib }) =>\n new mapLib.FullscreenControl({\n container: props.containerId && document.getElementById(props.containerId),\n }),\n { position: props.position }\n )\n\n useEffect(() => {\n applyReactStyle(ctrl._controlContainer, props.style)\n }, [props.style])\n\n return null\n}\n\nexport const FullscreenControl: React.FC<FullscreenControlProps> = memo(_FullscreenControl)\n","import * as React from 'react'\nimport { useImperativeHandle, useRef, useEffect, forwardRef, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type {\n ControlPosition,\n GeolocateControl as GeolocateControlInstance,\n GeolocateControlOptions,\n} from '../types/lib'\nimport type { GeolocateEvent, GeolocateResultEvent, GeolocateErrorEvent } from '../types/events'\n\nexport type GeolocateControlProps = GeolocateControlOptions & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n\n /** Called on each Geolocation API position update that returned as success. */\n onGeolocate?: (e: GeolocateResultEvent) => void\n /** Called on each Geolocation API position update that returned as an error. */\n onError?: (e: GeolocateErrorEvent) => void\n /** Called on each Geolocation API position update that returned as success but user position\n * is out of map `maxBounds`. */\n onOutOfMaxBounds?: (e: GeolocateResultEvent) => void\n /** Called when the GeolocateControl changes to the active lock state. */\n onTrackUserLocationStart?: (e: GeolocateEvent) => void\n /** Called when the GeolocateControl changes to the background state. */\n onTrackUserLocationEnd?: (e: GeolocateEvent) => void\n}\n\nfunction _GeolocateControl(props: GeolocateControlProps, ref: React.Ref<GeolocateControlInstance>) {\n const thisRef = useRef({ props })\n\n const ctrl = useControl(\n ({ mapLib }) => {\n const gc = new mapLib.GeolocateControl(props)\n\n // Hack: fix GeolocateControl reuse\n // When using React strict mode, the component is mounted twice.\n // GeolocateControl's UI creation is asynchronous. Removing and adding it back causes the UI to be initialized twice.\n const setupUI = gc._setupUI\n gc._setupUI = () => {\n if (!gc._container.hasChildNodes()) {\n setupUI()\n }\n }\n\n gc.on('geolocate', e => {\n thisRef.current.props.onGeolocate?.(e as GeolocateResultEvent)\n })\n gc.on('error', e => {\n thisRef.current.props.onError?.(e as GeolocateErrorEvent)\n })\n gc.on('outofmaxbounds', e => {\n thisRef.current.props.onOutOfMaxBounds?.(e as GeolocateResultEvent)\n })\n gc.on('trackuserlocationstart', e => {\n thisRef.current.props.onTrackUserLocationStart?.(e as GeolocateEvent)\n })\n gc.on('trackuserlocationend', e => {\n thisRef.current.props.onTrackUserLocationEnd?.(e as GeolocateEvent)\n })\n\n return gc\n },\n { position: props.position }\n )\n\n thisRef.current.props = props\n\n useImperativeHandle(ref, () => ctrl, [])\n\n useEffect(() => {\n applyReactStyle(ctrl._container, props.style)\n }, [props.style])\n\n return null\n}\n\nexport const GeolocateControl: React.FC<GeolocateControlProps> = memo(forwardRef(_GeolocateControl))\n","import * as React from 'react'\nimport { useEffect, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type { ControlPosition, NavigationControlOptions } from '../types/lib'\n\nexport type NavigationControlProps = NavigationControlOptions & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _NavigationControl(props: NavigationControlProps) {\n const ctrl = useControl(({ mapLib }) => new mapLib.NavigationControl(props), {\n position: props.position,\n })\n\n useEffect(() => {\n applyReactStyle(ctrl._container, props.style)\n }, [props.style])\n\n return null\n}\n\nexport const NavigationControl: React.FC<NavigationControlProps> = memo(_NavigationControl)\n","import * as React from 'react'\nimport { useEffect, useRef, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type { ControlPosition, ScaleControlOptions } from '../types/lib'\n\nexport type ScaleControlProps = ScaleControlOptions & {\n // These props will be further constraint by OptionsT\n unit?: string\n maxWidth?: number\n\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _ScaleControl(props: ScaleControlProps) {\n const ctrl = useControl(({ mapLib }) => new mapLib.ScaleControl(props), {\n position: props.position,\n })\n const propsRef = useRef<ScaleControlProps>(props)\n\n const prevProps = propsRef.current\n propsRef.current = props\n\n const { style, maxWidth, unit } = props\n\n // Move prop updates to useEffect to avoid render-phase side effects\n useEffect(() => {\n if (maxWidth !== undefined && maxWidth !== prevProps.maxWidth) {\n ctrl.options.maxWidth = maxWidth\n }\n if (unit !== undefined && unit !== prevProps.unit) {\n ctrl.setUnit(unit)\n }\n }, [ctrl, maxWidth, unit, prevProps.maxWidth, prevProps.unit])\n\n useEffect(() => {\n applyReactStyle(ctrl._container, style)\n }, [ctrl, style])\n\n return null\n}\n\nexport const ScaleControl: React.FC<ScaleControlProps> = memo(_ScaleControl)\n","import * as React from 'react'\nimport { useEffect, memo } from 'react'\nimport { applyReactStyle } from '../utils/apply-react-style'\nimport { useControl } from './use-control'\n\nimport type { ControlPosition } from '../types/lib'\nimport type { TerrainSpecification } from '../types/style-spec'\n\nexport type TerrainControlProps = TerrainSpecification & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n}\n\nfunction _TerrainControl(props: TerrainControlProps) {\n const ctrl = useControl(({ mapLib }) => new mapLib.TerrainControl(props), {\n position: props.position,\n })\n\n useEffect(() => {\n applyReactStyle(ctrl._container, props.style)\n }, [props.style])\n\n return null\n}\n\nexport const TerrainControl: React.FC<TerrainControlProps> = memo(_TerrainControl)\n","/**\n * @fileoverview Source component for adding data sources to a MapLibre GL map.\n *\n * Sources define the data that layers can render. This component supports all\n * MapLibre GL source types including GeoJSON, vector tiles, raster tiles. image. and video.\n *\n * @module components/source\n * @see {@link https://maplibre.org/maplibre-gl-js/docs/sources/}\n */\n\nimport * as React from 'react'\nimport {\n useContext,\n useEffect,\n useMemo,\n useState,\n useRef,\n cloneElement,\n memo,\n useId,\n useImperativeHandle,\n} from 'react'\nimport { MapContext } from './map'\nimport assert from '../utils/assert'\nimport { deepEqual } from '../utils/deep-equal'\nimport { emitWarning } from '../utils/warn'\n\nimport type {\n GeoJSONSourceImplementation,\n ImageSourceImplementation,\n AnySourceImplementation,\n MapInternalProperties,\n SourceWithOptionalMethods,\n LayerWithSource,\n} from '../types/internal'\nimport type { SourceSpecification } from '../types/style-spec'\nimport type { Map as MapInstance } from '../types/lib'\nimport type { ErrorEvent } from '../types/events'\n\n/**\n * Props for the Source component.\n *\n * @typedef {Object} SourceProps\n * @property {string} [id] - Unique identifier for the source. If not provided. one will be generated automatically.\n * @property {React.ReactNode} [children] - Child Layer components that will use this source.\n * @extends {SourceSpecification}\n *\n * @example\n * ```tsx\n * // GeoJSON source with a layer\n * <Source id=\"my-data\" type=\"geojson\" data={geojsonData}>\n * <Layer id=\"points-layer\" type=\"circle\" paint={{ 'circle-radius': 8 }} />\n * </Source>\n *\n * // Vector tile source\n * <Source id=\"streets\" type=\"vector\" url=\"mapbox://streets-v11\" />\n *\n * // Raster source\n * <Source id=\"satellite\" type=\"raster\" tiles={['https://example.com/tiles/{z}/{x}/{y}.png']} tileSize={256} />\n * ```\n */\nexport type SourceProps = SourceSpecification & {\n /** Unique identifier for the source. If not provided. one will be generated automatically. */\n id?: string\n\n /** Child Layer components that will use this source. */\n children?: any\n}\n\n/**\n * Creates a new source on the map.\n *\n * @param {MapInstance} map - The MapLibre GL map instance\n * @param {string} id - Unique identifier for the source\n * @param {SourceProps} props - Source properties\n * @returns {AnySourceImplementation | null} The created source or null if style not loaded\n * @private\n */\nfunction createSource(\n map: MapInstance,\n id: string,\n props: SourceProps\n): AnySourceImplementation | null {\n const mapInternal = map as unknown as MapInternalProperties\n if (mapInternal.style && mapInternal.style._loaded) {\n const options = { ...props }\n delete options.id\n delete options.children\n map.addSource(id, options as SourceSpecification)\n return map.getSource(id)\n }\n return null\n}\n\n/**\n * Updates an existing source with new properties.\n *\n * Handles updates for different source types:\n * - GeoJSON sources: updates data via setData()\n * - Image sources: updates via updateImage()\n * - Other sources: uses optional setCoordinates. setUrl. or setTiles methods\n *\n * @param {AnySourceImplementation} source - The source to update\n * @param {SourceProps} props - New properties\n * @param {SourceProps} prevProps - Previous properties\n * @throws {Error} If source id or type changes\n * @private\n */\nfunction updateSource(\n source: AnySourceImplementation,\n props: SourceProps,\n prevProps: SourceProps,\n onWarning?: (e: ErrorEvent) => void\n): void {\n assert(props.id === prevProps.id, 'source id changed')\n assert(props.type === prevProps.type, 'source type changed')\n\n let changedKey = ''\n let changedKeyCount = 0\n\n for (const key in props) {\n if (\n key !== 'children' &&\n key !== 'id' &&\n Object.prototype.hasOwnProperty.call(props, key) &&\n !deepEqual(prevProps[key], props[key])\n ) {\n changedKey = key\n changedKeyCount++\n }\n }\n\n if (!changedKeyCount) {\n return\n }\n\n const type = props.type\n\n if (type === 'geojson') {\n ;(source as GeoJSONSourceImplementation).setData(props.data)\n } else if (type === 'image') {\n ;(source as ImageSourceImplementation).updateImage({\n url: props.url,\n coordinates: props.coordinates,\n })\n } else {\n const sourceWithMethods = source as unknown as SourceWithOptionalMethods\n const propsWithOptional = props as Record<string, unknown>\n switch (changedKey) {\n case 'coordinates':\n sourceWithMethods.setCoordinates?.(propsWithOptional.coordinates)\n break\n case 'url':\n sourceWithMethods.setUrl?.(propsWithOptional.url as string)\n break\n case 'tiles':\n sourceWithMethods.setTiles?.(propsWithOptional.tiles as string[])\n break\n default:\n emitWarning(onWarning, new Error(`Unable to update <Source> prop: ${changedKey}`))\n }\n }\n}\n\n/**\n * Source component for adding data sources to a MapLibre GL map.\n *\n * Sources define the data that layers render. Supports all MapLibre GL source\n * types including GeoJSON. vector tiles. raster tiles. image. and video.\n *\n * @component\n * @example\n * ```tsx\n * // GeoJSON source with a layer\n * <Source id=\"my-data\" type=\"geojson\" data={geojsonData}>\n * <Layer id=\"points-layer\" type=\"circle\" paint={{ 'circle-radius': 8 }} />\n * </Source>\n *\n * // Vector tile source\n * <Source id=\"streets\" type=\"vector\" url=\"mapbox://streets-v11\" />\n *\n * // Raster source\n * <Source id=\"satellite\" type=\"raster\" tiles={['https://example.com/tiles/{z}/{x}/{y}.png']} tileSize={256} />\n *\n * // With ref forwarding\n * const sourceRef = useRef(null);\n * <Source ref={sourceRef} id=\"my-data\" type=\"geojson\" data={data}>\n * <Layer type=\"circle\" />\n * </Source>\n *\n * // Access source methods\n * useEffect(() => {\n * if (sourceRef.current) {\n * sourceRef.current.setData(newData);\n * }\n * }, [newData]);\n * ```\n */\nfunction _Source(props: SourceProps, ref: React.Ref<AnySourceImplementation | null>) {\n const context = useContext(MapContext)\n if (!context) {\n throw new Error('<Source> must be used within a Map component')\n }\n const map = context.map.getMap()\n const propsRef = useRef(props)\n const sourceRef = useRef<AnySourceImplementation | null>(null)\n const [, setStyleLoaded] = useState(0)\n\n // Generate a stable ID once on mount\n // Note: props.id changes after mount will trigger an error in updateSource\n const generatedId = useId()\n const id = useMemo(\n () => props.id || `jsx-source-${generatedId.replace(/:/g, '-')}`,\n // Empty deps - id is set once on mount and should not change\n []\n )\n\n useEffect(() => {\n if (map) {\n /* global setTimeout */\n const forceUpdate = () => setTimeout(() => setStyleLoaded(version => version + 1), 0)\n map.on('styledata', forceUpdate)\n forceUpdate()\n\n return () => {\n map.off('styledata', forceUpdate)\n const mapInternal = map as unknown as MapInternalProperties\n if (mapInternal.style && mapInternal.style._loaded && map.getSource(id)) {\n // Parent effects are destroyed before child ones. see\n // https://github.com/facebook/react/issues/16728\n // Source can only be removed after all child layers are removed\n const allLayers = map.getStyle()?.layers\n if (allLayers) {\n for (const layer of allLayers) {\n const layerWithSource = layer as unknown as LayerWithSource\n if (layerWithSource.source === id) {\n map.removeLayer(layer.id)\n }\n }\n }\n map.removeSource(id)\n }\n }\n }\n return undefined\n }, [map])\n\n const mapInternal = map as unknown as MapInternalProperties\n let source = map && mapInternal.style && map.getSource(id)\n if (source) {\n updateSource(source, props, propsRef.current, context.onWarning)\n } else {\n source = createSource(map, id, props)\n }\n\n // Update source ref for imperative handle\n sourceRef.current = source\n propsRef.current = props\n\n // Expose source instance via ref\n useImperativeHandle(ref, () => sourceRef.current, [source])\n\n return (\n (source &&\n React.Children.map(\n props.children,\n child =>\n child &&\n cloneElement(child, {\n source: id,\n })\n )) ||\n null\n )\n}\n\nexport const Source = memo(React.forwardRef(_Source))\n","export default function assert(condition: unknown, message: string) {\n if (!condition) {\n throw new Error(message)\n }\n}\n","import type { ErrorEvent } from '../types/events'\nimport { logger } from './logger'\n\n/**\n * Surface a non-fatal warning. Routes through the consumer's `onWarning`\n * callback when provided, otherwise falls back to `logger.warn`.\n *\n * @param onWarning - The consumer-supplied warning handler (from `<Map>`), if any.\n * @param error - The warning value; coerced to an `Error`.\n * @private\n */\nexport function emitWarning(\n onWarning: ((e: ErrorEvent) => void) | undefined,\n error: unknown\n): void {\n const err = error instanceof Error ? error : new Error(String(error))\n if (onWarning) {\n onWarning({ type: 'error', target: null, originalEvent: null, error: err })\n } else {\n logger.warn(err)\n }\n}\n","/**\n * @fileoverview CanvasSource component for adding canvas-based data sources to a MapLibre GL map.\n *\n * Canvas sources allow rendering custom HTML canvas elements as map layers.\n * This is useful for dynamic, animated, or custom-rendered data overlays.\n *\n * @module components/canvas-source\n * @see {@link https://maplibre.org/maplibre-gl-js/docs/sources/}\n */\n\nimport * as React from 'react'\nimport { useContext, useEffect, useMemo, useRef, memo } from 'react'\nimport { MapContext } from './map'\nimport type { MapInternalProperties, SourceWithOptionalMethods } from '../types/internal'\n\n/**\n * Coordinates for the canvas corners [top-left, top-right, bottom-right, bottom-left]\n */\nexport type CanvasCoordinates = [\n [number, number], // top-left [lng, lat]\n [number, number], // top-right [lng, lat]\n [number, number], // bottom-right [lng, lat]\n [number, number], // bottom-left [lng, lat]\n]\n\n/**\n * Props for the CanvasSource component.\n *\n * @typedef {Object} CanvasSourceProps\n * @property {string} [id] - Unique identifier for the source.\n * @property {CanvasCoordinates} coordinates - Corner coordinates of the canvas.\n * @property {HTMLCanvasElement} canvas - The canvas element to render.\n * @property {boolean} [animate] - Whether to animate the canvas (re-render on each frame).\n * @property {number} [width] - Width of the canvas context.\n * @property {number} [height] - Height of the canvas context.\n * @property {React.ReactNode} [children] - Child Layer components.\n *\n * @example\n * ```tsx\n * // Canvas source with dynamic content\n * const canvasRef = useRef<HTMLCanvasElement>(null);\n * const [canvasEl, setCanvasEl] = useState<HTMLCanvasElement | null>(null);\n *\n * useEffect(() => {\n * const canvas = canvasRef.current;\n * if (!canvas) return;\n * const ctx = canvas.getContext('2d');\n * if (ctx) {\n * ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';\n * ctx.fillRect(0, 0, 100, 100);\n * }\n * setCanvasEl(canvas);\n * }, []);\n *\n * {canvasEl && (\n * <CanvasSource\n * id=\"canvas-source\"\n * coordinates={[\n * [90.39, 23.83], // top-left\n * [90.41, 23.83], // top-right\n * [90.41, 23.81], // bottom-right\n * [90.39, 23.81] // bottom-left\n * ]}\n * canvas={canvasEl}\n * >\n * <Layer type=\"raster\" paint={{ 'raster-opacity': 0.8 }} />\n * </CanvasSource>\n * )}\n * ```\n */\nexport type CanvasSourceProps = {\n /** Unique identifier for the source */\n id?: string\n /** Corner coordinates of the canvas [top-left, top-right, bottom-right, bottom-left] */\n coordinates: CanvasCoordinates\n /** The canvas element to render */\n canvas: HTMLCanvasElement\n /** Whether to animate the canvas (re-render on each frame) */\n animate?: boolean\n /** Width of the canvas context */\n width?: number\n /** Height of the canvas context */\n height?: number\n /** Child Layer components */\n children?: React.ReactNode\n}\n\n/**\n * CanvasSource component for adding canvas-based data sources to a MapLibre GL map.\n *\n * Canvas sources allow rendering custom HTML canvas elements as map layers.\n * This is useful for dynamic, animated, or custom-rendered data overlays.\n *\n * @component\n * @example\n * ```tsx\n * import { Map, CanvasSource, Layer } from 'react-bkoi-gl';\n * import \"react-bkoi-gl/styles\";\n * import { useRef, useEffect, useState } from 'react';\n *\n * function CanvasExample() {\n * const canvasRef = useRef<HTMLCanvasElement>(null);\n * const [canvasEl, setCanvasEl] = useState<HTMLCanvasElement | null>(null);\n *\n * useEffect(() => {\n * const canvas = canvasRef.current;\n * if (!canvas) return;\n *\n * const ctx = canvas.getContext('2d');\n * if (ctx) {\n * ctx.fillStyle = 'rgba(0, 100, 255, 0.5)';\n * ctx.fillRect(0, 0, 256, 256);\n * ctx.fillStyle = 'rgba(255, 0, 0, 0.8)';\n * ctx.beginPath();\n * ctx.arc(128, 128, 50, 0, 2 * Math.PI);\n * ctx.fill();\n * }\n *\n * setCanvasEl(canvas);\n * }, []);\n *\n * return (\n * <Map\n * mapStyle={`https://map.barikoi.com/styles/osm-liberty/style.json?key=${API_KEY}`}\n * initialViewState={{\n * longitude: 90.3938,\n * latitude: 23.8216,\n * zoom: 12\n * }}\n * >\n * <canvas ref={canvasRef} width={256} height={256} style={{ display: 'none' }} />\n * {canvasEl && (\n * <CanvasSource\n * id=\"my-canvas\"\n * coordinates={[\n * [90.38, 23.83],\n * [90.41, 23.83],\n * [90.41, 23.81],\n * [90.38, 23.81]\n * ]}\n * canvas={canvasEl}\n * >\n * <Layer type=\"raster\" paint={{ 'raster-opacity': 0.8 }} />\n * </CanvasSource>\n * )}\n * </Map>\n * );\n * }\n * ```\n */\nfunction _CanvasSource(props: CanvasSourceProps) {\n const map = useContext(MapContext).map.getMap()\n const propsRef = useRef(props)\n\n const id = useMemo(() => props.id || `canvas-source-${Date.now()}`, [props.id])\n\n useEffect(() => {\n if (!map) return undefined\n\n const mapInternal = map as unknown as MapInternalProperties\n let source: maplibregl.CanvasSource | null = null\n\n const addSource = () => {\n if (!mapInternal.style || !mapInternal.style._loaded) return\n if (map.getSource(id)) return\n\n const { coordinates, canvas, animate } = props\n\n // Add canvas source\n ;(map as any).addSource(id, {\n type: 'canvas',\n coordinates,\n canvas,\n animate: animate || false,\n })\n\n source = map.getSource(id) as maplibregl.CanvasSource\n }\n\n const updateSource = () => {\n if (!source) return\n\n const { coordinates } = props\n const prevProps = propsRef.current\n\n // Update coordinates if changed\n if (JSON.stringify(coordinates) !== JSON.stringify(prevProps.coordinates)) {\n const sourceWithMethods = source as unknown as SourceWithOptionalMethods\n sourceWithMethods.setCoordinates?.(coordinates)\n }\n }\n\n // Wait for style to load\n if (mapInternal.style && mapInternal.style._loaded) {\n addSource()\n } else {\n map.once('styledata', addSource)\n }\n\n return () => {\n map.off('styledata', addSource)\n const mapInternalForCleanup = map as unknown as MapInternalProperties\n if (mapInternalForCleanup.style && mapInternalForCleanup.style._loaded && map.getSource(id)) {\n // Remove all layers using this source first\n const allLayers = map.getStyle()?.layers\n if (allLayers) {\n for (const layer of allLayers) {\n if ((layer as any).source === id) {\n map.removeLayer(layer.id)\n }\n }\n }\n map.removeSource(id)\n }\n }\n }, [map, id])\n\n // Update source when props change\n useEffect(() => {\n if (!map) return\n\n const source = map.getSource(id) as maplibregl.CanvasSource | undefined\n if (!source) return\n\n const { coordinates } = props\n const prevProps = propsRef.current\n\n // Update coordinates if changed\n if (JSON.stringify(coordinates) !== JSON.stringify(prevProps.coordinates)) {\n const sourceWithMethods = source as unknown as SourceWithOptionalMethods\n sourceWithMethods.setCoordinates?.(coordinates)\n }\n\n propsRef.current = props\n }, [map, id, props.coordinates, props.canvas])\n\n // Render children with source id\n if (!map) return null\n\n const mapInternal = map as unknown as MapInternalProperties\n if (!mapInternal.style || !mapInternal.style._loaded || !map.getSource(id)) {\n return null\n }\n\n // Clone children and pass source id\n return (\n (props.children &&\n React.Children.map(\n props.children,\n child =>\n child &&\n React.cloneElement(child as any, {\n source: id,\n })\n )) ||\n null\n )\n}\n\nexport const CanvasSource = memo<CanvasSourceProps>(_CanvasSource)\n","/**\n * @fileoverview Layer component for adding visual layers to a MapLibre GL map.\n *\n * Layers define how data from sources is rendered on the map. This component supports\n * all MapLibre GL layer types including fill, line, circle, symbol. raster. and more.\n *\n * @module components/layer\n * @see {@link https://maplibre.org/maplibre-gl-js/docs/layers/}\n */\n\nimport { useContext, useEffect, useMemo, useState, useRef, memo, useId } from 'react'\nimport { MapContext } from './map'\nimport assert from '../utils/assert'\nimport { deepEqual } from '../utils/deep-equal'\nimport { emitWarning } from '../utils/warn'\n\nimport type { FilterSpecification, MapLayerMouseEvent } from 'maplibre-gl'\n\nimport type { Map as MapInstance, CustomLayerInterface } from '../types/lib'\nimport type { LayerSpecification } from '../types/style-spec'\nimport type { MapInternalProperties } from '../types/internal'\n\n/**\n * Type for layer with filter property (not all layer types have filter)\n * @private\n */\ntype LayerWithFilter = {\n filter?: FilterSpecification | null\n layout?: Record<string, unknown>\n paint?: Record<string, unknown>\n minzoom?: number\n maxzoom?: number\n beforeId?: string\n type?: string\n id?: string\n source?: string\n}\n\n/**\n * Event handlers for layer interactions\n * @private\n */\ntype LayerEventHandlers = {\n onClick?: (e: MapLayerMouseEvent) => void\n onMouseEnter?: (e: MapLayerMouseEvent) => void\n onMouseLeave?: (e: MapLayerMouseEvent) => void\n onMouseMove?: (e: MapLayerMouseEvent) => void\n onMouseDown?: (e: MapLayerMouseEvent) => void\n onMouseUp?: (e: MapLayerMouseEvent) => void\n onContextMenu?: (e: MapLayerMouseEvent) => void\n onDoubleClick?: (e: MapLayerMouseEvent) => void\n}\n\n/**\n * Utility type to make id optional in layer specification.\n * @private\n */\ntype OptionalId<T> = T extends { id: string } ? Omit<T, 'id'> & { id?: string } : T\n\n/**\n * Utility type to make source optional in layer specification.\n * @private\n */\ntype OptionalSource<T> = T extends { source: string } ? Omit<T, 'source'> & { source?: string } : T\n\n/**\n * Props for the Layer component.\n *\n * @typedef {Object} LayerProps\n * @property {string} [id] - Unique identifier for the layer. If not provided, one will be generated automatically.\n * @property {string} [source] - The source ID this layer should use (inherited from parent Source component).\n * @property {string} [beforeId] - If set, the layer will be inserted before the specified layer.\n * @property {function} [onClick] - Called when the layer is clicked.\n * @property {function} [onMouseEnter] - Called when the mouse enters the layer.\n * @property {function} [onMouseLeave] - Called when the mouse leaves the layer.\n * @property {function} [onMouseMove] - Called when the mouse moves over the layer.\n * @property {function} [onMouseDown] - Called when mouse button is pressed on the layer.\n * @property {function} [onMouseUp] - Called when mouse button is released on the layer.\n * @property {function} [onContextMenu] - Called on right-click context menu.\n * @property {function} [onDoubleClick] - Called on double click.\n * @extends {LayerSpecification | CustomLayerInterface}\n *\n * @example\n * ```tsx\n * // Circle layer with paint properties\n * <Layer\n * id=\"points-layer\"\n * type=\"circle\"\n * paint={{\n * 'circle-radius': 8,\n * 'circle-color': '#007cbf'\n * }}\n * />\n *\n * // Line layer with filter\n * <Layer\n * id=\"roads-layer\"\n * type=\"line\"\n * source=\"streets\"\n * source-layer=\"road\"\n * filter={['==', ['get', 'type'], 'primary']}\n * paint={{ 'line-width': 2 }}\n * />\n *\n * // Interactive layer with events\n * <Layer\n * id=\"interactive-layer\"\n * type=\"fill\"\n * paint={{ 'fill-color': '#088' }}\n * onClick={(e) => console.log('Clicked:', e.features)}\n * onMouseEnter={(e) => console.log('Hover:', e.features)}\n * onMouseLeave={() => console.log('Left layer')}\n * />\n *\n * // Custom layer\n * <Layer\n * type=\"custom\"\n * renderingMode=\"2d\"\n * onAdd={(map) => { ... }}\n * render={(gl, matrix) => { ... }}\n * />\n * ```\n */\nexport type LayerProps = (OptionalSource<OptionalId<LayerSpecification>> | CustomLayerInterface) & {\n /** If set, the layer will be inserted before the specified layer */\n beforeId?: string\n /** Called when the layer is clicked */\n onClick?: (e: MapLayerMouseEvent) => void\n /** Called when the mouse enters the layer */\n onMouseEnter?: (e: MapLayerMouseEvent) => void\n /** Called when the mouse leaves the layer */\n onMouseLeave?: () => void\n /** Called when the mouse moves over the layer */\n onMouseMove?: (e: MapLayerMouseEvent) => void\n /** Called when mouse button is pressed on the layer */\n onMouseDown?: (e: MapLayerMouseEvent) => void\n /** Called when mouse button is released on the layer */\n onMouseUp?: (e: MapLayerMouseEvent) => void\n /** Called on right-click context menu */\n onContextMenu?: (e: MapLayerMouseEvent) => void\n /** Called on double click */\n onDoubleClick?: (e: MapLayerMouseEvent) => void\n}\n\n/**\n * Updates an existing layer with new properties.\n *\n * Handles updates for:\n * - Layout properties via setLayoutProperty()\n * - Paint properties via setPaintProperty()\n * - Filter via setFilter()\n * - Zoom range via setLayerZoomRange()\n * - Layer order via moveLayer()\n *\n * @param {MapInstance} map - The MapLibre GL map instance\n * @param {string} id - Unique identifier for the layer\n * @param {LayerProps} props - New properties\n * @param {LayerProps} prevProps - Previous properties\n * @throws {Error} If layer id or type changes\n * @private\n */\nfunction updateLayer(map: MapInstance, id: string, props: LayerProps, prevProps: LayerProps): void {\n assert(props.id === prevProps.id, 'layer id changed')\n assert(props.type === prevProps.type, 'layer type changed')\n\n if (props.type === 'custom' || prevProps.type === 'custom') {\n return\n }\n\n const propsWithFilter = props as unknown as LayerWithFilter\n const prevPropsWithFilter = prevProps as unknown as LayerWithFilter\n const { layout = {}, paint = {}, filter, minzoom, maxzoom, beforeId } = propsWithFilter\n\n if (beforeId !== prevPropsWithFilter.beforeId) {\n map.moveLayer(id, beforeId)\n }\n if (layout !== prevPropsWithFilter.layout) {\n const prevLayout = prevPropsWithFilter.layout || {}\n for (const key in layout) {\n if (\n Object.prototype.hasOwnProperty.call(layout, key) &&\n !deepEqual(layout[key], prevLayout[key])\n ) {\n map.setLayoutProperty(id, key, layout[key])\n }\n }\n for (const key in prevLayout) {\n if (\n Object.prototype.hasOwnProperty.call(prevLayout, key) &&\n !Object.prototype.hasOwnProperty.call(layout, key)\n ) {\n map.setLayoutProperty(id, key, undefined)\n }\n }\n }\n if (paint !== prevPropsWithFilter.paint) {\n const prevPaint = prevPropsWithFilter.paint || {}\n for (const key in paint) {\n if (\n Object.prototype.hasOwnProperty.call(paint, key) &&\n !deepEqual(paint[key], prevPaint[key])\n ) {\n map.setPaintProperty(id, key, paint[key])\n }\n }\n for (const key in prevPaint) {\n if (\n Object.prototype.hasOwnProperty.call(prevPaint, key) &&\n !Object.prototype.hasOwnProperty.call(paint, key)\n ) {\n map.setPaintProperty(id, key, undefined)\n }\n }\n }\n\n if (!deepEqual(filter, prevPropsWithFilter.filter)) {\n map.setFilter(id, filter ?? null)\n }\n if (minzoom !== prevPropsWithFilter.minzoom || maxzoom !== prevPropsWithFilter.maxzoom) {\n map.setLayerZoomRange(id, minzoom, maxzoom)\n }\n}\n\n/**\n * Creates a new layer on the map.\n *\n * @param {MapInstance} map - The MapLibre GL map instance\n * @param {string} id - Unique identifier for the layer\n * @param {LayerProps} props - Layer properties\n * @private\n */\nfunction createLayer(map: MapInstance, id: string, props: LayerProps): void {\n const mapInternal = map as unknown as MapInternalProperties\n if (\n mapInternal.style &&\n mapInternal.style._loaded &&\n (!('source' in props) || map.getSource(props.source as string))\n ) {\n const options: LayerProps = { ...props, id }\n delete options.beforeId\n\n map.addLayer(options as LayerSpecification, props.beforeId)\n }\n}\n\n/**\n * Layer component for adding visual layers to a MapLibre GL map.\n *\n * Layers define how data from sources is rendered on the map. Supports all\n * MapLibre GL layer types including fill, line, circle, symbol, raster,\n * hillshade, heatmap, and custom layers.\n *\n * Must be a child of a Source component (for data layers) or used standalone\n * with a source prop for pre-existing sources.\n *\n * @component\n * @example\n * ```tsx\n * // Circle layer with paint properties\n * <Layer\n * id=\"points-layer\"\n * type=\"circle\"\n * paint={{\n * 'circle-radius': 8,\n * 'circle-color': '#007cbf'\n * }}\n * />\n *\n * // Line layer with filter\n * <Layer\n * id=\"roads-layer\"\n * type=\"line\"\n * source=\"streets\"\n * source-layer=\"road\"\n * filter={['==', ['get', 'type'], 'primary']}\n * paint={{ 'line-width': 2 }}\n * />\n *\n * // Inside a Source component\n * <Source id=\"geojson\" type=\"geojson\" data={data}>\n * <Layer type=\"circle\" paint={{ 'circle-radius': 6 }} />\n * </Source>\n * ```\n */\nfunction _Layer(props: LayerProps) {\n const context = useContext(MapContext)\n if (!context) {\n throw new Error('<Layer> must be used within a Map component')\n }\n const map = context.map.getMap()\n const propsRef = useRef(props)\n const [, setStyleLoaded] = useState(0)\n\n // Generate a stable ID once on mount\n // Note: props.id changes after mount will trigger an error in updateLayer\n const generatedId = useId()\n const id = useMemo(\n () => props.id || `jsx-layer-${generatedId.replace(/:/g, '-')}`,\n // Empty deps - id is set once on mount and should not change\n []\n )\n\n // Extract event handlers\n const {\n onClick,\n onMouseEnter,\n onMouseLeave,\n onMouseMove,\n onMouseDown,\n onMouseUp,\n onContextMenu,\n onDoubleClick,\n } = props\n\n // Store callbacks in refs to avoid re-registering events\n const callbacksRef = useRef({\n onClick,\n onMouseEnter,\n onMouseLeave,\n onMouseMove,\n onMouseDown,\n onMouseUp,\n onContextMenu,\n onDoubleClick,\n })\n\n // Update refs when callbacks change\n useEffect(() => {\n callbacksRef.current = {\n onClick,\n onMouseEnter,\n onMouseLeave,\n onMouseMove,\n onMouseDown,\n onMouseUp,\n onContextMenu,\n onDoubleClick,\n }\n }, [\n onClick,\n onMouseEnter,\n onMouseLeave,\n onMouseMove,\n onMouseDown,\n onMouseUp,\n onContextMenu,\n onDoubleClick,\n ])\n\n useEffect(() => {\n if (map) {\n const forceUpdate = () => setStyleLoaded(version => version + 1)\n map.on('styledata', forceUpdate)\n forceUpdate()\n\n return () => {\n map.off('styledata', forceUpdate)\n const mapInternal = map as unknown as MapInternalProperties\n if (mapInternal.style && mapInternal.style._loaded && map.getLayer(id)) {\n map.removeLayer(id)\n }\n }\n }\n return undefined\n }, [map])\n\n // Register layer event handlers\n useEffect(() => {\n if (!map) return undefined\n\n const hasEventHandler =\n onClick ||\n onMouseEnter ||\n onMouseLeave ||\n onMouseMove ||\n onMouseDown ||\n onMouseUp ||\n onContextMenu ||\n onDoubleClick\n\n if (!hasEventHandler) return undefined\n\n // Event handlers\n const handleClick = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onClick?.(e)\n }\n\n const handleMouseEnter = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onMouseEnter?.(e)\n // Change cursor to pointer\n if (callbacksRef.current.onClick) {\n map.getCanvas().style.cursor = 'pointer'\n }\n }\n\n const handleMouseLeave = () => {\n callbacksRef.current.onMouseLeave?.()\n // Reset cursor\n map.getCanvas().style.cursor = ''\n }\n\n const handleMouseMove = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onMouseMove?.(e)\n }\n\n const handleMouseDown = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onMouseDown?.(e)\n }\n\n const handleMouseUp = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onMouseUp?.(e)\n }\n\n const handleContextMenu = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onContextMenu?.(e)\n }\n\n const handleDoubleClick = (e: MapLayerMouseEvent) => {\n callbacksRef.current.onDoubleClick?.(e)\n }\n\n // Register events\n if (onClick) map.on('click', id, handleClick)\n if (onMouseEnter) map.on('mouseenter', id, handleMouseEnter)\n if (onMouseLeave) map.on('mouseleave', id, handleMouseLeave)\n if (onMouseMove) map.on('mousemove', id, handleMouseMove)\n if (onMouseDown) map.on('mousedown', id, handleMouseDown)\n if (onMouseUp) map.on('mouseup', id, handleMouseUp)\n if (onContextMenu) map.on('contextmenu', id, handleContextMenu)\n if (onDoubleClick) map.on('dblclick', id, handleDoubleClick)\n\n // Cleanup\n return () => {\n if (onClick) map.off('click', id, handleClick)\n if (onMouseEnter) map.off('mouseenter', id, handleMouseEnter)\n if (onMouseLeave) map.off('mouseleave', id, handleMouseLeave)\n if (onMouseMove) map.off('mousemove', id, handleMouseMove)\n if (onMouseDown) map.off('mousedown', id, handleMouseDown)\n if (onMouseUp) map.off('mouseup', id, handleMouseUp)\n if (onContextMenu) map.off('contextmenu', id, handleContextMenu)\n if (onDoubleClick) map.off('dblclick', id, handleDoubleClick)\n }\n }, [\n map,\n id,\n onClick,\n onMouseEnter,\n onMouseLeave,\n onMouseMove,\n onMouseDown,\n onMouseUp,\n onContextMenu,\n onDoubleClick,\n ])\n\n const mapInternal = map as unknown as MapInternalProperties\n const layer = map && mapInternal.style && map.getLayer(id)\n if (layer) {\n try {\n updateLayer(map, id, props, propsRef.current)\n } catch (error) {\n emitWarning(context.onWarning, error)\n }\n } else {\n createLayer(map, id, props)\n }\n\n // Store last rendered props\n propsRef.current = props\n\n return null\n}\n\nexport const Layer = memo(_Layer)\n","import * as React from 'react'\nimport { useEffect, useMemo, memo, useRef, useContext } from 'react'\nimport MapboxDraw from 'maplibre-gl-draw'\nimport { MapContext } from './map'\n\nimport type { ControlPosition, IControl, Map as MapInstance } from '../types/lib'\n\n/**\n * Draw event types\n */\nexport interface DrawEvent {\n type: string\n features?: GeoJSON.Feature<GeoJSON.Geometry>[]\n featureIds?: string[]\n mode?: string\n originalEvent?: unknown\n}\n\n/**\n * Draw control options - extends maplibre-gl-draw options\n */\nexport interface DrawControlOptions {\n /** Whether controls are displayed by default */\n displayControlsDefault?: boolean\n /** Control configuration */\n controls?: {\n point?: boolean\n line_string?: boolean\n polygon?: boolean\n trash?: boolean\n combine_features?: boolean\n uncombine_features?: boolean\n }\n /** Custom styles for draw layers */\n styles?: unknown[]\n /** Available modes */\n modes?: Record<string, unknown>\n /** Default mode */\n defaultMode?: string\n}\n\nexport type DrawControlProps = DrawControlOptions & {\n /** Placement of the control relative to the map. */\n position?: ControlPosition\n /** CSS style override, applied to the control's container */\n style?: React.CSSProperties\n /** Callback fired when a feature is created */\n onDrawCreate?: (e: DrawEvent) => void\n /** Callback fired when a feature is deleted */\n onDrawDelete?: (e: DrawEvent) => void\n /** Callback fired when a feature is updated */\n onDrawUpdate?: (e: DrawEvent) => void\n /** Callback fired when the selection changes */\n onDrawSelectionChange?: (e: DrawEvent) => void\n /** Callback fired when the draw mode changes */\n onDrawModeChange?: (e: DrawEvent) => void\n /** Callback fired when features are combined */\n onDrawCombine?: (e: DrawEvent) => void\n /** Callback fired when features are uncombined */\n onDrawUncombine?: (e: DrawEvent) => void\n /** Callback fired when rendering */\n onDrawRender?: (e: DrawEvent) => void\n}\n\n/**\n * Default draw options - enables polygon and trash controls\n */\nconst defaultDrawOptions: DrawControlOptions = {\n displayControlsDefault: false,\n controls: {\n polygon: true,\n trash: true,\n },\n}\n\nfunction _DrawControl(props: DrawControlProps) {\n const {\n position,\n style,\n onDrawCreate,\n onDrawDelete,\n onDrawUpdate,\n onDrawSelectionChange,\n onDrawModeChange,\n onDrawCombine,\n onDrawUncombine,\n onDrawRender,\n ...drawOptions\n } = props\n\n const context = useContext(MapContext)\n\n if (!context) {\n throw new Error('DrawControl must be used within a Map component')\n }\n\n // Deep merge user options with defaults to preserve nested object properties\n const options = useMemo<DrawControlOptions>(\n () => ({\n ...defaultDrawOptions,\n ...drawOptions,\n controls: {\n ...defaultDrawOptions.controls,\n ...drawOptions.controls,\n },\n }),\n [\n drawOptions.displayControlsDefault,\n drawOptions.controls,\n drawOptions.styles,\n drawOptions.modes,\n drawOptions.defaultMode,\n ]\n )\n\n // Create a stable key for the options to detect changes\n const optionsKey = useMemo(() => JSON.stringify(options), [options])\n\n // Track callbacks in refs to avoid recreating the control for callback changes\n const callbacksRef = useRef({\n onDrawCreate,\n onDrawDelete,\n onDrawUpdate,\n onDrawSelectionChange,\n onDrawModeChange,\n onDrawCombine,\n onDrawUncombine,\n onDrawRender,\n })\n\n useEffect(() => {\n callbacksRef.current = {\n onDrawCreate,\n onDrawDelete,\n onDrawUpdate,\n onDrawSelectionChange,\n onDrawModeChange,\n onDrawCombine,\n onDrawUncombine,\n onDrawRender,\n }\n }, [\n onDrawCreate,\n onDrawDelete,\n onDrawUpdate,\n onDrawSelectionChange,\n onDrawModeChange,\n onDrawCombine,\n onDrawUncombine,\n onDrawRender,\n ])\n\n // Store control reference\n const ctrlRef = useRef<(IControl & { getMode: () => string }) | null>(null)\n const listenersRef = useRef<{\n handleCreate?: (e: DrawEvent) => void\n handleUpdate?: (e: DrawEvent) => void\n handleDelete?: (e: DrawEvent) => void\n handleSelectionChange?: (e: DrawEvent) => void\n handleModeChange?: (e: DrawEvent) => void\n handleCombine?: (e: DrawEvent) => void\n handleUncombine?: (e: DrawEvent) => void\n handleRender?: (e: DrawEvent) => void\n }>({})\n\n useEffect(() => {\n const { map } = context\n if (!map) return\n\n const mapInstance = map.getMap() as MapInstance\n if (!mapInstance) return\n\n const DrawClass = MapboxDraw as typeof MapboxDraw & {\n new (options: DrawControlOptions): IControl & { getMode: () => string }\n }\n\n // Helper to reset cursor when not in drawing mode\n const resetCursorIfNeeded = () => {\n if (ctrlRef.current) {\n const currentMode = ctrlRef.current.getMode()\n if (currentMode === 'simple_select') {\n mapInstance.getCanvas().style.cursor = ''\n }\n }\n }\n\n // Event handlers\n const handleCreate = (e: DrawEvent) => {\n resetCursorIfNeeded()\n callbacksRef.current.onDrawCreate?.(e)\n }\n\n const handleUpdate = (e: DrawEvent) => {\n resetCursorIfNeeded()\n callbacksRef.current.onDrawUpdate?.(e)\n }\n\n const handleDelete = (e: DrawEvent) => {\n resetCursorIfNeeded()\n callbacksRef.current.onDrawDelete?.(e)\n }\n\n const handleSelectionChange = (e: DrawEvent) => {\n resetCursorIfNeeded()\n callbacksRef.current.onDrawSelectionChange?.(e)\n }\n\n const handleModeChange = (e: DrawEvent) => {\n resetCursorIfNeeded()\n callbacksRef.current.onDrawModeChange?.(e)\n }\n\n const handleCombine = (e: DrawEvent) => {\n callbacksRef.current.onDrawCombine?.(e)\n }\n\n const handleUncombine = (e: DrawEvent) => {\n callbacksRef.current.onDrawUncombine?.(e)\n }\n\n const handleRender = (e: DrawEvent) => {\n callbacksRef.current.onDrawRender?.(e)\n }\n\n // Create new control\n const ctrl = new DrawClass(options)\n ctrlRef.current = ctrl\n\n // Add control to map\n map.addControl(ctrl, position)\n\n // Store listeners for cleanup\n listenersRef.current = {\n handleCreate,\n handleUpdate,\n handleDelete,\n handleSelectionChange,\n handleModeChange,\n handleCombine,\n handleUncombine,\n handleRender,\n }\n\n // Add event listeners\n mapInstance.on('draw.create', handleCreate)\n mapInstance.on('draw.update', handleUpdate)\n mapInstance.on('draw.delete', handleDelete)\n mapInstance.on('draw.selectionchange', handleSelectionChange)\n mapInstance.on('draw.modechange', handleModeChange)\n mapInstance.on('draw.combine', handleCombine)\n mapInstance.on('draw.uncombine', handleUncombine)\n mapInstance.on('draw.render', handleRender)\n\n // Cleanup function\n return () => {\n // Remove event listeners\n if (listenersRef.current.handleCreate) {\n mapInstance.off('draw.create', listenersRef.current.handleCreate)\n }\n if (listenersRef.current.handleUpdate) {\n mapInstance.off('draw.update', listenersRef.current.handleUpdate)\n }\n if (listenersRef.current.handleDelete) {\n mapInstance.off('draw.delete', listenersRef.current.handleDelete)\n }\n if (listenersRef.current.handleSelectionChange) {\n mapInstance.off('draw.selectionchange', listenersRef.current.handleSelectionChange)\n }\n if (listenersRef.current.handleModeChange) {\n mapInstance.off('draw.modechange', listenersRef.current.handleModeChange)\n }\n if (listenersRef.current.handleCombine) {\n mapInstance.off('draw.combine', listenersRef.current.handleCombine)\n }\n if (listenersRef.current.handleUncombine) {\n mapInstance.off('draw.uncombine', listenersRef.current.handleUncombine)\n }\n if (listenersRef.current.handleRender) {\n mapInstance.off('draw.render', listenersRef.current.handleRender)\n }\n\n // Remove control from map\n if (ctrlRef.current && map.hasControl(ctrlRef.current)) {\n map.removeControl(ctrlRef.current)\n }\n ctrlRef.current = null\n }\n }, [context, optionsKey, position])\n\n return null\n}\n\nexport const DrawControl = memo(_DrawControl)\n","\nconst ModeHandler = function(mode, DrawContext) {\n\n const handlers = {\n drag: [],\n click: [],\n mousemove: [],\n mousedown: [],\n mouseup: [],\n mouseout: [],\n keydown: [],\n keyup: [],\n touchstart: [],\n touchmove: [],\n touchend: [],\n tap: []\n };\n\n const ctx = {\n on(event, selector, fn) {\n if (handlers[event] === undefined) {\n throw new Error(`Invalid event type: ${event}`);\n }\n handlers[event].push({\n selector,\n fn\n });\n },\n render(id) {\n DrawContext.store.featureChanged(id);\n }\n };\n\n const delegate = function (eventName, event) {\n const handles = handlers[eventName];\n let iHandle = handles.length;\n while (iHandle--) {\n const handle = handles[iHandle];\n if (handle.selector(event)) {\n const skipRender = handle.fn.call(ctx, event);\n if (!skipRender) {\n DrawContext.store.render();\n }\n DrawContext.ui.updateMapClasses();\n\n // ensure an event is only handled once\n // we do this to let modes have multiple overlapping selectors\n // and relay on order of oppertations to filter\n break;\n }\n }\n };\n\n mode.start.call(ctx);\n\n return {\n render: mode.render,\n stop() {\n if (mode.stop) mode.stop();\n },\n trash() {\n if (mode.trash) {\n mode.trash();\n DrawContext.store.render();\n }\n },\n combineFeatures() {\n if (mode.combineFeatures) {\n mode.combineFeatures();\n }\n },\n uncombineFeatures() {\n if (mode.uncombineFeatures) {\n mode.uncombineFeatures();\n }\n },\n drag(event) {\n delegate('drag', event);\n },\n click(event) {\n delegate('click', event);\n },\n mousemove(event) {\n delegate('mousemove', event);\n },\n mousedown(event) {\n delegate('mousedown', event);\n },\n mouseup(event) {\n delegate('mouseup', event);\n },\n mouseout(event) {\n delegate('mouseout', event);\n },\n keydown(event) {\n delegate('keydown', event);\n },\n keyup(event) {\n delegate('keyup', event);\n },\n touchstart(event) {\n delegate('touchstart', event);\n },\n touchmove(event) {\n delegate('touchmove', event);\n },\n touchend(event) {\n delegate('touchend', event);\n },\n tap(event) {\n delegate('tap', event);\n }\n };\n};\n\nexport default ModeHandler;\n","module.exports.RADIUS = 6378137;\nmodule.exports.FLATTENING = 1/298.257223563;\nmodule.exports.POLAR_RADIUS = 6356752.3142;\n","var wgs84 = require('wgs84');\n\nmodule.exports.geometry = geometry;\nmodule.exports.ring = ringArea;\n\nfunction geometry(_) {\n var area = 0, i;\n switch (_.type) {\n case 'Polygon':\n return polygonArea(_.coordinates);\n case 'MultiPolygon':\n for (i = 0; i < _.coordinates.length; i++) {\n area += polygonArea(_.coordinates[i]);\n }\n return area;\n case 'Point':\n case 'MultiPoint':\n case 'LineString':\n case 'MultiLineString':\n return 0;\n case 'GeometryCollection':\n for (i = 0; i < _.geometries.length; i++) {\n area += geometry(_.geometries[i]);\n }\n return area;\n }\n}\n\nfunction polygonArea(coords) {\n var area = 0;\n if (coords && coords.length > 0) {\n area += Math.abs(ringArea(coords[0]));\n for (var i = 1; i < coords.length; i++) {\n area -= Math.abs(ringArea(coords[i]));\n }\n }\n return area;\n}\n\n/**\n * Calculate the approximate area of the polygon were it projected onto\n * the earth. Note that this area will be positive if ring is oriented\n * clockwise, otherwise it will be negative.\n *\n * Reference:\n * Robert. G. Chamberlain and William H. Duquette, \"Some Algorithms for\n * Polygons on a Sphere\", JPL Publication 07-03, Jet Propulsion\n * Laboratory, Pasadena, CA, June 2007 http://trs-new.jpl.nasa.gov/dspace/handle/2014/40409\n *\n * Returns:\n * {float} The approximate signed geodesic area of the polygon in square\n * meters.\n */\n\nfunction ringArea(coords) {\n var p1, p2, p3, lowerIndex, middleIndex, upperIndex, i,\n area = 0,\n coordsLength = coords.length;\n\n if (coordsLength > 2) {\n for (i = 0; i < coordsLength; i++) {\n if (i === coordsLength - 2) {// i = N-2\n lowerIndex = coordsLength - 2;\n middleIndex = coordsLength -1;\n upperIndex = 0;\n } else if (i === coordsLength - 1) {// i = N-1\n lowerIndex = coordsLength - 1;\n middleIndex = 0;\n upperIndex = 1;\n } else { // i = 0 to N-3\n lowerIndex = i;\n middleIndex = i+1;\n upperIndex = i+2;\n }\n p1 = coords[lowerIndex];\n p2 = coords[middleIndex];\n p3 = coords[upperIndex];\n area += ( rad(p3[0]) - rad(p1[0]) ) * Math.sin( rad(p2[1]));\n }\n\n area = area * wgs84.RADIUS * wgs84.RADIUS / 2;\n }\n\n return area;\n}\n\nfunction rad(_) {\n return _ * Math.PI / 180;\n}","export const classes = {\n CONTROL_BASE: 'maplibregl-ctrl',\n CONTROL_PREFIX: 'maplibregl-ctrl-',\n CONTROL_BUTTON: 'mapbox-gl-draw_ctrl-draw-btn',\n CONTROL_BUTTON_LINE: 'mapbox-gl-draw_line',\n CONTROL_BUTTON_POLYGON: 'mapbox-gl-draw_polygon',\n CONTROL_BUTTON_POINT: 'mapbox-gl-draw_point',\n CONTROL_BUTTON_TRASH: 'mapbox-gl-draw_trash',\n CONTROL_BUTTON_COMBINE_FEATURES: 'mapbox-gl-draw_combine',\n CONTROL_BUTTON_UNCOMBINE_FEATURES: 'mapbox-gl-draw_uncombine',\n CONTROL_BUTTON_SRMODE: 'mapbox-gl-draw_srmode',\n CONTROL_GROUP: 'maplibregl-ctrl-group',\n ATTRIBUTION: 'maplibregl-ctrl-attrib',\n ACTIVE_BUTTON: 'active',\n BOX_SELECT: 'mapbox-gl-draw_boxselect'\n};\n\nexport const sources = {\n HOT: 'mapbox-gl-draw-hot',\n COLD: 'mapbox-gl-draw-cold'\n};\n\nexport const cursors = {\n ADD: 'add',\n MOVE: 'move',\n DRAG: 'drag',\n POINTER: 'pointer',\n NONE: 'none'\n};\n\nexport const types = {\n POLYGON: 'polygon',\n LINE: 'line_string',\n POINT: 'point'\n};\n\nexport const geojsonTypes = {\n FEATURE: 'Feature',\n POLYGON: 'Polygon',\n LINE_STRING: 'LineString',\n POINT: 'Point',\n FEATURE_COLLECTION: 'FeatureCollection',\n MULTI_PREFIX: 'Multi',\n MULTI_POINT: 'MultiPoint',\n MULTI_LINE_STRING: 'MultiLineString',\n MULTI_POLYGON: 'MultiPolygon'\n};\n\nexport const modes = {\n DRAW_LINE_STRING: 'draw_line_string',\n DRAW_POLYGON: 'draw_polygon',\n DRAW_POINT: 'draw_point',\n SIMPLE_SELECT: 'simple_select',\n DIRECT_SELECT: 'direct_select',\n SCALE_ROTATE: 'srmode',\n STATIC: 'static'\n};\n\nexport const events = {\n CREATE: 'draw.create',\n DELETE: 'draw.delete',\n UPDATE: 'draw.update',\n SELECTION_CHANGE: 'draw.selectionchange',\n MODE_CHANGE: 'draw.modechange',\n ACTIONABLE: 'draw.actionable',\n RENDER: 'draw.render',\n COMBINE_FEATURES: 'draw.combine',\n UNCOMBINE_FEATURES: 'draw.uncombine'\n};\n\nexport const updateActions = {\n MOVE: 'move',\n CHANGE_COORDINATES: 'change_coordinates'\n};\n\nexport const meta = {\n FEATURE: 'feature',\n MIDPOINT: 'midpoint',\n VERTEX: 'vertex'\n};\n\nexport const activeStates = {\n ACTIVE: 'true',\n INACTIVE: 'false'\n};\n\nexport const interactions = [\n 'scrollZoom',\n 'boxZoom',\n 'dragRotate',\n 'dragPan',\n 'keyboard',\n 'doubleClickZoom',\n 'touchZoomRotate'\n];\n\nexport const LAT_MIN = -90;\nexport const LAT_RENDERED_MIN = -85;\nexport const LAT_MAX = 90;\nexport const LAT_RENDERED_MAX = 85;\nexport const LNG_MIN = -270;\nexport const LNG_MAX = 270;\n","import area from '@mapbox/geojson-area';\nimport * as Constants from '../constants';\n\nconst FEATURE_SORT_RANKS = {\n Point: 0,\n LineString: 1,\n MultiLineString: 1,\n Polygon: 2\n};\n\nfunction comparator(a, b) {\n const score = FEATURE_SORT_RANKS[a.geometry.type] - FEATURE_SORT_RANKS[b.geometry.type];\n\n if (score === 0 && a.geometry.type === Constants.geojsonTypes.POLYGON) {\n return a.area - b.area;\n }\n\n return score;\n}\n\n// Sort in the order above, then sort polygons by area ascending.\nfunction sortFeatures(features) {\n return features.map((feature) => {\n if (feature.geometry.type === Constants.geojsonTypes.POLYGON) {\n feature.area = area.geometry({\n type: Constants.geojsonTypes.FEATURE,\n property: {},\n geometry: feature.geometry\n });\n }\n return feature;\n }).sort(comparator).map((feature) => {\n delete feature.area;\n return feature;\n });\n}\n\nexport default sortFeatures;\n","/**\n * Returns a bounding box representing the event's location.\n *\n * @param {Event} mapEvent - Mapbox GL JS map event, with a point properties.\n * @return {Array<Array<number>>} Bounding box.\n */\nfunction mapEventToBoundingBox(mapEvent, buffer = 0) {\n return [\n [mapEvent.point.x - buffer, mapEvent.point.y - buffer],\n [mapEvent.point.x + buffer, mapEvent.point.y + buffer]\n ];\n}\n\nexport default mapEventToBoundingBox;\n","function StringSet(items) {\n this._items = {};\n this._nums = {};\n this._length = items ? items.length : 0;\n if (!items) return;\n for (let i = 0, l = items.length; i < l; i++) {\n this.add(items[i]);\n if (items[i] === undefined) continue;\n if (typeof items[i] === 'string') this._items[items[i]] = i;\n else this._nums[items[i]] = i;\n\n }\n}\n\nStringSet.prototype.add = function(x) {\n if (this.has(x)) return this;\n this._length++;\n if (typeof x === 'string') this._items[x] = this._length;\n else this._nums[x] = this._length;\n return this;\n};\n\nStringSet.prototype.delete = function(x) {\n if (this.has(x) === false) return this;\n this._length--;\n delete this._items[x];\n delete this._nums[x];\n return this;\n};\n\nStringSet.prototype.has = function(x) {\n if (typeof x !== 'string' && typeof x !== 'number') return false;\n return this._items[x] !== undefined || this._nums[x] !== undefined;\n};\n\nStringSet.prototype.values = function() {\n const values = [];\n Object.keys(this._items).forEach((k) => {\n values.push({ k, v: this._items[k] });\n });\n Object.keys(this._nums).forEach((k) => {\n values.push({ k: JSON.parse(k), v: this._nums[k] });\n });\n\n return values.sort((a, b) => a.v - b.v).map(a => a.k);\n};\n\nStringSet.prototype.clear = function() {\n this._length = 0;\n this._items = {};\n this._nums = {};\n return this;\n};\n\nexport default StringSet;\n","import sortFeatures from './sort_features';\nimport mapEventToBoundingBox from './map_event_to_bounding_box';\nimport * as Constants from '../constants';\nimport StringSet from './string_set';\n\nconst META_TYPES = [\n Constants.meta.FEATURE,\n Constants.meta.MIDPOINT,\n Constants.meta.VERTEX\n];\n\n// Requires either event or bbox\nexport default {\n click: featuresAtClick,\n touch: featuresAtTouch\n};\n\nfunction featuresAtClick(event, bbox, ctx) {\n return featuresAt(event, bbox, ctx, ctx.options.clickBuffer);\n}\n\nfunction featuresAtTouch(event, bbox, ctx) {\n return featuresAt(event, bbox, ctx, ctx.options.touchBuffer);\n}\n\nfunction featuresAt(event, bbox, ctx, buffer) {\n if (ctx.map === null) return [];\n\n const box = (event) ? mapEventToBoundingBox(event, buffer) : bbox;\n\n const queryParams = {};\n if (ctx.options.styles) queryParams.layers = ctx.options.styles.map(s => s.id);\n\n const features = ctx.map.queryRenderedFeatures(box, queryParams)\n .filter(feature => META_TYPES.indexOf(feature.properties.meta) !== -1);\n\n const featureIds = new StringSet();\n const uniqueFeatures = [];\n features.forEach((feature) => {\n const featureId = feature.properties.id;\n if (featureIds.has(featureId)) return;\n featureIds.add(featureId);\n uniqueFeatures.push(feature);\n });\n\n return sortFeatures(uniqueFeatures);\n}\n","import featuresAt from './features_at';\nimport * as Constants from '../constants';\n\nexport default function getFeatureAtAndSetCursors(event, ctx) {\n const features = featuresAt.click(event, null, ctx);\n const classes = { mouse: Constants.cursors.NONE };\n\n if (features[0]) {\n classes.mouse = (features[0].properties.active === Constants.activeStates.ACTIVE) ?\n Constants.cursors.MOVE : Constants.cursors.POINTER;\n classes.feature = features[0].properties.meta;\n }\n\n if (ctx.events.currentModeName().indexOf('draw') !== -1) {\n classes.mouse = Constants.cursors.ADD;\n }\n\n ctx.ui.queueMapClasses(classes);\n ctx.ui.updateMapClasses();\n\n return features[0];\n}\n","export default function(a, b) {\n const x = a.x - b.x;\n const y = a.y - b.y;\n return Math.sqrt((x * x) + (y * y));\n}\n","import euclideanDistance from './euclidean_distance';\n\nconst FINE_TOLERANCE = 4;\nconst GROSS_TOLERANCE = 12;\nconst INTERVAL = 500;\n\nexport default function isClick(start, end, options = {}) {\n const fineTolerance = (options.fineTolerance != null) ? options.fineTolerance : FINE_TOLERANCE;\n const grossTolerance = (options.grossTolerance != null) ? options.grossTolerance : GROSS_TOLERANCE;\n const interval = (options.interval != null) ? options.interval : INTERVAL;\n\n start.point = start.point || end.point;\n start.time = start.time || end.time;\n const moveDistance = euclideanDistance(start.point, end.point);\n\n return moveDistance < fineTolerance ||\n (moveDistance < grossTolerance && (end.time - start.time) < interval);\n}\n","import euclideanDistance from './euclidean_distance';\n\nexport const TAP_TOLERANCE = 25;\nexport const TAP_INTERVAL = 250;\n\nexport default function isTap(start, end, options = {}) {\n const tolerance = (options.tolerance != null) ? options.tolerance : TAP_TOLERANCE;\n const interval = (options.interval != null) ? options.interval : TAP_INTERVAL;\n\n start.point = start.point || end.point;\n start.time = start.time || end.time;\n const moveDistance = euclideanDistance(start.point, end.point);\n\n return moveDistance < tolerance && (end.time - start.time) < interval;\n}\n","var hat = module.exports = function (bits, base) {\n if (!base) base = 16;\n if (bits === undefined) bits = 128;\n if (bits <= 0) return '0';\n \n var digits = Math.log(Math.pow(2, bits)) / Math.log(base);\n for (var i = 2; digits === Infinity; i *= 2) {\n digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;\n }\n \n var rem = digits - Math.floor(digits);\n \n var res = '';\n \n for (var i = 0; i < Math.floor(digits); i++) {\n var x = Math.floor(Math.random() * base).toString(base);\n res = x + res;\n }\n \n if (rem) {\n var b = Math.pow(base, rem);\n var x = Math.floor(Math.random() * b).toString(base);\n res = x + res;\n }\n \n var parsed = parseInt(res, base);\n if (parsed !== Infinity && parsed >= Math.pow(2, bits)) {\n return hat(bits, base)\n }\n else return res;\n};\n\nhat.rack = function (bits, base, expandBy) {\n var fn = function (data) {\n var iters = 0;\n do {\n if (iters ++ > 10) {\n if (expandBy) bits += expandBy;\n else throw new Error('too many ID collisions, use more bits')\n }\n \n var id = hat(bits, base);\n } while (Object.hasOwnProperty.call(hats, id));\n \n hats[id] = data;\n return id;\n };\n var hats = fn.hats = {};\n \n fn.get = function (id) {\n return fn.hats[id];\n };\n \n fn.set = function (id, value) {\n fn.hats[id] = value;\n return fn;\n };\n \n fn.bits = bits || 128;\n fn.base = base || 16;\n return fn;\n};\n","import hat from 'hat';\nimport * as Constants from '../constants';\n\nconst Feature = function(ctx, geojson) {\n this.ctx = ctx;\n this.properties = geojson.properties || {};\n this.coordinates = geojson.geometry.coordinates;\n this.id = geojson.id || hat();\n this.type = geojson.geometry.type;\n};\n\nFeature.prototype.changed = function() {\n this.ctx.store.featureChanged(this.id);\n};\n\nFeature.prototype.incomingCoords = function(coords) {\n this.setCoordinates(coords);\n};\n\nFeature.prototype.setCoordinates = function(coords) {\n this.coordinates = coords;\n this.changed();\n};\n\nFeature.prototype.getCoordinates = function() {\n return JSON.parse(JSON.stringify(this.coordinates));\n};\n\nFeature.prototype.setProperty = function(property, value) {\n this.properties[property] = value;\n};\n\nFeature.prototype.toGeoJSON = function() {\n return JSON.parse(JSON.stringify({\n id: this.id,\n type: Constants.geojsonTypes.FEATURE,\n properties: this.properties,\n geometry: {\n coordinates: this.getCoordinates(),\n type: this.type\n }\n }));\n};\n\nFeature.prototype.internal = function(mode) {\n const properties = {\n id: this.id,\n meta: Constants.meta.FEATURE,\n 'meta:type': this.type,\n active: Constants.activeStates.INACTIVE,\n mode\n };\n\n if (this.ctx.options.userProperties) {\n for (const name in this.properties) {\n properties[`user_${name}`] = this.properties[name];\n }\n }\n\n return {\n type: Constants.geojsonTypes.FEATURE,\n properties,\n geometry: {\n coordinates: this.getCoordinates(),\n type: this.type\n }\n };\n};\n\nexport default Feature;\n","import Feature from './feature';\n\nconst Point = function(ctx, geojson) {\n Feature.call(this, ctx, geojson);\n};\n\nPoint.prototype = Object.create(Feature.prototype);\n\nPoint.prototype.isValid = function() {\n return typeof this.coordinates[0] === 'number' &&\n typeof this.coordinates[1] === 'number';\n};\n\nPoint.prototype.updateCoordinate = function(pathOrLng, lngOrLat, lat) {\n if (arguments.length === 3) {\n this.coordinates = [lngOrLat, lat];\n } else {\n this.coordinates = [pathOrLng, lngOrLat];\n }\n this.changed();\n};\n\nPoint.prototype.getCoordinate = function() {\n return this.getCoordinates();\n};\n\nexport default Point;\n","import Feature from './feature';\n\nconst LineString = function(ctx, geojson) {\n Feature.call(this, ctx, geojson);\n};\n\nLineString.prototype = Object.create(Feature.prototype);\n\nLineString.prototype.isValid = function() {\n return this.coordinates.length > 1;\n};\n\nLineString.prototype.addCoordinate = function(path, lng, lat) {\n this.changed();\n const id = parseInt(path, 10);\n this.coordinates.splice(id, 0, [lng, lat]);\n};\n\nLineString.prototype.getCoordinate = function(path) {\n const id = parseInt(path, 10);\n return JSON.parse(JSON.stringify(this.coordinates[id]));\n};\n\nLineString.prototype.removeCoordinate = function(path) {\n this.changed();\n this.coordinates.splice(parseInt(path, 10), 1);\n};\n\nLineString.prototype.updateCoordinate = function(path, lng, lat) {\n const id = parseInt(path, 10);\n this.coordinates[id] = [lng, lat];\n this.changed();\n};\n\nexport default LineString;\n","import Feature from './feature';\n\nconst Polygon = function(ctx, geojson) {\n Feature.call(this, ctx, geojson);\n this.coordinates = this.coordinates.map(ring => ring.slice(0, -1));\n};\n\nPolygon.prototype = Object.create(Feature.prototype);\n\nPolygon.prototype.isValid = function() {\n if (this.coordinates.length === 0) return false;\n return this.coordinates.every(ring => ring.length > 2);\n};\n\n// Expects valid geoJSON polygon geometry: first and last positions must be equivalent.\nPolygon.prototype.incomingCoords = function(coords) {\n this.coordinates = coords.map(ring => ring.slice(0, -1));\n this.changed();\n};\n\n// Does NOT expect valid geoJSON polygon geometry: first and last positions should not be equivalent.\nPolygon.prototype.setCoordinates = function(coords) {\n this.coordinates = coords;\n this.changed();\n};\n\nPolygon.prototype.addCoordinate = function(path, lng, lat) {\n this.changed();\n const ids = path.split('.').map(x => parseInt(x, 10));\n\n const ring = this.coordinates[ids[0]];\n\n ring.splice(ids[1], 0, [lng, lat]);\n};\n\nPolygon.prototype.removeCoordinate = function(path) {\n this.changed();\n const ids = path.split('.').map(x => parseInt(x, 10));\n const ring = this.coordinates[ids[0]];\n if (ring) {\n ring.splice(ids[1], 1);\n if (ring.length < 3) {\n this.coordinates.splice(ids[0], 1);\n }\n }\n};\n\nPolygon.prototype.getCoordinate = function(path) {\n const ids = path.split('.').map(x => parseInt(x, 10));\n const ring = this.coordinates[ids[0]];\n return JSON.parse(JSON.stringify(ring[ids[1]]));\n};\n\nPolygon.prototype.getCoordinates = function() {\n return this.coordinates.map(coords => coords.concat([coords[0]]));\n};\n\nPolygon.prototype.updateCoordinate = function(path, lng, lat) {\n this.changed();\n const parts = path.split('.');\n const ringId = parseInt(parts[0], 10);\n const coordId = parseInt(parts[1], 10);\n\n if (this.coordinates[ringId] === undefined) {\n this.coordinates[ringId] = [];\n }\n\n this.coordinates[ringId][coordId] = [lng, lat];\n};\n\nexport default Polygon;\n","import Feature from './feature';\nimport * as Constants from '../constants';\nimport hat from 'hat';\n\nimport MultiPoint from './point';\nimport MultiLineString from './line_string';\nimport MultiPolygon from './polygon';\n\nconst models = {\n MultiPoint,\n MultiLineString,\n MultiPolygon\n};\n\nconst takeAction = (features, action, path, lng, lat) => {\n const parts = path.split('.');\n const idx = parseInt(parts[0], 10);\n const tail = (!parts[1]) ? null : parts.slice(1).join('.');\n return features[idx][action](tail, lng, lat);\n};\n\nconst MultiFeature = function(ctx, geojson) {\n Feature.call(this, ctx, geojson);\n\n delete this.coordinates;\n this.model = models[geojson.geometry.type];\n if (this.model === undefined) throw new TypeError(`${geojson.geometry.type} is not a valid type`);\n this.features = this._coordinatesToFeatures(geojson.geometry.coordinates);\n};\n\nMultiFeature.prototype = Object.create(Feature.prototype);\n\nMultiFeature.prototype._coordinatesToFeatures = function(coordinates) {\n const Model = this.model.bind(this);\n return coordinates.map(coords => new Model(this.ctx, {\n id: hat(),\n type: Constants.geojsonTypes.FEATURE,\n properties: {},\n geometry: {\n coordinates: coords,\n type: this.type.replace('Multi', '')\n }\n }));\n};\n\nMultiFeature.prototype.isValid = function() {\n return this.features.every(f => f.isValid());\n};\n\nMultiFeature.prototype.setCoordinates = function(coords) {\n this.features = this._coordinatesToFeatures(coords);\n this.changed();\n};\n\nMultiFeature.prototype.getCoordinate = function(path) {\n return takeAction(this.features, 'getCoordinate', path);\n};\n\nMultiFeature.prototype.getCoordinates = function() {\n return JSON.parse(JSON.stringify(this.features.map((f) => {\n if (f.type === Constants.geojsonTypes.POLYGON) return f.getCoordinates();\n return f.coordinates;\n })));\n};\n\nMultiFeature.prototype.updateCoordinate = function(path, lng, lat) {\n takeAction(this.features, 'updateCoordinate', path, lng, lat);\n this.changed();\n};\n\nMultiFeature.prototype.addCoordinate = function(path, lng, lat) {\n takeAction(this.features, 'addCoordinate', path, lng, lat);\n this.changed();\n};\n\nMultiFeature.prototype.removeCoordinate = function(path) {\n takeAction(this.features, 'removeCoordinate', path);\n this.changed();\n};\n\nMultiFeature.prototype.getFeatures = function() {\n return this.features;\n};\n\nexport default MultiFeature;\n","import * as Constants from '../constants';\nimport featuresAt from '../lib/features_at';\nimport Point from '../feature_types/point';\nimport LineString from '../feature_types/line_string';\nimport Polygon from '../feature_types/polygon';\nimport MultiFeature from '../feature_types/multi_feature';\n\nexport default function ModeInterface(ctx) {\n this.map = ctx.map;\n this.drawConfig = JSON.parse(JSON.stringify(ctx.options || {}));\n this._ctx = ctx;\n}\n\n/**\n * Sets Draw's interal selected state\n * @name this.setSelected\n * @param {DrawFeature[]} - whats selected as a [DrawFeature](https://github.com/mapbox/mapbox-gl-draw/blob/main/src/feature_types/feature.js)\n */\nModeInterface.prototype.setSelected = function(features) {\n return this._ctx.store.setSelected(features);\n};\n\n/**\n * Sets Draw's internal selected coordinate state\n * @name this.setSelectedCoordinates\n * @param {Object[]} coords - a array of {coord_path: 'string', feature_id: 'string'}\n */\nModeInterface.prototype.setSelectedCoordinates = function(coords) {\n this._ctx.store.setSelectedCoordinates(coords);\n coords.reduce((m, c) => {\n if (m[c.feature_id] === undefined) {\n m[c.feature_id] = true;\n this._ctx.store.get(c.feature_id).changed();\n }\n return m;\n }, {});\n};\n\n/**\n * Get all selected features as a [DrawFeature](https://github.com/mapbox/mapbox-gl-draw/blob/main/src/feature_types/feature.js)\n * @name this.getSelected\n * @returns {DrawFeature[]}\n */\nModeInterface.prototype.getSelected = function() {\n return this._ctx.store.getSelected();\n};\n\n/**\n * Get the ids of all currently selected features\n * @name this.getSelectedIds\n * @returns {String[]}\n */\nModeInterface.prototype.getSelectedIds = function() {\n return this._ctx.store.getSelectedIds();\n};\n\n/**\n * Check if a feature is selected\n * @name this.isSelected\n * @param {String} id - a feature id\n * @returns {Boolean}\n */\nModeInterface.prototype.isSelected = function(id) {\n return this._ctx.store.isSelected(id);\n};\n\n/**\n * Get a [DrawFeature](https://github.com/mapbox/mapbox-gl-draw/blob/main/src/feature_types/feature.js) by its id\n * @name this.getFeature\n * @param {String} id - a feature id\n * @returns {DrawFeature}\n */\nModeInterface.prototype.getFeature = function(id) {\n return this._ctx.store.get(id);\n};\n\n/**\n * Add a feature to draw's internal selected state\n * @name this.select\n * @param {String} id\n */\nModeInterface.prototype.select = function(id) {\n return this._ctx.store.select(id);\n};\n\n/**\n * Remove a feature from draw's internal selected state\n * @name this.delete\n * @param {String} id\n */\nModeInterface.prototype.deselect = function(id) {\n return this._ctx.store.deselect(id);\n};\n\n/**\n * Delete a feature from draw\n * @name this.deleteFeature\n * @param {String} id - a feature id\n */\nModeInterface.prototype.deleteFeature = function(id, opts = {}) {\n return this._ctx.store.delete(id, opts);\n};\n\n/**\n * Add a [DrawFeature](https://github.com/mapbox/mapbox-gl-draw/blob/main/src/feature_types/feature.js) to draw.\n * See `this.newFeature` for converting geojson into a DrawFeature\n * @name this.addFeature\n * @param {DrawFeature} feature - the feature to add\n */\nModeInterface.prototype.addFeature = function(feature) {\n return this._ctx.store.add(feature);\n};\n\n/**\n * Clear all selected features\n */\nModeInterface.prototype.clearSelectedFeatures = function() {\n return this._ctx.store.clearSelected();\n};\n\n/**\n * Clear all selected coordinates\n */\nModeInterface.prototype.clearSelectedCoordinates = function() {\n return this._ctx.store.clearSelectedCoordinates();\n};\n\n/**\n * Indicate if the different action are currently possible with your mode\n * See [draw.actionalbe](https://github.com/mapbox/mapbox-gl-draw/blob/main/API.md#drawactionable) for a list of possible actions. All undefined actions are set to **false** by default\n * @name this.setActionableState\n * @param {Object} actions\n */\nModeInterface.prototype.setActionableState = function(actions = {}) {\n const newSet = {\n trash: actions.trash || false,\n combineFeatures: actions.combineFeatures || false,\n uncombineFeatures: actions.uncombineFeatures || false\n };\n return this._ctx.events.actionable(newSet);\n};\n\n/**\n * Trigger a mode change\n * @name this.changeMode\n * @param {String} mode - the mode to transition into\n * @param {Object} opts - the options object to pass to the new mode\n * @param {Object} eventOpts - used to control what kind of events are emitted.\n */\nModeInterface.prototype.changeMode = function(mode, opts = {}, eventOpts = {}) {\n return this._ctx.events.changeMode(mode, opts, eventOpts);\n};\n\n/**\n * Update the state of draw map classes\n * @name this.updateUIClasses\n * @param {Object} opts\n */\nModeInterface.prototype.updateUIClasses = function(opts) {\n return this._ctx.ui.queueMapClasses(opts);\n};\n\n/**\n * If a name is provided it makes that button active, else if makes all buttons inactive\n * @name this.activateUIButton\n * @param {String?} name - name of the button to make active, leave as undefined to set buttons to be inactive\n */\nModeInterface.prototype.activateUIButton = function(name) {\n return this._ctx.ui.setActiveButton(name);\n};\n\n/**\n * Get the features at the location of an event object or in a bbox\n * @name this.featuresAt\n * @param {Event||NULL} event - a mapbox-gl event object\n * @param {BBOX||NULL} bbox - the area to get features from\n * @param {String} bufferType - is this `click` or `tap` event, defaults to click\n */\nModeInterface.prototype.featuresAt = function(event, bbox, bufferType = 'click') {\n if (bufferType !== 'click' && bufferType !== 'touch') throw new Error('invalid buffer type');\n return featuresAt[bufferType](event, bbox, this._ctx);\n};\n\n/**\n * Create a new [DrawFeature](https://github.com/mapbox/mapbox-gl-draw/blob/main/src/feature_types/feature.js) from geojson\n * @name this.newFeature\n * @param {GeoJSONFeature} geojson\n * @returns {DrawFeature}\n */\nModeInterface.prototype.newFeature = function(geojson) {\n const type = geojson.geometry.type;\n if (type === Constants.geojsonTypes.POINT) return new Point(this._ctx, geojson);\n if (type === Constants.geojsonTypes.LINE_STRING) return new LineString(this._ctx, geojson);\n if (type === Constants.geojsonTypes.POLYGON) return new Polygon(this._ctx, geojson);\n return new MultiFeature(this._ctx, geojson);\n};\n\n/**\n * Check is an object is an instance of a [DrawFeature](https://github.com/mapbox/mapbox-gl-draw/blob/main/src/feature_types/feature.js)\n * @name this.isInstanceOf\n * @param {String} type - `Point`, `LineString`, `Polygon`, `MultiFeature`\n * @param {Object} feature - the object that needs to be checked\n * @returns {Boolean}\n */\nModeInterface.prototype.isInstanceOf = function(type, feature) {\n if (type === Constants.geojsonTypes.POINT) return feature instanceof Point;\n if (type === Constants.geojsonTypes.LINE_STRING) return feature instanceof LineString;\n if (type === Constants.geojsonTypes.POLYGON) return feature instanceof Polygon;\n if (type === 'MultiFeature') return feature instanceof MultiFeature;\n throw new Error(`Unknown feature class: ${type}`);\n};\n\n/**\n * Force draw to rerender the feature of the provided id\n * @name this.doRender\n * @param {String} id - a feature id\n */\nModeInterface.prototype.doRender = function(id) {\n return this._ctx.store.featureChanged(id);\n};\n\n","import ModeInterface from './mode_interface_accessors';\nexport default ModeInterface;\n\n/**\n * Triggered while a mode is being transitioned into.\n * @param opts {Object} - this is the object passed via `draw.changeMode('mode', opts)`;\n * @name MODE.onSetup\n * @returns {Object} - this object will be passed to all other life cycle functions\n */\nModeInterface.prototype.onSetup = function() {};\n\n/**\n * Triggered when a drag event is detected on the map\n * @name MODE.onDrag\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onDrag = function() {};\n\n/**\n * Triggered when the mouse is clicked\n * @name MODE.onClick\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onClick = function() {};\n\n/**\n * Triggered with the mouse is moved\n * @name MODE.onMouseMove\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onMouseMove = function() {};\n\n/**\n * Triggered when the mouse button is pressed down\n * @name MODE.onMouseDown\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onMouseDown = function() {};\n\n/**\n * Triggered when the mouse button is released\n * @name MODE.onMouseUp\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onMouseUp = function() {};\n\n/**\n * Triggered when the mouse leaves the map's container\n * @name MODE.onMouseOut\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onMouseOut = function() {};\n\n/**\n * Triggered when a key up event is detected\n * @name MODE.onKeyUp\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onKeyUp = function() {};\n\n/**\n * Triggered when a key down event is detected\n * @name MODE.onKeyDown\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onKeyDown = function() {};\n\n/**\n * Triggered when a touch event is started\n * @name MODE.onTouchStart\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onTouchStart = function() {};\n\n/**\n * Triggered when one drags thier finger on a mobile device\n * @name MODE.onTouchMove\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onTouchMove = function() {};\n\n/**\n * Triggered when one removes their finger from the map\n * @name MODE.onTouchEnd\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onTouchEnd = function() {};\n\n/**\n * Triggered when one quicly taps the map\n * @name MODE.onTap\n * @param state {Object} - a mutible state object created by onSetup\n * @param e {Object} - the captured event that is triggering this life cycle event\n */\nModeInterface.prototype.onTap = function() {};\n\n/**\n * Triggered when the mode is being exited, to be used for cleaning up artifacts such as invalid features\n * @name MODE.onStop\n * @param state {Object} - a mutible state object created by onSetup\n */\nModeInterface.prototype.onStop = function() {};\n\n/**\n * Triggered when [draw.trash()](https://github.com/mapbox/mapbox-gl-draw/blob/main/API.md#trash-draw) is called.\n * @name MODE.onTrash\n * @param state {Object} - a mutible state object created by onSetup\n */\nModeInterface.prototype.onTrash = function() {};\n\n/**\n * Triggered when [draw.combineFeatures()](https://github.com/mapbox/mapbox-gl-draw/blob/main/API.md#combinefeatures-draw) is called.\n * @name MODE.onCombineFeature\n * @param state {Object} - a mutible state object created by onSetup\n */\nModeInterface.prototype.onCombineFeature = function() {};\n\n/**\n * Triggered when [draw.uncombineFeatures()](https://github.com/mapbox/mapbox-gl-draw/blob/main/API.md#uncombinefeatures-draw) is called.\n * @name MODE.onUncombineFeature\n * @param state {Object} - a mutible state object created by onSetup\n */\nModeInterface.prototype.onUncombineFeature = function() {};\n\n/**\n * Triggered per feature on render to convert raw features into set of features for display on the map\n * See [styling draw](https://github.com/mapbox/mapbox-gl-draw/blob/main/API.md#styling-draw) for information about what geojson properties Draw uses as part of rendering.\n * @name MODE.toDisplayFeatures\n * @param state {Object} - a mutible state object created by onSetup\n * @param geojson {Object} - a geojson being evaulated. To render, pass to `display`.\n * @param display {Function} - all geojson objects passed to this be rendered onto the map\n */\nModeInterface.prototype.toDisplayFeatures = function() {\n throw new Error('You must overwrite toDisplayFeatures');\n};\n\n","import ModeInterface from './mode_interface';\n\nconst eventMapper = {\n drag: 'onDrag',\n click: 'onClick',\n mousemove: 'onMouseMove',\n mousedown: 'onMouseDown',\n mouseup: 'onMouseUp',\n mouseout: 'onMouseOut',\n keyup: 'onKeyUp',\n keydown: 'onKeyDown',\n touchstart: 'onTouchStart',\n touchmove: 'onTouchMove',\n touchend: 'onTouchEnd',\n tap: 'onTap'\n};\n\nconst eventKeys = Object.keys(eventMapper);\n\nexport default function(modeObject) {\n const modeObjectKeys = Object.keys(modeObject);\n\n return function(ctx, startOpts = {}) {\n let state = {};\n\n const mode = modeObjectKeys.reduce((m, k) => {\n m[k] = modeObject[k];\n return m;\n }, new ModeInterface(ctx));\n\n function wrapper(eh) {\n return e => mode[eh](state, e);\n }\n\n return {\n start() {\n state = mode.onSetup(startOpts); // this should set ui buttons\n\n // Adds event handlers for all event options\n // add sets the selector to false for all\n // handlers that are not present in the mode\n // to reduce on render calls for functions that\n // have no logic\n eventKeys.forEach((key) => {\n const modeHandler = eventMapper[key];\n let selector = () => false;\n if (modeObject[modeHandler]) {\n selector = () => true;\n }\n this.on(key, selector, wrapper(modeHandler));\n });\n\n },\n stop() {\n mode.onStop(state);\n },\n trash() {\n mode.onTrash(state);\n },\n combineFeatures() {\n mode.onCombineFeatures(state);\n },\n uncombineFeatures() {\n mode.onUncombineFeatures(state);\n },\n render(geojson, push) {\n mode.toDisplayFeatures(state, geojson, push);\n }\n };\n };\n}\n","export let SRCenter = {\n Center: 0, // rotate or scale around center of polygon\n Opposite: 1, // rotate or scale around opposite side of polygon\n };","import setupModeHandler from './lib/mode_handler';\nimport getFeaturesAndSetCursor from './lib/get_features_and_set_cursor';\nimport featuresAt from './lib/features_at';\nimport isClick from './lib/is_click';\nimport isTap from './lib/is_tap';\nimport * as Constants from './constants';\nimport objectToMode from './modes/object_to_mode';\nimport {SRCenter} from \"./lib/SRCenter\";\n\nexport default function(ctx) {\n\n const modes = Object.keys(ctx.options.modes).reduce((m, k) => {\n m[k] = objectToMode(ctx.options.modes[k]);\n return m;\n }, {});\n\n let mouseDownInfo = {};\n let touchStartInfo = {};\n const events = {};\n let currentModeName = null;\n let currentMode = null;\n\n events.drag = function(event, isDrag) {\n if (isDrag({\n point: event.point,\n time: new Date().getTime()\n })) {\n ctx.ui.queueMapClasses({ mouse: Constants.cursors.DRAG });\n currentMode.drag(event);\n } else {\n event.originalEvent.stopPropagation();\n }\n };\n\n events.mousedrag = function(event) {\n events.drag(event, endInfo => !isClick(mouseDownInfo, endInfo));\n };\n\n events.touchdrag = function(event) {\n events.drag(event, endInfo => !isTap(touchStartInfo, endInfo));\n };\n\n events.mousemove = function(event) {\n const button = event.originalEvent.buttons !== undefined ? event.originalEvent.buttons : event.originalEvent.which;\n if (button === 1) {\n return events.mousedrag(event);\n }\n const target = getFeaturesAndSetCursor(event, ctx);\n event.featureTarget = target;\n currentMode.mousemove(event);\n };\n\n events.mousedown = function(event) {\n mouseDownInfo = {\n time: new Date().getTime(),\n point: event.point\n };\n const target = getFeaturesAndSetCursor(event, ctx);\n event.featureTarget = target;\n currentMode.mousedown(event);\n };\n\n events.mouseup = function(event) {\n const target = getFeaturesAndSetCursor(event, ctx);\n event.featureTarget = target;\n\n if (isClick(mouseDownInfo, {\n point: event.point,\n time: new Date().getTime()\n })) {\n currentMode.click(event);\n } else {\n currentMode.mouseup(event);\n }\n };\n\n events.mouseout = function(event) {\n currentMode.mouseout(event);\n };\n\n events.touchstart = function(event) {\n // Prevent emulated mouse events because we will fully handle the touch here.\n // This does not stop the touch events from propogating to mapbox though.\n event.originalEvent.preventDefault();\n if (!ctx.options.touchEnabled) {\n return;\n }\n\n touchStartInfo = {\n time: new Date().getTime(),\n point: event.point\n };\n const target = featuresAt.touch(event, null, ctx)[0];\n event.featureTarget = target;\n currentMode.touchstart(event);\n };\n\n events.touchmove = function(event) {\n event.originalEvent.preventDefault();\n if (!ctx.options.touchEnabled) {\n return;\n }\n\n currentMode.touchmove(event);\n return events.touchdrag(event);\n };\n\n events.touchend = function(event) {\n event.originalEvent.preventDefault();\n if (!ctx.options.touchEnabled) {\n return;\n }\n\n const target = featuresAt.touch(event, null, ctx)[0];\n event.featureTarget = target;\n if (isTap(touchStartInfo, {\n time: new Date().getTime(),\n point: event.point\n })) {\n currentMode.tap(event);\n } else {\n currentMode.touchend(event);\n }\n };\n\n // 8 - Backspace\n // 46 - Delete\n const isKeyModeValid = code => !(code === 8 || code === 46 || (code >= 48 && code <= 57));\n\n events.keydown = function(event) {\n const isMapElement = (event.srcElement || event.target).classList.contains('maplibregl-canvas');\n if (!isMapElement) return; // we only handle events on the map\n\n if ((event.keyCode === 8 || event.keyCode === 46) && ctx.options.controls.trash) {\n event.preventDefault();\n currentMode.trash();\n } else if (isKeyModeValid(event.keyCode)) {\n currentMode.keydown(event);\n } else if (event.keyCode === 49 && ctx.options.controls.point) {\n changeMode(Constants.modes.DRAW_POINT);\n } else if (event.keyCode === 50 && ctx.options.controls.line_string) {\n changeMode(Constants.modes.DRAW_LINE_STRING);\n } else if (event.keyCode === 51 && ctx.options.controls.polygon) {\n changeMode(Constants.modes.DRAW_POLYGON);\n }\n };\n\n events.keyup = function(event) {\n if (isKeyModeValid(event.keyCode)) {\n currentMode.keyup(event);\n }\n };\n\n events.zoomend = function() {\n ctx.store.changeZoom();\n };\n\n events.data = function(event) {\n if (event.dataType === 'style') {\n const { setup, map, options, store } = ctx;\n const hasLayers = options.styles.some(style => map.getLayer(style.id));\n if (!hasLayers) {\n setup.addLayers();\n store.setDirty();\n store.render();\n }\n }\n };\n\n function changeMode(modename, nextModeOptions, eventOptions = {}) {\n currentMode.stop();\n\n const modebuilder = modes[modename];\n if (modebuilder === undefined) {\n throw new Error(`${modename} is not valid`);\n }\n currentModeName = modename;\n const mode = modebuilder(ctx, nextModeOptions);\n currentMode = setupModeHandler(mode, ctx);\n\n if (!eventOptions.silent) {\n ctx.map.fire(Constants.events.MODE_CHANGE, { mode: modename});\n }\n\n ctx.store.setDirty();\n ctx.store.render();\n }\n\n const actionState = {\n trash: false,\n combineFeatures: false,\n uncombineFeatures: false\n };\n\n function actionable(actions) {\n let changed = false;\n Object.keys(actions).forEach((action) => {\n if (actionState[action] === undefined) throw new Error('Invalid action type');\n if (actionState[action] !== actions[action]) changed = true;\n actionState[action] = actions[action];\n });\n if (changed) ctx.map.fire(Constants.events.ACTIONABLE, { actions: actionState });\n }\n\n const api = {\n start() {\n currentModeName = ctx.options.defaultMode;\n currentMode = setupModeHandler(modes[currentModeName](ctx), ctx);\n },\n changeMode,\n actionable,\n currentModeName() {\n return currentModeName;\n },\n currentModeRender(geojson, push) {\n return currentMode.render(geojson, push);\n },\n fire(name, event) {\n if (events[name]) {\n events[name](event);\n }\n },\n addEventListeners() {\n ctx.map.on('mousemove', events.mousemove);\n ctx.map.on('mousedown', events.mousedown);\n ctx.map.on('mouseup', events.mouseup);\n ctx.map.on('data', events.data);\n\n ctx.map.on('touchmove', events.touchmove);\n ctx.map.on('touchstart', events.touchstart);\n ctx.map.on('touchend', events.touchend);\n\n ctx.container.addEventListener('mouseout', events.mouseout);\n\n if (ctx.options.keybindings) {\n ctx.container.addEventListener('keydown', events.keydown);\n ctx.container.addEventListener('keyup', events.keyup);\n }\n },\n removeEventListeners() {\n ctx.map.off('mousemove', events.mousemove);\n ctx.map.off('mousedown', events.mousedown);\n ctx.map.off('mouseup', events.mouseup);\n ctx.map.off('data', events.data);\n\n ctx.map.off('touchmove', events.touchmove);\n ctx.map.off('touchstart', events.touchstart);\n ctx.map.off('touchend', events.touchend);\n\n ctx.container.removeEventListener('mouseout', events.mouseout);\n\n if (ctx.options.keybindings) {\n ctx.container.removeEventListener('keydown', events.keydown);\n ctx.container.removeEventListener('keyup', events.keyup);\n }\n },\n trash(options) {\n currentMode.trash(options);\n },\n combineFeatures() {\n currentMode.combineFeatures();\n },\n uncombineFeatures() {\n currentMode.uncombineFeatures();\n },\n getMode() {\n return currentModeName;\n }\n };\n\n return api;\n}\n","/**\n * Derive a dense array (no `undefined`s) from a single value or array.\n *\n * @param {any} x\n * @return {Array<any>}\n */\nfunction toDenseArray(x) {\n return [].concat(x).filter(y => y !== undefined);\n}\n\nexport default toDenseArray;\n","import * as Constants from './constants';\n\nexport default function render() {\n // eslint-disable-next-line no-invalid-this\n const store = this;\n const mapExists = store.ctx.map && store.ctx.map.getSource(Constants.sources.HOT) !== undefined;\n if (!mapExists) return cleanup();\n\n const mode = store.ctx.events.currentModeName();\n\n store.ctx.ui.queueMapClasses({ mode });\n\n let newHotIds = [];\n let newColdIds = [];\n\n if (store.isDirty) {\n newColdIds = store.getAllIds();\n } else {\n newHotIds = store.getChangedIds().filter(id => store.get(id) !== undefined);\n newColdIds = store.sources.hot.filter(geojson => geojson.properties.id && newHotIds.indexOf(geojson.properties.id) === -1 && store.get(geojson.properties.id) !== undefined).map(geojson => geojson.properties.id);\n }\n\n store.sources.hot = [];\n const lastColdCount = store.sources.cold.length;\n store.sources.cold = store.isDirty ? [] : store.sources.cold.filter((geojson) => {\n const id = geojson.properties.id || geojson.properties.parent;\n return newHotIds.indexOf(id) === -1;\n });\n\n const coldChanged = lastColdCount !== store.sources.cold.length || newColdIds.length > 0;\n newHotIds.forEach(id => renderFeature(id, 'hot'));\n newColdIds.forEach(id => renderFeature(id, 'cold'));\n\n function renderFeature(id, source) {\n const feature = store.get(id);\n const featureInternal = feature.internal(mode);\n store.ctx.events.currentModeRender(featureInternal, (geojson) => {\n store.sources[source].push(geojson);\n });\n }\n\n if (coldChanged) {\n store.ctx.map.getSource(Constants.sources.COLD).setData({\n type: Constants.geojsonTypes.FEATURE_COLLECTION,\n features: store.sources.cold\n });\n }\n\n store.ctx.map.getSource(Constants.sources.HOT).setData({\n type: Constants.geojsonTypes.FEATURE_COLLECTION,\n features: store.sources.hot\n });\n\n if (store._emitSelectionChange) {\n store.ctx.map.fire(Constants.events.SELECTION_CHANGE, {\n features: store.getSelected().map(feature => feature.toGeoJSON()),\n points: store.getSelectedCoordinates().map(coordinate => ({\n type: Constants.geojsonTypes.FEATURE,\n properties: {},\n geometry: {\n type: Constants.geojsonTypes.POINT,\n coordinates: coordinate.coordinates\n }\n }))\n });\n store._emitSelectionChange = false;\n }\n\n if (store._deletedFeaturesToEmit.length) {\n const geojsonToEmit = store._deletedFeaturesToEmit.map(feature => feature.toGeoJSON());\n\n store._deletedFeaturesToEmit = [];\n\n store.ctx.map.fire(Constants.events.DELETE, {\n features: geojsonToEmit\n });\n }\n\n cleanup();\n store.ctx.map.fire(Constants.events.RENDER, {});\n\n function cleanup() {\n store.isDirty = false;\n store.clearChangedIds();\n }\n}\n","import toDenseArray from './lib/to_dense_array';\nimport StringSet from './lib/string_set';\nimport render from './render';\nimport {interactions} from './constants';\n\nexport default function Store(ctx) {\n this._features = {};\n this._featureIds = new StringSet();\n this._selectedFeatureIds = new StringSet();\n this._selectedCoordinates = [];\n this._changedFeatureIds = new StringSet();\n this._deletedFeaturesToEmit = [];\n this._emitSelectionChange = false;\n this._mapInitialConfig = {};\n this.ctx = ctx;\n this.sources = {\n hot: [],\n cold: []\n };\n\n // Deduplicate requests to render and tie them to animation frames.\n let renderRequest;\n this.render = () => {\n if (!renderRequest) {\n renderRequest = requestAnimationFrame(() => {\n renderRequest = null;\n render.call(this);\n });\n }\n };\n this.isDirty = false;\n}\n\n\n/**\n * Delays all rendering until the returned function is invoked\n * @return {Function} renderBatch\n */\nStore.prototype.createRenderBatch = function() {\n const holdRender = this.render;\n let numRenders = 0;\n this.render = function() {\n numRenders++;\n };\n\n return () => {\n this.render = holdRender;\n if (numRenders > 0) {\n this.render();\n }\n };\n};\n\n/**\n * Sets the store's state to dirty.\n * @return {Store} this\n */\nStore.prototype.setDirty = function() {\n this.isDirty = true;\n return this;\n};\n\n/**\n * Sets a feature's state to changed.\n * @param {string} featureId\n * @return {Store} this\n */\nStore.prototype.featureChanged = function(featureId) {\n this._changedFeatureIds.add(featureId);\n return this;\n};\n\n/**\n * Gets the ids of all features currently in changed state.\n * @return {Store} this\n */\nStore.prototype.getChangedIds = function() {\n return this._changedFeatureIds.values();\n};\n\n/**\n * Sets all features to unchanged state.\n * @return {Store} this\n */\nStore.prototype.clearChangedIds = function() {\n this._changedFeatureIds.clear();\n return this;\n};\n\n/**\n * Gets the ids of all features in the store.\n * @return {Store} this\n */\nStore.prototype.getAllIds = function() {\n return this._featureIds.values();\n};\n\n/**\n * Adds a feature to the store.\n * @param {Object} feature\n *\n * @return {Store} this\n */\nStore.prototype.add = function(feature) {\n this.featureChanged(feature.id);\n this._features[feature.id] = feature;\n this._featureIds.add(feature.id);\n return this;\n};\n\n/**\n * Deletes a feature or array of features from the store.\n * Cleans up after the deletion by deselecting the features.\n * If changes were made, sets the state to the dirty\n * and fires an event.\n * @param {string | Array<string>} featureIds\n * @param {Object} [options]\n * @param {Object} [options.silent] - If `true`, this invocation will not fire an event.\n * @return {Store} this\n */\nStore.prototype.delete = function(featureIds, options = {}) {\n toDenseArray(featureIds).forEach((id) => {\n if (!this._featureIds.has(id)) return;\n this._featureIds.delete(id);\n this._selectedFeatureIds.delete(id);\n if (!options.silent) {\n if (this._deletedFeaturesToEmit.indexOf(this._features[id]) === -1) {\n this._deletedFeaturesToEmit.push(this._features[id]);\n }\n }\n delete this._features[id];\n this.isDirty = true;\n });\n refreshSelectedCoordinates(this, options);\n return this;\n};\n\n/**\n * Returns a feature in the store matching the specified value.\n * @return {Object | undefined} feature\n */\nStore.prototype.get = function(id) {\n return this._features[id];\n};\n\n/**\n * Returns all features in the store.\n * @return {Array<Object>}\n */\nStore.prototype.getAll = function() {\n return Object.keys(this._features).map(id => this._features[id]);\n};\n\n/**\n * Adds features to the current selection.\n * @param {string | Array<string>} featureIds\n * @param {Object} [options]\n * @param {Object} [options.silent] - If `true`, this invocation will not fire an event.\n * @return {Store} this\n */\nStore.prototype.select = function(featureIds, options = {}) {\n toDenseArray(featureIds).forEach((id) => {\n if (this._selectedFeatureIds.has(id)) return;\n this._selectedFeatureIds.add(id);\n this._changedFeatureIds.add(id);\n if (!options.silent) {\n this._emitSelectionChange = true;\n }\n });\n return this;\n};\n\n/**\n * Deletes features from the current selection.\n * @param {string | Array<string>} featureIds\n * @param {Object} [options]\n * @param {Object} [options.silent] - If `true`, this invocation will not fire an event.\n * @return {Store} this\n */\nStore.prototype.deselect = function(featureIds, options = {}) {\n toDenseArray(featureIds).forEach((id) => {\n if (!this._selectedFeatureIds.has(id)) return;\n this._selectedFeatureIds.delete(id);\n this._changedFeatureIds.add(id);\n if (!options.silent) {\n this._emitSelectionChange = true;\n }\n });\n refreshSelectedCoordinates(this, options);\n return this;\n};\n\n/**\n * Clears the current selection.\n * @param {Object} [options]\n * @param {Object} [options.silent] - If `true`, this invocation will not fire an event.\n * @return {Store} this\n */\nStore.prototype.clearSelected = function(options = {}) {\n this.deselect(this._selectedFeatureIds.values(), { silent: options.silent });\n return this;\n};\n\n/**\n * Sets the store's selection, clearing any prior values.\n * If no feature ids are passed, the store is just cleared.\n * @param {string | Array<string> | undefined} featureIds\n * @param {Object} [options]\n * @param {Object} [options.silent] - If `true`, this invocation will not fire an event.\n * @return {Store} this\n */\nStore.prototype.setSelected = function(featureIds, options = {}) {\n featureIds = toDenseArray(featureIds);\n\n // Deselect any features not in the new selection\n this.deselect(this._selectedFeatureIds.values().filter(id => featureIds.indexOf(id) === -1), { silent: options.silent });\n\n // Select any features in the new selection that were not already selected\n this.select(featureIds.filter(id => !this._selectedFeatureIds.has(id)), { silent: options.silent });\n\n return this;\n};\n\n/**\n * Sets the store's coordinates selection, clearing any prior values.\n * @param {Array<Array<string>>} coordinates\n * @return {Store} this\n */\nStore.prototype.setSelectedCoordinates = function(coordinates) {\n this._selectedCoordinates = coordinates;\n this._emitSelectionChange = true;\n return this;\n};\n\n/**\n * Clears the current coordinates selection.\n * @param {Object} [options]\n * @return {Store} this\n */\nStore.prototype.clearSelectedCoordinates = function() {\n this._selectedCoordinates = [];\n this._emitSelectionChange = true;\n return this;\n};\n\n/**\n * Returns the ids of features in the current selection.\n * @return {Array<string>} Selected feature ids.\n */\nStore.prototype.getSelectedIds = function() {\n return this._selectedFeatureIds.values();\n};\n\n/**\n * Returns features in the current selection.\n * @return {Array<Object>} Selected features.\n */\nStore.prototype.getSelected = function() {\n return this._selectedFeatureIds.values().map(id => this.get(id));\n};\n\n/**\n * Returns selected coordinates in the currently selected feature.\n * @return {Array<Object>} Selected coordinates.\n */\nStore.prototype.getSelectedCoordinates = function() {\n const selected = this._selectedCoordinates.map((coordinate) => {\n const feature = this.get(coordinate.feature_id);\n return {\n coordinates: feature.getCoordinate(coordinate.coord_path)\n };\n });\n return selected;\n};\n\n/**\n * Indicates whether a feature is selected.\n * @param {string} featureId\n * @return {boolean} `true` if the feature is selected, `false` if not.\n */\nStore.prototype.isSelected = function(featureId) {\n return this._selectedFeatureIds.has(featureId);\n};\n\n/**\n * Sets a property on the given feature\n * @param {string} featureId\n * @param {string} property property\n * @param {string} property value\n*/\nStore.prototype.setFeatureProperty = function(featureId, property, value) {\n this.get(featureId).setProperty(property, value);\n this.featureChanged(featureId);\n};\n\nfunction refreshSelectedCoordinates(store, options) {\n const newSelectedCoordinates = store._selectedCoordinates.filter(point => store._selectedFeatureIds.has(point.feature_id));\n if (store._selectedCoordinates.length !== newSelectedCoordinates.length && !options.silent) {\n store._emitSelectionChange = true;\n }\n store._selectedCoordinates = newSelectedCoordinates;\n}\n\n/**\n * Stores the initial config for a map, so that we can set it again after we're done.\n*/\nStore.prototype.storeMapConfig = function() {\n interactions.forEach((interaction) => {\n const interactionSet = this.ctx.map[interaction];\n if (interactionSet) {\n this._mapInitialConfig[interaction] = this.ctx.map[interaction].isEnabled();\n }\n });\n};\n\n/**\n * Restores the initial config for a map, ensuring all is well.\n*/\nStore.prototype.restoreMapConfig = function() {\n Object.keys(this._mapInitialConfig).forEach((key) => {\n const value = this._mapInitialConfig[key];\n if (value) {\n this.ctx.map[key].enable();\n } else {\n this.ctx.map[key].disable();\n }\n });\n};\n\n/**\n * Returns the initial state of an interaction setting.\n * @param {string} interaction\n * @return {boolean} `true` if the interaction is enabled, `false` if not.\n * Defaults to `true`. (Todo: include defaults.)\n*/\nStore.prototype.getInitialConfigValue = function(interaction) {\n if (this._mapInitialConfig[interaction] !== undefined) {\n return this._mapInitialConfig[interaction];\n } else {\n // This needs to be set to whatever the default is for that interaction\n // It seems to be true for all cases currently, so let's send back `true`.\n return true;\n }\n};\n","module.exports = extend\n\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nfunction extend() {\n var target = {}\n\n for (var i = 0; i < arguments.length; i++) {\n var source = arguments[i]\n\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n target[key] = source[key]\n }\n }\n }\n\n return target\n}\n","import xtend from 'xtend';\nimport * as Constants from './constants';\nimport { SRCenter } from './lib/SRCenter';\n\nconst classTypes = ['mode', 'feature', 'mouse'];\n\nexport default function(ctx) {\n const buttonElements = {};\n let activeButton = null;\n\n let currentMapClasses = {\n mode: null, // e.g. mode-direct_select\n feature: null, // e.g. feature-vertex\n mouse: null // e.g. mouse-move\n };\n\n let nextMapClasses = {\n mode: null,\n feature: null,\n mouse: null\n };\n\n function clearMapClasses() {\n queueMapClasses({mode:null, feature:null, mouse:null});\n updateMapClasses();\n }\n\n function queueMapClasses(options) {\n nextMapClasses = xtend(nextMapClasses, options);\n }\n\n function updateMapClasses() {\n if (!ctx.container) return;\n\n const classesToRemove = [];\n const classesToAdd = [];\n\n classTypes.forEach((type) => {\n if (nextMapClasses[type] === currentMapClasses[type]) return;\n\n classesToRemove.push(`${type}-${currentMapClasses[type]}`);\n if (nextMapClasses[type] !== null) {\n classesToAdd.push(`${type}-${nextMapClasses[type]}`);\n }\n });\n\n if (classesToRemove.length > 0) {\n ctx.container.classList.remove(...classesToRemove);\n }\n\n if (classesToAdd.length > 0) {\n ctx.container.classList.add(...classesToAdd);\n }\n\n currentMapClasses = xtend(currentMapClasses, nextMapClasses);\n }\n\n function createControlButton(id, options = {}) {\n const button = document.createElement('button');\n button.className = `${Constants.classes.CONTROL_BUTTON} ${options.className}`;\n button.setAttribute('title', options.title);\n options.container.appendChild(button);\n\n button.addEventListener('click', (e) => {\n e.preventDefault();\n e.stopPropagation();\n\n const clickedButton = e.target;\n if (clickedButton === activeButton) {\n deactivateButtons();\n options.onDeactivate();\n return;\n }\n\n setActiveButton(id);\n options.onActivate();\n }, true);\n\n return button;\n }\n\n function deactivateButtons() {\n if (!activeButton) return;\n activeButton.classList.remove(Constants.classes.ACTIVE_BUTTON);\n activeButton = null;\n }\n\n function setActiveButton(id) {\n deactivateButtons();\n\n const button = buttonElements[id];\n if (!button) return;\n\n if (button && id !== 'trash') {\n button.classList.add(Constants.classes.ACTIVE_BUTTON);\n activeButton = button;\n }\n }\n\n function addButtons() {\n const controls = ctx.options.controls;\n const controlGroup = document.createElement('div');\n controlGroup.className = `${Constants.classes.CONTROL_GROUP} ${Constants.classes.CONTROL_BASE}`;\n\n if (!controls) return controlGroup;\n\n if (controls[Constants.types.POINT]) {\n buttonElements[Constants.types.POINT] = createControlButton(Constants.types.POINT, {\n container: controlGroup,\n className: Constants.classes.CONTROL_BUTTON_POINT,\n title: `Marker tool ${ctx.options.keybindings ? '(m)' : ''}`,\n onActivate: () => ctx.events.changeMode(Constants.modes.DRAW_POINT),\n onDeactivate: () => ctx.events.trash()\n });\n }\n \n if (controls[Constants.types.LINE]) {\n buttonElements[Constants.types.LINE] = createControlButton(Constants.types.LINE, {\n container: controlGroup,\n className: Constants.classes.CONTROL_BUTTON_LINE,\n title: `LineString tool ${ctx.options.keybindings ? '(l)' : ''}`,\n onActivate: () => ctx.events.changeMode(Constants.modes.DRAW_LINE_STRING),\n onDeactivate: () => ctx.events.trash()\n });\n }\n\n if (controls[Constants.types.POLYGON]) {\n buttonElements[Constants.types.POLYGON] = createControlButton(Constants.types.POLYGON, {\n container: controlGroup,\n className: Constants.classes.CONTROL_BUTTON_POLYGON,\n title: `Polygon tool ${ctx.options.keybindings ? '(p)' : ''}`,\n onActivate: () => ctx.events.changeMode(Constants.modes.DRAW_POLYGON),\n onDeactivate: () => ctx.events.trash()\n });\n }\n\n if (controls.trash) {\n buttonElements.trash = createControlButton('trash', {\n container: controlGroup,\n className: Constants.classes.CONTROL_BUTTON_TRASH,\n title: 'Delete',\n onActivate: () => {\n ctx.events.trash();\n }\n });\n }\n\n if (controls.combine_features) {\n buttonElements.combine_features = createControlButton('combineFeatures', {\n container: controlGroup,\n className: Constants.classes.CONTROL_BUTTON_COMBINE_FEATURES,\n title: 'Combine',\n onActivate: () => {\n ctx.events.combineFeatures();\n }\n });\n }\n\n if (controls.uncombine_features) {\n buttonElements.uncombine_features = createControlButton('uncombineFeatures', {\n container: controlGroup,\n className: Constants.classes.CONTROL_BUTTON_UNCOMBINE_FEATURES,\n title: 'Uncombine',\n onActivate: () => {\n ctx.events.uncombineFeatures();\n }\n });\n }\n\n if (controls.srmode) {\n buttonElements.srmode = createControlButton('srmode', {\n container: controlGroup,\n className: Constants.classes.CONTROL_BUTTON_SRMODE,\n title: 'SRMode',\n onActivate: () => {\n let tmp = ctx.store.getSelected();\n if(tmp.length === 0 || tmp[0].type === \"Point\" || tmp[0].type === \"MultiPoint\"){\n deactivateButtons();\n return;\n }\n ctx.events.changeMode('SRMode', {\n canScale: true,\n canRotate: true, // only rotation enabled\n canTrash: false, // disable feature delete\n \n rotatePivot: SRCenter.Center, // rotate around center\n scaleCenter: SRCenter.Opposite, // scale around opposite vertex\n \n singleRotationPoint: true, // only one rotation point\n rotationPointRadius: 1.2, // offset rotation point\n \n canSelectFeatures: true,\n });\n },\n onDeactivate: () => {\n ctx.events.changeMode(Constants.modes.SIMPLE_SELECT);\n }\n });\n }\n\n return controlGroup;\n }\n\n function removeButtons() {\n Object.keys(buttonElements).forEach((buttonId) => {\n const button = buttonElements[buttonId];\n if (button.parentNode) {\n button.parentNode.removeChild(button);\n }\n delete buttonElements[buttonId];\n });\n }\n\n return {\n setActiveButton,\n queueMapClasses,\n updateMapClasses,\n clearMapClasses,\n addButtons,\n removeButtons,\n deactivateButtons\n };\n}\n","import events from './events';\nimport Store from './store';\nimport ui from './ui';\nimport * as Constants from './constants';\nimport xtend from 'xtend';\n\nexport default function(ctx) {\n\n let controlContainer = null;\n let mapLoadedInterval = null;\n\n const setup = {\n onRemove() {\n // Stop connect attempt in the event that control is removed before map is loaded\n ctx.map.off('load', setup.connect);\n clearInterval(mapLoadedInterval);\n\n setup.removeLayers();\n ctx.store.restoreMapConfig();\n ctx.ui.removeButtons();\n ctx.events.removeEventListeners();\n ctx.ui.clearMapClasses();\n if (ctx.boxZoomInitial) ctx.map.boxZoom.enable();\n ctx.map = null;\n ctx.container = null;\n ctx.store = null;\n\n if (controlContainer && controlContainer.parentNode) controlContainer.parentNode.removeChild(controlContainer);\n controlContainer = null;\n\n return this;\n },\n connect() {\n ctx.map.off('load', setup.connect);\n clearInterval(mapLoadedInterval);\n setup.addLayers();\n ctx.store.storeMapConfig();\n ctx.events.addEventListeners();\n },\n onAdd(map) {\n if (process.env.NODE_ENV !== 'test') {\n // Monkey patch to resolve breaking change to `fire` introduced by\n // mapbox-gl-js. See mapbox/mapbox-gl-draw/issues/766.\n const _fire = map.fire;\n map.fire = function(type, event) {\n // eslint-disable-next-line\n let args = arguments;\n\n if (_fire.length === 1 && arguments.length !== 1) {\n args = [xtend({}, { type }, event)];\n }\n\n return _fire.apply(map, args);\n };\n }\n\n ctx.map = map;\n ctx.events = events(ctx);\n ctx.ui = ui(ctx);\n ctx.container = map.getContainer();\n ctx.store = new Store(ctx);\n\n\n controlContainer = ctx.ui.addButtons();\n\n if (ctx.options.boxSelect) {\n ctx.boxZoomInitial = map.boxZoom.isEnabled();\n map.boxZoom.disable();\n // Need to toggle dragPan on and off or else first\n // dragPan disable attempt in simple_select doesn't work\n map.dragPan.disable();\n map.dragPan.enable();\n }\n\n if (map.loaded()) {\n setup.connect();\n } else {\n map.on('load', setup.connect);\n mapLoadedInterval = setInterval(() => { if (map.loaded()) setup.connect(); }, 16);\n }\n\n ctx.events.start();\n return controlContainer;\n },\n addLayers() {\n // drawn features style\n if(!ctx.map.getSource(Constants.sources.COLD)){\n ctx.map.addSource(Constants.sources.COLD, {\n data: {\n type: Constants.geojsonTypes.FEATURE_COLLECTION,\n features: []\n },\n type: 'geojson'\n });\n } \n\n // hot features style\n if(!ctx.map.getSource(Constants.sources.HOT)){\n ctx.map.addSource(Constants.sources.HOT, {\n data: {\n type: Constants.geojsonTypes.FEATURE_COLLECTION,\n features: []\n },\n type: 'geojson'\n });\n } \n\n ctx.options.styles.forEach((style) => {\n if(!ctx.map.getLayer(style.id)){\n ctx.map.addLayer(style);\n }\n });\n\n ctx.store.setDirty(true);\n ctx.store.render();\n },\n // Check for layers and sources before attempting to remove\n // If user adds draw control and removes it before the map is loaded, layers and sources will be missing\n removeLayers() {\n ctx.options.styles.forEach((style) => {\n if (ctx.map.getLayer(style.id)) {\n ctx.map.removeLayer(style.id);\n }\n });\n\n if (ctx.map.getSource(Constants.sources.COLD)) {\n ctx.map.removeSource(Constants.sources.COLD);\n }\n\n if (ctx.map.getSource(Constants.sources.HOT)) {\n ctx.map.removeSource(Constants.sources.HOT);\n }\n }\n };\n\n ctx.setup = setup;\n\n return setup;\n}\n","export default [\n {\n 'id': 'gl-draw-polygon-fill-inactive',\n 'type': 'fill',\n 'filter': ['all',\n ['==', 'active', 'false'],\n ['==', '$type', 'Polygon'],\n ['!=', 'mode', 'static']\n ],\n 'paint': {\n 'fill-color': '#3bb2d0',\n 'fill-outline-color': '#3bb2d0',\n 'fill-opacity': 0.1\n }\n },\n {\n 'id': 'gl-draw-polygon-fill-active',\n 'type': 'fill',\n 'filter': ['all', ['==', 'active', 'true'], ['==', '$type', 'Polygon']],\n 'paint': {\n 'fill-color': '#fbb03b',\n 'fill-outline-color': '#fbb03b',\n 'fill-opacity': 0.1\n }\n },\n {\n 'id': 'gl-draw-polygon-midpoint',\n 'type': 'circle',\n 'filter': ['all',\n ['==', '$type', 'Point'],\n ['==', 'meta', 'midpoint']],\n 'paint': {\n 'circle-radius': 3,\n 'circle-color': '#fbb03b'\n }\n },\n {\n 'id': 'gl-draw-polygon-stroke-inactive',\n 'type': 'line',\n 'filter': ['all',\n ['==', 'active', 'false'],\n ['==', '$type', 'Polygon'],\n ['!=', 'mode', 'static']\n ],\n 'layout': {\n 'line-cap': 'round',\n 'line-join': 'round'\n },\n 'paint': {\n 'line-color': '#3bb2d0',\n 'line-width': 2\n }\n },\n {\n 'id': 'gl-draw-polygon-stroke-active',\n 'type': 'line',\n 'filter': ['all', ['==', 'active', 'true'], ['==', '$type', 'Polygon']],\n 'layout': {\n 'line-cap': 'round',\n 'line-join': 'round'\n },\n 'paint': {\n 'line-color': '#fbb03b',\n 'line-dasharray': [0.2, 2],\n 'line-width': 2\n }\n },\n {\n 'id': 'gl-draw-line-inactive',\n 'type': 'line',\n 'filter': ['all',\n ['==', 'active', 'false'],\n ['==', '$type', 'LineString'],\n ['!=', 'mode', 'static']\n ],\n 'layout': {\n 'line-cap': 'round',\n 'line-join': 'round'\n },\n 'paint': {\n 'line-color': '#3bb2d0',\n 'line-width': 2\n }\n },\n {\n 'id': 'gl-draw-line-active',\n 'type': 'line',\n 'filter': ['all',\n ['==', '$type', 'LineString'],\n ['==', 'active', 'true']\n ],\n 'layout': {\n 'line-cap': 'round',\n 'line-join': 'round'\n },\n 'paint': {\n 'line-color': '#fbb03b',\n 'line-dasharray': [0.2, 2],\n 'line-width': 2\n }\n },\n {\n 'id': 'gl-draw-polygon-and-line-vertex-stroke-inactive',\n 'type': 'circle',\n 'filter': ['all',\n ['==', 'meta', 'vertex'],\n ['==', '$type', 'Point'],\n ['!=', 'mode', 'static']\n ],\n 'paint': {\n 'circle-radius': 5,\n 'circle-color': '#fff'\n }\n },\n {\n 'id': 'gl-draw-polygon-and-line-vertex-inactive',\n 'type': 'circle',\n 'filter': ['all',\n ['==', 'meta', 'vertex'],\n ['==', '$type', 'Point'],\n ['!=', 'mode', 'static']\n ],\n 'paint': {\n 'circle-radius': 3,\n 'circle-color': '#fbb03b'\n }\n },\n {\n 'id': 'gl-draw-point-point-stroke-inactive',\n 'type': 'circle',\n 'filter': ['all',\n ['==', 'active', 'false'],\n ['==', '$type', 'Point'],\n ['==', 'meta', 'feature'],\n ['!=', 'mode', 'static']\n ],\n 'paint': {\n 'circle-radius': 5,\n 'circle-opacity': 1,\n 'circle-color': '#fff'\n }\n },\n {\n 'id': 'gl-draw-point-inactive',\n 'type': 'circle',\n 'filter': ['all',\n ['==', 'active', 'false'],\n ['==', '$type', 'Point'],\n ['==', 'meta', 'feature'],\n ['!=', 'mode', 'static']\n ],\n 'paint': {\n 'circle-radius': 3,\n 'circle-color': '#3bb2d0'\n }\n },\n {\n 'id': 'gl-draw-point-stroke-active',\n 'type': 'circle',\n 'filter': ['all',\n ['==', '$type', 'Point'],\n ['==', 'active', 'true'],\n ['!=', 'meta', 'midpoint']\n ],\n 'paint': {\n 'circle-radius': 7,\n 'circle-color': '#fff'\n }\n },\n {\n 'id': 'gl-draw-point-active',\n 'type': 'circle',\n 'filter': ['all',\n ['==', '$type', 'Point'],\n ['!=', 'meta', 'midpoint'],\n ['==', 'active', 'true']],\n 'paint': {\n 'circle-radius': 5,\n 'circle-color': '#fbb03b'\n }\n },\n {\n 'id': 'gl-draw-polygon-fill-static',\n 'type': 'fill',\n 'filter': ['all', ['==', 'mode', 'static'], ['==', '$type', 'Polygon']],\n 'paint': {\n 'fill-color': '#404040',\n 'fill-outline-color': '#404040',\n 'fill-opacity': 0.1\n }\n },\n {\n 'id': 'gl-draw-polygon-stroke-static',\n 'type': 'line',\n 'filter': ['all', ['==', 'mode', 'static'], ['==', '$type', 'Polygon']],\n 'layout': {\n 'line-cap': 'round',\n 'line-join': 'round'\n },\n 'paint': {\n 'line-color': '#404040',\n 'line-width': 2\n }\n },\n {\n 'id': 'gl-draw-line-static',\n 'type': 'line',\n 'filter': ['all', ['==', 'mode', 'static'], ['==', '$type', 'LineString']],\n 'layout': {\n 'line-cap': 'round',\n 'line-join': 'round'\n },\n 'paint': {\n 'line-color': '#404040',\n 'line-width': 2\n }\n },\n {\n 'id': 'gl-draw-point-static',\n 'type': 'circle',\n 'filter': ['all', ['==', 'mode', 'static'], ['==', '$type', 'Point']],\n 'paint': {\n 'circle-radius': 5,\n 'circle-color': '#404040'\n }\n }\n];\n","import * as Constants from '../constants';\n\nexport function isOfMetaType(type) {\n return function(e) {\n const featureTarget = e.featureTarget;\n if (!featureTarget) return false;\n if (!featureTarget.properties) return false;\n return featureTarget.properties.meta === type;\n };\n}\n\nexport function isShiftMousedown(e) {\n if (!e.originalEvent) return false;\n if (!e.originalEvent.shiftKey) return false;\n return e.originalEvent.button === 0;\n}\n\nexport function isActiveFeature(e) {\n if (!e.featureTarget) return false;\n if (!e.featureTarget.properties) return false;\n return e.featureTarget.properties.active === Constants.activeStates.ACTIVE &&\n e.featureTarget.properties.meta === Constants.meta.FEATURE;\n}\n\nexport function isInactiveFeature(e) {\n if (!e.featureTarget) return false;\n if (!e.featureTarget.properties) return false;\n return e.featureTarget.properties.active === Constants.activeStates.INACTIVE &&\n e.featureTarget.properties.meta === Constants.meta.FEATURE;\n}\n\nexport function noTarget(e) {\n return e.featureTarget === undefined;\n}\n\nexport function isFeature(e) {\n if (!e.featureTarget) return false;\n if (!e.featureTarget.properties) return false;\n return e.featureTarget.properties.meta === Constants.meta.FEATURE;\n}\n\nexport function isVertex(e) {\n const featureTarget = e.featureTarget;\n if (!featureTarget) return false;\n if (!featureTarget.properties) return false;\n return featureTarget.properties.meta === Constants.meta.VERTEX;\n}\n\nexport function isShiftDown(e) {\n if (!e.originalEvent) return false;\n return e.originalEvent.shiftKey === true;\n}\n\nexport function isEscapeKey(e) {\n return e.keyCode === 27;\n}\n\nexport function isEnterKey(e) {\n return e.keyCode === 13;\n}\n\nexport function isTrue() {\n return true;\n}\n","'use strict';\n\nmodule.exports = Point;\n\n/**\n * A standalone point geometry with useful accessor, comparison, and\n * modification methods.\n *\n * @class Point\n * @param {Number} x the x-coordinate. this could be longitude or screen\n * pixels, or any other sort of unit.\n * @param {Number} y the y-coordinate. this could be latitude or screen\n * pixels, or any other sort of unit.\n * @example\n * var point = new Point(-77, 38);\n */\nfunction Point(x, y) {\n this.x = x;\n this.y = y;\n}\n\nPoint.prototype = {\n\n /**\n * Clone this point, returning a new point that can be modified\n * without affecting the old one.\n * @return {Point} the clone\n */\n clone: function() { return new Point(this.x, this.y); },\n\n /**\n * Add this point's x & y coordinates to another point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n add: function(p) { return this.clone()._add(p); },\n\n /**\n * Subtract this point's x & y coordinates to from point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n sub: function(p) { return this.clone()._sub(p); },\n\n /**\n * Multiply this point's x & y coordinates by point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n multByPoint: function(p) { return this.clone()._multByPoint(p); },\n\n /**\n * Divide this point's x & y coordinates by point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n divByPoint: function(p) { return this.clone()._divByPoint(p); },\n\n /**\n * Multiply this point's x & y coordinates by a factor,\n * yielding a new point.\n * @param {Point} k factor\n * @return {Point} output point\n */\n mult: function(k) { return this.clone()._mult(k); },\n\n /**\n * Divide this point's x & y coordinates by a factor,\n * yielding a new point.\n * @param {Point} k factor\n * @return {Point} output point\n */\n div: function(k) { return this.clone()._div(k); },\n\n /**\n * Rotate this point around the 0, 0 origin by an angle a,\n * given in radians\n * @param {Number} a angle to rotate around, in radians\n * @return {Point} output point\n */\n rotate: function(a) { return this.clone()._rotate(a); },\n\n /**\n * Rotate this point around p point by an angle a,\n * given in radians\n * @param {Number} a angle to rotate around, in radians\n * @param {Point} p Point to rotate around\n * @return {Point} output point\n */\n rotateAround: function(a,p) { return this.clone()._rotateAround(a,p); },\n\n /**\n * Multiply this point by a 4x1 transformation matrix\n * @param {Array<Number>} m transformation matrix\n * @return {Point} output point\n */\n matMult: function(m) { return this.clone()._matMult(m); },\n\n /**\n * Calculate this point but as a unit vector from 0, 0, meaning\n * that the distance from the resulting point to the 0, 0\n * coordinate will be equal to 1 and the angle from the resulting\n * point to the 0, 0 coordinate will be the same as before.\n * @return {Point} unit vector point\n */\n unit: function() { return this.clone()._unit(); },\n\n /**\n * Compute a perpendicular point, where the new y coordinate\n * is the old x coordinate and the new x coordinate is the old y\n * coordinate multiplied by -1\n * @return {Point} perpendicular point\n */\n perp: function() { return this.clone()._perp(); },\n\n /**\n * Return a version of this point with the x & y coordinates\n * rounded to integers.\n * @return {Point} rounded point\n */\n round: function() { return this.clone()._round(); },\n\n /**\n * Return the magitude of this point: this is the Euclidean\n * distance from the 0, 0 coordinate to this point's x and y\n * coordinates.\n * @return {Number} magnitude\n */\n mag: function() {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n },\n\n /**\n * Judge whether this point is equal to another point, returning\n * true or false.\n * @param {Point} other the other point\n * @return {boolean} whether the points are equal\n */\n equals: function(other) {\n return this.x === other.x &&\n this.y === other.y;\n },\n\n /**\n * Calculate the distance from this point to another point\n * @param {Point} p the other point\n * @return {Number} distance\n */\n dist: function(p) {\n return Math.sqrt(this.distSqr(p));\n },\n\n /**\n * Calculate the distance from this point to another point,\n * without the square root step. Useful if you're comparing\n * relative distances.\n * @param {Point} p the other point\n * @return {Number} distance\n */\n distSqr: function(p) {\n var dx = p.x - this.x,\n dy = p.y - this.y;\n return dx * dx + dy * dy;\n },\n\n /**\n * Get the angle from the 0, 0 coordinate to this point, in radians\n * coordinates.\n * @return {Number} angle\n */\n angle: function() {\n return Math.atan2(this.y, this.x);\n },\n\n /**\n * Get the angle from this point to another point, in radians\n * @param {Point} b the other point\n * @return {Number} angle\n */\n angleTo: function(b) {\n return Math.atan2(this.y - b.y, this.x - b.x);\n },\n\n /**\n * Get the angle between this point and another point, in radians\n * @param {Point} b the other point\n * @return {Number} angle\n */\n angleWith: function(b) {\n return this.angleWithSep(b.x, b.y);\n },\n\n /*\n * Find the angle of the two vectors, solving the formula for\n * the cross product a x b = |a||b|sin(θ) for θ.\n * @param {Number} x the x-coordinate\n * @param {Number} y the y-coordinate\n * @return {Number} the angle in radians\n */\n angleWithSep: function(x, y) {\n return Math.atan2(\n this.x * y - this.y * x,\n this.x * x + this.y * y);\n },\n\n _matMult: function(m) {\n var x = m[0] * this.x + m[1] * this.y,\n y = m[2] * this.x + m[3] * this.y;\n this.x = x;\n this.y = y;\n return this;\n },\n\n _add: function(p) {\n this.x += p.x;\n this.y += p.y;\n return this;\n },\n\n _sub: function(p) {\n this.x -= p.x;\n this.y -= p.y;\n return this;\n },\n\n _mult: function(k) {\n this.x *= k;\n this.y *= k;\n return this;\n },\n\n _div: function(k) {\n this.x /= k;\n this.y /= k;\n return this;\n },\n\n _multByPoint: function(p) {\n this.x *= p.x;\n this.y *= p.y;\n return this;\n },\n\n _divByPoint: function(p) {\n this.x /= p.x;\n this.y /= p.y;\n return this;\n },\n\n _unit: function() {\n this._div(this.mag());\n return this;\n },\n\n _perp: function() {\n var y = this.y;\n this.y = this.x;\n this.x = -y;\n return this;\n },\n\n _rotate: function(angle) {\n var cos = Math.cos(angle),\n sin = Math.sin(angle),\n x = cos * this.x - sin * this.y,\n y = sin * this.x + cos * this.y;\n this.x = x;\n this.y = y;\n return this;\n },\n\n _rotateAround: function(angle, p) {\n var cos = Math.cos(angle),\n sin = Math.sin(angle),\n x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y),\n y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y);\n this.x = x;\n this.y = y;\n return this;\n },\n\n _round: function() {\n this.x = Math.round(this.x);\n this.y = Math.round(this.y);\n return this;\n }\n};\n\n/**\n * Construct a point from an array if necessary, otherwise if the input\n * is already a Point, or an unknown type, return it unchanged\n * @param {Array<Number>|Point|*} a any kind of input value\n * @return {Point} constructed point, or passed-through value.\n * @example\n * // this\n * var point = Point.convert([0, 1]);\n * // is equivalent to\n * var point = new Point(0, 1);\n */\nPoint.convert = function (a) {\n if (a instanceof Point) {\n return a;\n }\n if (Array.isArray(a)) {\n return new Point(a[0], a[1]);\n }\n return a;\n};\n","import Point from '@mapbox/point-geometry';\n\n/**\n * Returns a Point representing a mouse event's position\n * relative to a containing element.\n *\n * @param {MouseEvent} mouseEvent\n * @param {Node} container\n * @returns {Point}\n */\nfunction mouseEventPoint(mouseEvent, container) {\n const rect = container.getBoundingClientRect();\n return new Point(\n mouseEvent.clientX - rect.left - (container.clientLeft || 0),\n mouseEvent.clientY - rect.top - (container.clientTop || 0)\n );\n}\n\nexport default mouseEventPoint;\n","import * as Constants from '../constants';\n\n/**\n * Returns GeoJSON for a Point representing the\n * vertex of another feature.\n *\n * @param {string} parentId\n * @param {Array<number>} coordinates\n * @param {string} path - Dot-separated numbers indicating exactly\n * where the point exists within its parent feature's coordinates.\n * @param {boolean} selected\n * @return {GeoJSON} Point\n */\nexport default function(parentId, coordinates, path, selected) {\n return {\n type: Constants.geojsonTypes.FEATURE,\n properties: {\n meta: Constants.meta.VERTEX,\n parent: parentId,\n coord_path: path,\n active: (selected) ? Constants.activeStates.ACTIVE : Constants.activeStates.INACTIVE\n },\n geometry: {\n type: Constants.geojsonTypes.POINT,\n coordinates\n }\n };\n}\n","import * as Constants from '../constants';\n\nexport default function(parent, startVertex, endVertex) {\n const startCoord = startVertex.geometry.coordinates;\n const endCoord = endVertex.geometry.coordinates;\n\n // If a coordinate exceeds the projection, we can't calculate a midpoint,\n // so run away\n if (startCoord[1] > Constants.LAT_RENDERED_MAX ||\n startCoord[1] < Constants.LAT_RENDERED_MIN ||\n endCoord[1] > Constants.LAT_RENDERED_MAX ||\n endCoord[1] < Constants.LAT_RENDERED_MIN) {\n return null;\n }\n\n const mid = {\n lng: (startCoord[0] + endCoord[0]) / 2,\n lat: (startCoord[1] + endCoord[1]) / 2\n };\n\n return {\n type: Constants.geojsonTypes.FEATURE,\n properties: {\n meta: Constants.meta.MIDPOINT,\n parent,\n lng: mid.lng,\n lat: mid.lat,\n coord_path: endVertex.properties.coord_path\n },\n geometry: {\n type: Constants.geojsonTypes.POINT,\n coordinates: [mid.lng, mid.lat]\n }\n };\n}\n","import createVertex from './create_vertex';\nimport createMidpoint from './create_midpoint';\nimport * as Constants from '../constants';\n\nfunction createSupplementaryPoints(geojson, options = {}, basePath = null) {\n const { type, coordinates } = geojson.geometry;\n const featureId = geojson.properties && geojson.properties.id;\n\n let supplementaryPoints = [];\n\n if (type === Constants.geojsonTypes.POINT) {\n // For points, just create a vertex\n supplementaryPoints.push(createVertex(featureId, coordinates, basePath, isSelectedPath(basePath)));\n } else if (type === Constants.geojsonTypes.POLYGON) {\n // Cycle through a Polygon's rings and\n // process each line\n coordinates.forEach((line, lineIndex) => {\n processLine(line, (basePath !== null) ? `${basePath}.${lineIndex}` : String(lineIndex));\n });\n } else if (type === Constants.geojsonTypes.LINE_STRING) {\n processLine(coordinates, basePath);\n } else if (type.indexOf(Constants.geojsonTypes.MULTI_PREFIX) === 0) {\n processMultiGeometry();\n }\n\n function processLine(line, lineBasePath) {\n let firstPointString = '';\n let lastVertex = null;\n line.forEach((point, pointIndex) => {\n const pointPath = (lineBasePath !== undefined && lineBasePath !== null) ? `${lineBasePath}.${pointIndex}` : String(pointIndex);\n const vertex = createVertex(featureId, point, pointPath, isSelectedPath(pointPath));\n\n // If we're creating midpoints, check if there was a\n // vertex before this one. If so, add a midpoint\n // between that vertex and this one.\n if (options.midpoints && lastVertex) {\n const midpoint = createMidpoint(featureId, lastVertex, vertex);\n if (midpoint) {\n supplementaryPoints.push(midpoint);\n }\n }\n lastVertex = vertex;\n\n // A Polygon line's last point is the same as the first point. If we're on the last\n // point, we want to draw a midpoint before it but not another vertex on it\n // (since we already a vertex there, from the first point).\n const stringifiedPoint = JSON.stringify(point);\n if (firstPointString !== stringifiedPoint) {\n supplementaryPoints.push(vertex);\n }\n if (pointIndex === 0) {\n firstPointString = stringifiedPoint;\n }\n });\n }\n\n function isSelectedPath(path) {\n if (!options.selectedPaths) return false;\n return options.selectedPaths.indexOf(path) !== -1;\n }\n\n // Split a multi-geometry into constituent\n // geometries, and accumulate the supplementary points\n // for each of those constituents\n function processMultiGeometry() {\n const subType = type.replace(Constants.geojsonTypes.MULTI_PREFIX, '');\n coordinates.forEach((subCoordinates, index) => {\n const subFeature = {\n type: Constants.geojsonTypes.FEATURE,\n properties: geojson.properties,\n geometry: {\n type: subType,\n coordinates: subCoordinates\n }\n };\n supplementaryPoints = supplementaryPoints.concat(createSupplementaryPoints(subFeature, options, index));\n });\n }\n\n return supplementaryPoints;\n}\n\nexport default createSupplementaryPoints;\n","export default {\n enable(ctx) {\n setTimeout(() => {\n // First check we've got a map and some context.\n if (!ctx.map || !ctx.map.doubleClickZoom || !ctx._ctx || !ctx._ctx.store || !ctx._ctx.store.getInitialConfigValue) return;\n // Now check initial state wasn't false (we leave it disabled if so)\n if (!ctx._ctx.store.getInitialConfigValue('doubleClickZoom')) return;\n ctx.map.doubleClickZoom.enable();\n }, 0);\n },\n disable(ctx) {\n setTimeout(() => {\n if (!ctx.map || !ctx.map.doubleClickZoom) return;\n // Always disable here, as it's necessary in some cases.\n ctx.map.doubleClickZoom.disable();\n }, 0);\n }\n};\n","module.exports = normalize;\n\nvar types = {\n Point: 'geometry',\n MultiPoint: 'geometry',\n LineString: 'geometry',\n MultiLineString: 'geometry',\n Polygon: 'geometry',\n MultiPolygon: 'geometry',\n GeometryCollection: 'geometry',\n Feature: 'feature',\n FeatureCollection: 'featurecollection'\n};\n\n/**\n * Normalize a GeoJSON feature into a FeatureCollection.\n *\n * @param {object} gj geojson data\n * @returns {object} normalized geojson data\n */\nfunction normalize(gj) {\n if (!gj || !gj.type) return null;\n var type = types[gj.type];\n if (!type) return null;\n\n if (type === 'geometry') {\n return {\n type: 'FeatureCollection',\n features: [{\n type: 'Feature',\n properties: {},\n geometry: gj\n }]\n };\n } else if (type === 'feature') {\n return {\n type: 'FeatureCollection',\n features: [gj]\n };\n } else if (type === 'featurecollection') {\n return gj;\n }\n}\n","export default function e(t){switch(t&&t.type||null){case\"FeatureCollection\":return t.features=t.features.reduce(function(t,r){return t.concat(e(r))},[]),t;case\"Feature\":return t.geometry?e(t.geometry).map(function(e){var r={type:\"Feature\",properties:JSON.parse(JSON.stringify(t.properties)),geometry:e};return void 0!==t.id&&(r.id=t.id),r}):[t];case\"MultiPoint\":return t.coordinates.map(function(e){return{type:\"Point\",coordinates:e}});case\"MultiPolygon\":return t.coordinates.map(function(e){return{type:\"Polygon\",coordinates:e}});case\"MultiLineString\":return t.coordinates.map(function(e){return{type:\"LineString\",coordinates:e}});case\"GeometryCollection\":return t.geometries.map(e).reduce(function(e,t){return e.concat(t)},[]);case\"Point\":case\"Polygon\":case\"LineString\":return[t]}}\n//# sourceMappingURL=index.es.js.map\n","module.exports = function flatten(list) {\n return _flatten(list);\n\n function _flatten(list) {\n if (Array.isArray(list) && list.length &&\n typeof list[0] === 'number') {\n return [list];\n }\n return list.reduce(function (acc, item) {\n if (Array.isArray(item) && Array.isArray(item[0])) {\n return acc.concat(_flatten(item));\n } else {\n acc.push(item);\n return acc;\n }\n }, []);\n }\n};\n","var geojsonNormalize = require('@mapbox/geojson-normalize'),\n geojsonFlatten = require('geojson-flatten'),\n flatten = require('./flatten');\n\nif (!(geojsonFlatten instanceof Function)) geojsonFlatten = geojsonFlatten.default;\n\nmodule.exports = function(_) {\n if (!_) return [];\n var normalized = geojsonFlatten(geojsonNormalize(_)),\n coordinates = [];\n normalized.features.forEach(function(feature) {\n if (!feature.geometry) return;\n coordinates = coordinates.concat(flatten(feature.geometry.coordinates));\n });\n return coordinates;\n};\n","var traverse = module.exports = function (obj) {\n return new Traverse(obj);\n};\n\nfunction Traverse (obj) {\n this.value = obj;\n}\n\nTraverse.prototype.get = function (ps) {\n var node = this.value;\n for (var i = 0; i < ps.length; i ++) {\n var key = ps[i];\n if (!node || !hasOwnProperty.call(node, key)) {\n node = undefined;\n break;\n }\n node = node[key];\n }\n return node;\n};\n\nTraverse.prototype.has = function (ps) {\n var node = this.value;\n for (var i = 0; i < ps.length; i ++) {\n var key = ps[i];\n if (!node || !hasOwnProperty.call(node, key)) {\n return false;\n }\n node = node[key];\n }\n return true;\n};\n\nTraverse.prototype.set = function (ps, value) {\n var node = this.value;\n for (var i = 0; i < ps.length - 1; i ++) {\n var key = ps[i];\n if (!hasOwnProperty.call(node, key)) node[key] = {};\n node = node[key];\n }\n node[ps[i]] = value;\n return value;\n};\n\nTraverse.prototype.map = function (cb) {\n return walk(this.value, cb, true);\n};\n\nTraverse.prototype.forEach = function (cb) {\n this.value = walk(this.value, cb, false);\n return this.value;\n};\n\nTraverse.prototype.reduce = function (cb, init) {\n var skip = arguments.length === 1;\n var acc = skip ? this.value : init;\n this.forEach(function (x) {\n if (!this.isRoot || !skip) {\n acc = cb.call(this, acc, x);\n }\n });\n return acc;\n};\n\nTraverse.prototype.paths = function () {\n var acc = [];\n this.forEach(function (x) {\n acc.push(this.path); \n });\n return acc;\n};\n\nTraverse.prototype.nodes = function () {\n var acc = [];\n this.forEach(function (x) {\n acc.push(this.node);\n });\n return acc;\n};\n\nTraverse.prototype.clone = function () {\n var parents = [], nodes = [];\n \n return (function clone (src) {\n for (var i = 0; i < parents.length; i++) {\n if (parents[i] === src) {\n return nodes[i];\n }\n }\n \n if (typeof src === 'object' && src !== null) {\n var dst = copy(src);\n \n parents.push(src);\n nodes.push(dst);\n \n forEach(objectKeys(src), function (key) {\n dst[key] = clone(src[key]);\n });\n \n parents.pop();\n nodes.pop();\n return dst;\n }\n else {\n return src;\n }\n })(this.value);\n};\n\nfunction walk (root, cb, immutable) {\n var path = [];\n var parents = [];\n var alive = true;\n \n return (function walker (node_) {\n var node = immutable ? copy(node_) : node_;\n var modifiers = {};\n \n var keepGoing = true;\n \n var state = {\n node : node,\n node_ : node_,\n path : [].concat(path),\n parent : parents[parents.length - 1],\n parents : parents,\n key : path.slice(-1)[0],\n isRoot : path.length === 0,\n level : path.length,\n circular : null,\n update : function (x, stopHere) {\n if (!state.isRoot) {\n state.parent.node[state.key] = x;\n }\n state.node = x;\n if (stopHere) keepGoing = false;\n },\n 'delete' : function (stopHere) {\n delete state.parent.node[state.key];\n if (stopHere) keepGoing = false;\n },\n remove : function (stopHere) {\n if (isArray(state.parent.node)) {\n state.parent.node.splice(state.key, 1);\n }\n else {\n delete state.parent.node[state.key];\n }\n if (stopHere) keepGoing = false;\n },\n keys : null,\n before : function (f) { modifiers.before = f },\n after : function (f) { modifiers.after = f },\n pre : function (f) { modifiers.pre = f },\n post : function (f) { modifiers.post = f },\n stop : function () { alive = false },\n block : function () { keepGoing = false }\n };\n \n if (!alive) return state;\n \n function updateState() {\n if (typeof state.node === 'object' && state.node !== null) {\n if (!state.keys || state.node_ !== state.node) {\n state.keys = objectKeys(state.node)\n }\n \n state.isLeaf = state.keys.length == 0;\n \n for (var i = 0; i < parents.length; i++) {\n if (parents[i].node_ === node_) {\n state.circular = parents[i];\n break;\n }\n }\n }\n else {\n state.isLeaf = true;\n state.keys = null;\n }\n \n state.notLeaf = !state.isLeaf;\n state.notRoot = !state.isRoot;\n }\n \n updateState();\n \n // use return values to update if defined\n var ret = cb.call(state, state.node);\n if (ret !== undefined && state.update) state.update(ret);\n \n if (modifiers.before) modifiers.before.call(state, state.node);\n \n if (!keepGoing) return state;\n \n if (typeof state.node == 'object'\n && state.node !== null && !state.circular) {\n parents.push(state);\n \n updateState();\n \n forEach(state.keys, function (key, i) {\n path.push(key);\n \n if (modifiers.pre) modifiers.pre.call(state, state.node[key], key);\n \n var child = walker(state.node[key]);\n if (immutable && hasOwnProperty.call(state.node, key)) {\n state.node[key] = child.node;\n }\n \n child.isLast = i == state.keys.length - 1;\n child.isFirst = i == 0;\n \n if (modifiers.post) modifiers.post.call(state, child);\n \n path.pop();\n });\n parents.pop();\n }\n \n if (modifiers.after) modifiers.after.call(state, state.node);\n \n return state;\n })(root).node;\n}\n\nfunction copy (src) {\n if (typeof src === 'object' && src !== null) {\n var dst;\n \n if (isArray(src)) {\n dst = [];\n }\n else if (isDate(src)) {\n dst = new Date(src.getTime ? src.getTime() : src);\n }\n else if (isRegExp(src)) {\n dst = new RegExp(src);\n }\n else if (isError(src)) {\n dst = { message: src.message };\n }\n else if (isBoolean(src)) {\n dst = new Boolean(src);\n }\n else if (isNumber(src)) {\n dst = new Number(src);\n }\n else if (isString(src)) {\n dst = new String(src);\n }\n else if (Object.create && Object.getPrototypeOf) {\n dst = Object.create(Object.getPrototypeOf(src));\n }\n else if (src.constructor === Object) {\n dst = {};\n }\n else {\n var proto =\n (src.constructor && src.constructor.prototype)\n || src.__proto__\n || {}\n ;\n var T = function () {};\n T.prototype = proto;\n dst = new T;\n }\n \n forEach(objectKeys(src), function (key) {\n dst[key] = src[key];\n });\n return dst;\n }\n else return src;\n}\n\nvar objectKeys = Object.keys || function keys (obj) {\n var res = [];\n for (var key in obj) res.push(key)\n return res;\n};\n\nfunction toS (obj) { return Object.prototype.toString.call(obj) }\nfunction isDate (obj) { return toS(obj) === '[object Date]' }\nfunction isRegExp (obj) { return toS(obj) === '[object RegExp]' }\nfunction isError (obj) { return toS(obj) === '[object Error]' }\nfunction isBoolean (obj) { return toS(obj) === '[object Boolean]' }\nfunction isNumber (obj) { return toS(obj) === '[object Number]' }\nfunction isString (obj) { return toS(obj) === '[object String]' }\n\nvar isArray = Array.isArray || function isArray (xs) {\n return Object.prototype.toString.call(xs) === '[object Array]';\n};\n\nvar forEach = function (xs, fn) {\n if (xs.forEach) return xs.forEach(fn)\n else for (var i = 0; i < xs.length; i++) {\n fn(xs[i], i, xs);\n }\n};\n\nforEach(objectKeys(Traverse.prototype), function (key) {\n traverse[key] = function (obj) {\n var args = [].slice.call(arguments, 1);\n var t = new Traverse(obj);\n return t[key].apply(t, args);\n };\n});\n\nvar hasOwnProperty = Object.hasOwnProperty || function (obj, key) {\n return key in obj;\n};\n","module.exports = Extent;\n\nfunction Extent(bbox) {\n if (!(this instanceof Extent)) {\n return new Extent(bbox);\n }\n this._bbox = bbox || [Infinity, Infinity, -Infinity, -Infinity];\n this._valid = !!bbox;\n}\n\nExtent.prototype.include = function(ll) {\n this._valid = true;\n this._bbox[0] = Math.min(this._bbox[0], ll[0]);\n this._bbox[1] = Math.min(this._bbox[1], ll[1]);\n this._bbox[2] = Math.max(this._bbox[2], ll[0]);\n this._bbox[3] = Math.max(this._bbox[3], ll[1]);\n return this;\n};\n\nExtent.prototype.equals = function(_) {\n var other;\n if (_ instanceof Extent) { other = _.bbox(); } else { other = _; }\n return this._bbox[0] == other[0] &&\n this._bbox[1] == other[1] &&\n this._bbox[2] == other[2] &&\n this._bbox[3] == other[3];\n};\n\nExtent.prototype.center = function(_) {\n if (!this._valid) return null;\n return [\n (this._bbox[0] + this._bbox[2]) / 2,\n (this._bbox[1] + this._bbox[3]) / 2]\n};\n\nExtent.prototype.union = function(_) {\n this._valid = true;\n var other;\n if (_ instanceof Extent) { other = _.bbox(); } else { other = _; }\n this._bbox[0] = Math.min(this._bbox[0], other[0]);\n this._bbox[1] = Math.min(this._bbox[1], other[1]);\n this._bbox[2] = Math.max(this._bbox[2], other[2]);\n this._bbox[3] = Math.max(this._bbox[3], other[3]);\n return this;\n};\n\nExtent.prototype.bbox = function() {\n if (!this._valid) return null;\n return this._bbox;\n};\n\nExtent.prototype.contains = function(ll) {\n if (!ll) return this._fastContains();\n if (!this._valid) return null;\n var lon = ll[0], lat = ll[1];\n return this._bbox[0] <= lon &&\n this._bbox[1] <= lat &&\n this._bbox[2] >= lon &&\n this._bbox[3] >= lat;\n};\n\nExtent.prototype.intersect = function(_) {\n if (!this._valid) return null;\n\n var other;\n if (_ instanceof Extent) { other = _.bbox(); } else { other = _; }\n\n return !(\n this._bbox[0] > other[2] ||\n this._bbox[2] < other[0] ||\n this._bbox[3] < other[1] ||\n this._bbox[1] > other[3]\n );\n};\n\nExtent.prototype._fastContains = function() {\n if (!this._valid) return new Function('return null;');\n var body = 'return ' +\n this._bbox[0] + '<= ll[0] &&' +\n this._bbox[1] + '<= ll[1] &&' +\n this._bbox[2] + '>= ll[0] &&' +\n this._bbox[3] + '>= ll[1]';\n return new Function('ll', body);\n};\n\nExtent.prototype.polygon = function() {\n if (!this._valid) return null;\n return {\n type: 'Polygon',\n coordinates: [\n [\n // W, S\n [this._bbox[0], this._bbox[1]],\n // E, S\n [this._bbox[2], this._bbox[1]],\n // E, N\n [this._bbox[2], this._bbox[3]],\n // W, N\n [this._bbox[0], this._bbox[3]],\n // W, S\n [this._bbox[0], this._bbox[1]]\n ]\n ]\n };\n};\n","var geojsonCoords = require('@mapbox/geojson-coords'),\n traverse = require('traverse'),\n extent = require('@mapbox/extent');\n\nvar geojsonTypesByDataAttributes = {\n features: ['FeatureCollection'],\n coordinates: ['Point', 'MultiPoint', 'LineString', 'MultiLineString', 'Polygon', 'MultiPolygon'],\n geometry: ['Feature'],\n geometries: ['GeometryCollection']\n}\n\nvar dataAttributes = Object.keys(geojsonTypesByDataAttributes);\n\nmodule.exports = function(_) {\n return getExtent(_).bbox();\n};\n\nmodule.exports.polygon = function(_) {\n return getExtent(_).polygon();\n};\n\nmodule.exports.bboxify = function(_) {\n return traverse(_).map(function(value) {\n if (!value) return ;\n\n var isValid = dataAttributes.some(function(attribute){\n if(value[attribute]) {\n return geojsonTypesByDataAttributes[attribute].indexOf(value.type) !== -1;\n }\n return false;\n });\n\n if(isValid){\n value.bbox = getExtent(value).bbox();\n this.update(value);\n }\n\n });\n};\n\nfunction getExtent(_) {\n var ext = extent(),\n coords = geojsonCoords(_);\n for (var i = 0; i < coords.length; i++) ext.include(coords[i]);\n return ext;\n}\n","import extent from '@mapbox/geojson-extent';\nimport * as Constants from '../constants';\n\nconst {\n LAT_MIN,\n LAT_MAX,\n LAT_RENDERED_MIN,\n LAT_RENDERED_MAX,\n LNG_MIN,\n LNG_MAX\n} = Constants;\n\n// Ensure that we do not drag north-south far enough for\n// - any part of any feature to exceed the poles\n// - any feature to be completely lost in the space between the projection's\n// edge and the poles, such that it couldn't be re-selected and moved back\nexport default function(geojsonFeatures, delta) {\n // \"inner edge\" = a feature's latitude closest to the equator\n let northInnerEdge = LAT_MIN;\n let southInnerEdge = LAT_MAX;\n // \"outer edge\" = a feature's latitude furthest from the equator\n let northOuterEdge = LAT_MIN;\n let southOuterEdge = LAT_MAX;\n\n let westEdge = LNG_MAX;\n let eastEdge = LNG_MIN;\n\n geojsonFeatures.forEach((feature) => {\n const bounds = extent(feature);\n const featureSouthEdge = bounds[1];\n const featureNorthEdge = bounds[3];\n const featureWestEdge = bounds[0];\n const featureEastEdge = bounds[2];\n if (featureSouthEdge > northInnerEdge) northInnerEdge = featureSouthEdge;\n if (featureNorthEdge < southInnerEdge) southInnerEdge = featureNorthEdge;\n if (featureNorthEdge > northOuterEdge) northOuterEdge = featureNorthEdge;\n if (featureSouthEdge < southOuterEdge) southOuterEdge = featureSouthEdge;\n if (featureWestEdge < westEdge) westEdge = featureWestEdge;\n if (featureEastEdge > eastEdge) eastEdge = featureEastEdge;\n });\n\n\n // These changes are not mutually exclusive: we might hit the inner\n // edge but also have hit the outer edge and therefore need\n // another readjustment\n const constrainedDelta = delta;\n if (northInnerEdge + constrainedDelta.lat > LAT_RENDERED_MAX) {\n constrainedDelta.lat = LAT_RENDERED_MAX - northInnerEdge;\n }\n if (northOuterEdge + constrainedDelta.lat > LAT_MAX) {\n constrainedDelta.lat = LAT_MAX - northOuterEdge;\n }\n if (southInnerEdge + constrainedDelta.lat < LAT_RENDERED_MIN) {\n constrainedDelta.lat = LAT_RENDERED_MIN - southInnerEdge;\n }\n if (southOuterEdge + constrainedDelta.lat < LAT_MIN) {\n constrainedDelta.lat = LAT_MIN - southOuterEdge;\n }\n if (westEdge + constrainedDelta.lng <= LNG_MIN) {\n constrainedDelta.lng += Math.ceil(Math.abs(constrainedDelta.lng) / 360) * 360;\n }\n if (eastEdge + constrainedDelta.lng >= LNG_MAX) {\n constrainedDelta.lng -= Math.ceil(Math.abs(constrainedDelta.lng) / 360) * 360;\n }\n\n return constrainedDelta;\n}\n","import constrainFeatureMovement from './constrain_feature_movement';\nimport * as Constants from '../constants';\n\nexport default function(features, delta) {\n const constrainedDelta = constrainFeatureMovement(features.map(feature => feature.toGeoJSON()), delta);\n\n features.forEach((feature) => {\n const currentCoordinates = feature.getCoordinates();\n\n const moveCoordinate = (coord) => {\n const point = {\n lng: coord[0] + constrainedDelta.lng,\n lat: coord[1] + constrainedDelta.lat\n };\n return [point.lng, point.lat];\n };\n const moveRing = ring => ring.map(coord => moveCoordinate(coord));\n const moveMultiPolygon = multi => multi.map(ring => moveRing(ring));\n\n let nextCoordinates;\n if (feature.type === Constants.geojsonTypes.POINT) {\n nextCoordinates = moveCoordinate(currentCoordinates);\n } else if (feature.type === Constants.geojsonTypes.LINE_STRING || feature.type === Constants.geojsonTypes.MULTI_POINT) {\n nextCoordinates = currentCoordinates.map(moveCoordinate);\n } else if (feature.type === Constants.geojsonTypes.POLYGON || feature.type === Constants.geojsonTypes.MULTI_LINE_STRING) {\n nextCoordinates = currentCoordinates.map(moveRing);\n } else if (feature.type === Constants.geojsonTypes.MULTI_POLYGON) {\n nextCoordinates = currentCoordinates.map(moveMultiPolygon);\n }\n\n feature.incomingCoords(nextCoordinates);\n });\n}\n","import * as CommonSelectors from '../lib/common_selectors';\nimport mouseEventPoint from '../lib/mouse_event_point';\nimport createSupplementaryPoints from '../lib/create_supplementary_points';\nimport StringSet from '../lib/string_set';\nimport doubleClickZoom from '../lib/double_click_zoom';\nimport moveFeatures from '../lib/move_features';\nimport * as Constants from '../constants';\n\nconst SimpleSelect = {};\n\nSimpleSelect.onSetup = function(opts) {\n // turn the opts into state.\n const state = {\n dragMoveLocation: null,\n boxSelectStartLocation: null,\n boxSelectElement: undefined,\n boxSelecting: false,\n canBoxSelect: false,\n dragMoving: false,\n canDragMove: false,\n initiallySelectedFeatureIds: opts.featureIds || []\n };\n\n this.setSelected(state.initiallySelectedFeatureIds.filter(id => this.getFeature(id) !== undefined));\n this.fireActionable();\n\n this.setActionableState({\n combineFeatures: true,\n uncombineFeatures: true,\n trash: true\n });\n\n return state;\n};\n\nSimpleSelect.fireUpdate = function() {\n this.map.fire(Constants.events.UPDATE, {\n action: Constants.updateActions.MOVE,\n features: this.getSelected().map(f => f.toGeoJSON())\n });\n};\n\nSimpleSelect.fireActionable = function() {\n const selectedFeatures = this.getSelected();\n\n const multiFeatures = selectedFeatures.filter(\n feature => this.isInstanceOf('MultiFeature', feature)\n );\n\n let combineFeatures = false;\n\n if (selectedFeatures.length > 1) {\n combineFeatures = true;\n const featureType = selectedFeatures[0].type.replace('Multi', '');\n selectedFeatures.forEach((feature) => {\n if (feature.type.replace('Multi', '') !== featureType) {\n combineFeatures = false;\n }\n });\n }\n\n const uncombineFeatures = multiFeatures.length > 0;\n const trash = selectedFeatures.length > 0;\n\n this.setActionableState({\n combineFeatures, uncombineFeatures, trash\n });\n};\n\nSimpleSelect.getUniqueIds = function(allFeatures) {\n if (!allFeatures.length) return [];\n const ids = allFeatures.map(s => s.properties.id)\n .filter(id => id !== undefined)\n .reduce((memo, id) => {\n memo.add(id);\n return memo;\n }, new StringSet());\n\n return ids.values();\n};\n\nSimpleSelect.stopExtendedInteractions = function(state) {\n if (state.boxSelectElement) {\n if (state.boxSelectElement.parentNode) state.boxSelectElement.parentNode.removeChild(state.boxSelectElement);\n state.boxSelectElement = null;\n }\n\n this.map.dragPan.enable();\n\n state.boxSelecting = false;\n state.canBoxSelect = false;\n state.dragMoving = false;\n state.canDragMove = false;\n};\n\nSimpleSelect.onStop = function() {\n doubleClickZoom.enable(this);\n};\n\nSimpleSelect.onMouseMove = function(state, e) {\n const isFeature = CommonSelectors.isFeature(e);\n if (isFeature && state.dragMoving) this.fireUpdate();\n\n // On mousemove that is not a drag, stop extended interactions.\n // This is useful if you drag off the canvas, release the button,\n // then move the mouse back over the canvas --- we don't allow the\n // interaction to continue then, but we do let it continue if you held\n // the mouse button that whole time\n this.stopExtendedInteractions(state);\n\n // Skip render\n return true;\n};\n\nSimpleSelect.onMouseOut = function(state) {\n // As soon as you mouse leaves the canvas, update the feature\n if (state.dragMoving) return this.fireUpdate();\n\n // Skip render\n return true;\n};\n\nSimpleSelect.onTap = SimpleSelect.onClick = function(state, e) {\n // Click (with or without shift) on no feature\n if (CommonSelectors.noTarget(e)) return this.clickAnywhere(state, e); // also tap\n if (CommonSelectors.isOfMetaType(Constants.meta.VERTEX)(e)) return this.clickOnVertex(state, e); //tap\n if (CommonSelectors.isFeature(e)) return this.clickOnFeature(state, e);\n};\n\nSimpleSelect.clickAnywhere = function (state) {\n // Clear the re-render selection\n const wasSelected = this.getSelectedIds();\n if (wasSelected.length) {\n this.clearSelectedFeatures();\n wasSelected.forEach(id => this.doRender(id));\n }\n doubleClickZoom.enable(this);\n this.stopExtendedInteractions(state);\n};\n\nSimpleSelect.clickOnVertex = function(state, e) {\n // Enter direct select mode\n this.changeMode(Constants.modes.DIRECT_SELECT, {\n featureId: e.featureTarget.properties.parent,\n coordPath: e.featureTarget.properties.coord_path,\n startPos: e.lngLat\n });\n this.updateUIClasses({ mouse: Constants.cursors.MOVE });\n};\n\nSimpleSelect.startOnActiveFeature = function(state, e) {\n // Stop any already-underway extended interactions\n this.stopExtendedInteractions(state);\n\n // Disable map.dragPan immediately so it can't start\n this.map.dragPan.disable();\n\n // Re-render it and enable drag move\n this.doRender(e.featureTarget.properties.id);\n\n // Set up the state for drag moving\n state.canDragMove = true;\n state.dragMoveLocation = e.lngLat;\n};\n\nSimpleSelect.clickOnFeature = function(state, e) {\n // Stop everything\n doubleClickZoom.disable(this);\n this.stopExtendedInteractions(state);\n\n const isShiftClick = CommonSelectors.isShiftDown(e);\n const selectedFeatureIds = this.getSelectedIds();\n const featureId = e.featureTarget.properties.id;\n const isFeatureSelected = this.isSelected(featureId);\n\n // Click (without shift) on any selected feature but a point\n if (!isShiftClick && isFeatureSelected && this.getFeature(featureId).type !== Constants.geojsonTypes.POINT) {\n // Enter direct select mode\n return this.changeMode(Constants.modes.DIRECT_SELECT, {\n featureId\n });\n }\n\n // Shift-click on a selected feature\n if (isFeatureSelected && isShiftClick) {\n // Deselect it\n this.deselect(featureId);\n this.updateUIClasses({ mouse: Constants.cursors.POINTER });\n if (selectedFeatureIds.length === 1) {\n doubleClickZoom.enable(this);\n }\n // Shift-click on an unselected feature\n } else if (!isFeatureSelected && isShiftClick) {\n // Add it to the selection\n this.select(featureId);\n this.updateUIClasses({ mouse: Constants.cursors.MOVE });\n // Click (without shift) on an unselected feature\n } else if (!isFeatureSelected && !isShiftClick) {\n // Make it the only selected feature\n selectedFeatureIds.forEach(id => this.doRender(id));\n this.setSelected(featureId);\n this.updateUIClasses({ mouse: Constants.cursors.MOVE });\n }\n\n // No matter what, re-render the clicked feature\n this.doRender(featureId);\n};\n\nSimpleSelect.onMouseDown = function(state, e) {\n if (CommonSelectors.isActiveFeature(e)) return this.startOnActiveFeature(state, e);\n if (this.drawConfig.boxSelect && CommonSelectors.isShiftMousedown(e)) return this.startBoxSelect(state, e);\n};\n\nSimpleSelect.startBoxSelect = function(state, e) {\n this.stopExtendedInteractions(state);\n this.map.dragPan.disable();\n // Enable box select\n state.boxSelectStartLocation = mouseEventPoint(e.originalEvent, this.map.getContainer());\n state.canBoxSelect = true;\n};\n\nSimpleSelect.onTouchStart = function(state, e) {\n if (CommonSelectors.isActiveFeature(e)) return this.startOnActiveFeature(state, e);\n};\n\nSimpleSelect.onDrag = function(state, e) {\n if (state.canDragMove) return this.dragMove(state, e);\n if (this.drawConfig.boxSelect && state.canBoxSelect) return this.whileBoxSelect(state, e);\n};\n\nSimpleSelect.whileBoxSelect = function(state, e) {\n state.boxSelecting = true;\n this.updateUIClasses({ mouse: Constants.cursors.ADD });\n\n // Create the box node if it doesn't exist\n if (!state.boxSelectElement) {\n state.boxSelectElement = document.createElement('div');\n state.boxSelectElement.classList.add(Constants.classes.BOX_SELECT);\n this.map.getContainer().appendChild(state.boxSelectElement);\n }\n\n // Adjust the box node's width and xy position\n const current = mouseEventPoint(e.originalEvent, this.map.getContainer());\n const minX = Math.min(state.boxSelectStartLocation.x, current.x);\n const maxX = Math.max(state.boxSelectStartLocation.x, current.x);\n const minY = Math.min(state.boxSelectStartLocation.y, current.y);\n const maxY = Math.max(state.boxSelectStartLocation.y, current.y);\n const translateValue = `translate(${minX}px, ${minY}px)`;\n state.boxSelectElement.style.transform = translateValue;\n state.boxSelectElement.style.WebkitTransform = translateValue;\n state.boxSelectElement.style.width = `${maxX - minX}px`;\n state.boxSelectElement.style.height = `${maxY - minY}px`;\n};\n\nSimpleSelect.dragMove = function(state, e) {\n // Dragging when drag move is enabled\n state.dragMoving = true;\n e.originalEvent.stopPropagation();\n\n const delta = {\n lng: e.lngLat.lng - state.dragMoveLocation.lng,\n lat: e.lngLat.lat - state.dragMoveLocation.lat\n };\n\n moveFeatures(this.getSelected(), delta);\n\n state.dragMoveLocation = e.lngLat;\n};\n\nSimpleSelect.onTouchEnd = SimpleSelect.onMouseUp = function(state, e) {\n // End any extended interactions\n if (state.dragMoving) {\n this.fireUpdate();\n } else if (state.boxSelecting) {\n const bbox = [\n state.boxSelectStartLocation,\n mouseEventPoint(e.originalEvent, this.map.getContainer())\n ];\n const featuresInBox = this.featuresAt(null, bbox, 'click');\n const idsToSelect = this.getUniqueIds(featuresInBox)\n .filter(id => !this.isSelected(id));\n\n if (idsToSelect.length) {\n this.select(idsToSelect);\n idsToSelect.forEach(id => this.doRender(id));\n this.updateUIClasses({ mouse: Constants.cursors.MOVE });\n }\n }\n this.stopExtendedInteractions(state);\n};\n\nSimpleSelect.toDisplayFeatures = function(state, geojson, display) {\n geojson.properties.active = (this.isSelected(geojson.properties.id)) ?\n Constants.activeStates.ACTIVE : Constants.activeStates.INACTIVE;\n display(geojson);\n this.fireActionable();\n if (geojson.properties.active !== Constants.activeStates.ACTIVE ||\n geojson.geometry.type === Constants.geojsonTypes.POINT) return;\n createSupplementaryPoints(geojson).forEach(display);\n};\n\nSimpleSelect.onTrash = function() {\n this.deleteFeature(this.getSelectedIds());\n this.fireActionable();\n};\n\nSimpleSelect.onCombineFeatures = function() {\n const selectedFeatures = this.getSelected();\n\n if (selectedFeatures.length === 0 || selectedFeatures.length < 2) return;\n\n const coordinates = [], featuresCombined = [];\n const featureType = selectedFeatures[0].type.replace('Multi', '');\n\n for (let i = 0; i < selectedFeatures.length; i++) {\n const feature = selectedFeatures[i];\n\n if (feature.type.replace('Multi', '') !== featureType) {\n return;\n }\n if (feature.type.includes('Multi')) {\n feature.getCoordinates().forEach((subcoords) => {\n coordinates.push(subcoords);\n });\n } else {\n coordinates.push(feature.getCoordinates());\n }\n\n featuresCombined.push(feature.toGeoJSON());\n }\n\n if (featuresCombined.length > 1) {\n const multiFeature = this.newFeature({\n type: Constants.geojsonTypes.FEATURE,\n properties: featuresCombined[0].properties,\n geometry: {\n type: `Multi${featureType}`,\n coordinates\n }\n });\n\n this.addFeature(multiFeature);\n this.deleteFeature(this.getSelectedIds(), { silent: true });\n this.setSelected([multiFeature.id]);\n\n this.map.fire(Constants.events.COMBINE_FEATURES, {\n createdFeatures: [multiFeature.toGeoJSON()],\n deletedFeatures: featuresCombined\n });\n }\n this.fireActionable();\n};\n\nSimpleSelect.onUncombineFeatures = function() {\n const selectedFeatures = this.getSelected();\n if (selectedFeatures.length === 0) return;\n\n const createdFeatures = [];\n const featuresUncombined = [];\n\n for (let i = 0; i < selectedFeatures.length; i++) {\n const feature = selectedFeatures[i];\n\n if (this.isInstanceOf('MultiFeature', feature)) {\n feature.getFeatures().forEach((subFeature) => {\n this.addFeature(subFeature);\n subFeature.properties = feature.properties;\n createdFeatures.push(subFeature.toGeoJSON());\n this.select([subFeature.id]);\n });\n this.deleteFeature(feature.id, { silent: true });\n featuresUncombined.push(feature.toGeoJSON());\n }\n }\n\n if (createdFeatures.length > 1) {\n this.map.fire(Constants.events.UNCOMBINE_FEATURES, {\n createdFeatures,\n deletedFeatures: featuresUncombined\n });\n }\n this.fireActionable();\n};\n\nexport default SimpleSelect;\n","import {noTarget, isOfMetaType, isActiveFeature, isInactiveFeature, isShiftDown} from '../lib/common_selectors';\nimport createSupplementaryPoints from '../lib/create_supplementary_points';\nimport constrainFeatureMovement from '../lib/constrain_feature_movement';\nimport doubleClickZoom from '../lib/double_click_zoom';\nimport * as Constants from '../constants';\nimport moveFeatures from '../lib/move_features';\n\nconst isVertex = isOfMetaType(Constants.meta.VERTEX);\nconst isMidpoint = isOfMetaType(Constants.meta.MIDPOINT);\n\nconst DirectSelect = {};\n\n// INTERNAL FUCNTIONS\n\nDirectSelect.fireUpdate = function() {\n this.map.fire(Constants.events.UPDATE, {\n action: Constants.updateActions.CHANGE_COORDINATES,\n features: this.getSelected().map(f => f.toGeoJSON())\n });\n};\n\nDirectSelect.fireActionable = function(state) {\n this.setActionableState({\n combineFeatures: false,\n uncombineFeatures: false,\n trash: state.selectedCoordPaths.length > 0\n });\n};\n\nDirectSelect.startDragging = function(state, e) {\n this.map.dragPan.disable();\n state.canDragMove = true;\n state.dragMoveLocation = e.lngLat;\n};\n\nDirectSelect.stopDragging = function(state) {\n this.map.dragPan.enable();\n state.dragMoving = false;\n state.canDragMove = false;\n state.dragMoveLocation = null;\n};\n\nDirectSelect.onVertex = function (state, e) {\n this.startDragging(state, e);\n const about = e.featureTarget.properties;\n const selectedIndex = state.selectedCoordPaths.indexOf(about.coord_path);\n if (!isShiftDown(e) && selectedIndex === -1) {\n state.selectedCoordPaths = [about.coord_path];\n } else if (isShiftDown(e) && selectedIndex === -1) {\n state.selectedCoordPaths.push(about.coord_path);\n }\n\n const selectedCoordinates = this.pathsToCoordinates(state.featureId, state.selectedCoordPaths);\n this.setSelectedCoordinates(selectedCoordinates);\n};\n\nDirectSelect.onMidpoint = function(state, e) {\n this.startDragging(state, e);\n const about = e.featureTarget.properties;\n state.feature.addCoordinate(about.coord_path, about.lng, about.lat);\n this.fireUpdate();\n state.selectedCoordPaths = [about.coord_path];\n};\n\nDirectSelect.pathsToCoordinates = function(featureId, paths) {\n return paths.map(coord_path => ({ feature_id: featureId, coord_path }));\n};\n\nDirectSelect.onFeature = function(state, e) {\n if (state.selectedCoordPaths.length === 0) this.startDragging(state, e);\n else this.stopDragging(state);\n};\n\nDirectSelect.dragFeature = function(state, e, delta) {\n moveFeatures(this.getSelected(), delta);\n state.dragMoveLocation = e.lngLat;\n};\n\nDirectSelect.dragVertex = function(state, e, delta) {\n const selectedCoords = state.selectedCoordPaths.map(coord_path => state.feature.getCoordinate(coord_path));\n const selectedCoordPoints = selectedCoords.map(coords => ({\n type: Constants.geojsonTypes.FEATURE,\n properties: {},\n geometry: {\n type: Constants.geojsonTypes.POINT,\n coordinates: coords\n }\n }));\n\n const constrainedDelta = constrainFeatureMovement(selectedCoordPoints, delta);\n for (let i = 0; i < selectedCoords.length; i++) {\n const coord = selectedCoords[i];\n state.feature.updateCoordinate(state.selectedCoordPaths[i], coord[0] + constrainedDelta.lng, coord[1] + constrainedDelta.lat);\n }\n};\n\nDirectSelect.clickNoTarget = function () {\n this.changeMode(Constants.modes.SIMPLE_SELECT);\n};\n\nDirectSelect.clickInactive = function () {\n this.changeMode(Constants.modes.SIMPLE_SELECT);\n};\n\nDirectSelect.clickActiveFeature = function (state) {\n state.selectedCoordPaths = [];\n this.clearSelectedCoordinates();\n state.feature.changed();\n};\n\n// EXTERNAL FUNCTIONS\n\nDirectSelect.onSetup = function(opts) {\n const featureId = opts.featureId;\n const feature = this.getFeature(featureId);\n\n if (!feature) {\n throw new Error('You must provide a featureId to enter direct_select mode');\n }\n\n if (feature.type === Constants.geojsonTypes.POINT) {\n throw new TypeError('direct_select mode doesn\\'t handle point features');\n }\n\n const state = {\n featureId,\n feature,\n dragMoveLocation: opts.startPos || null,\n dragMoving: false,\n canDragMove: false,\n selectedCoordPaths: opts.coordPath ? [opts.coordPath] : []\n };\n\n this.setSelectedCoordinates(this.pathsToCoordinates(featureId, state.selectedCoordPaths));\n this.setSelected(featureId);\n doubleClickZoom.disable(this);\n\n this.setActionableState({\n trash: true\n });\n\n return state;\n};\n\nDirectSelect.onStop = function() {\n doubleClickZoom.enable(this);\n this.clearSelectedCoordinates();\n};\n\nDirectSelect.toDisplayFeatures = function(state, geojson, push) {\n if (state.featureId === geojson.properties.id) {\n geojson.properties.active = Constants.activeStates.ACTIVE;\n push(geojson);\n createSupplementaryPoints(geojson, {\n map: this.map,\n midpoints: true,\n selectedPaths: state.selectedCoordPaths\n }).forEach(push);\n } else {\n geojson.properties.active = Constants.activeStates.INACTIVE;\n push(geojson);\n }\n this.fireActionable(state);\n};\n\nDirectSelect.onTrash = function(state) {\n // Uses number-aware sorting to make sure '9' < '10'. Comparison is reversed because we want them\n // in reverse order so that we can remove by index safely.\n state.selectedCoordPaths\n .sort((a, b) => b.localeCompare(a, 'en', { numeric: true }))\n .forEach(id => state.feature.removeCoordinate(id));\n this.fireUpdate();\n state.selectedCoordPaths = [];\n this.clearSelectedCoordinates();\n this.fireActionable(state);\n if (state.feature.isValid() === false) {\n this.deleteFeature([state.featureId]);\n this.changeMode(Constants.modes.SIMPLE_SELECT, {});\n }\n};\n\nDirectSelect.onMouseMove = function(state, e) {\n // On mousemove that is not a drag, stop vertex movement.\n const isFeature = isActiveFeature(e);\n const onVertex = isVertex(e);\n const isMidPoint = isMidpoint(e);\n const noCoords = state.selectedCoordPaths.length === 0;\n if (isFeature && noCoords) this.updateUIClasses({ mouse: Constants.cursors.MOVE });\n else if (onVertex && !noCoords) this.updateUIClasses({ mouse: Constants.cursors.MOVE });\n else this.updateUIClasses({ mouse: Constants.cursors.NONE });\n\n const isDraggableItem = onVertex || isFeature || isMidPoint;\n if (isDraggableItem && state.dragMoving) this.fireUpdate();\n\n this.stopDragging(state);\n\n // Skip render\n return true;\n};\n\nDirectSelect.onMouseOut = function(state) {\n // As soon as you mouse leaves the canvas, update the feature\n if (state.dragMoving) this.fireUpdate();\n\n // Skip render\n return true;\n};\n\nDirectSelect.onTouchStart = DirectSelect.onMouseDown = function(state, e) {\n if (isVertex(e)) return this.onVertex(state, e);\n if (isActiveFeature(e)) return this.onFeature(state, e);\n if (isMidpoint(e)) return this.onMidpoint(state, e);\n};\n\nDirectSelect.onDrag = function(state, e) {\n if (state.canDragMove !== true) return;\n state.dragMoving = true;\n e.originalEvent.stopPropagation();\n\n const delta = {\n lng: e.lngLat.lng - state.dragMoveLocation.lng,\n lat: e.lngLat.lat - state.dragMoveLocation.lat\n };\n if (state.selectedCoordPaths.length > 0) this.dragVertex(state, e, delta);\n else this.dragFeature(state, e, delta);\n\n state.dragMoveLocation = e.lngLat;\n};\n\nDirectSelect.onClick = function(state, e) {\n if (noTarget(e)) return this.clickNoTarget(state, e);\n if (isActiveFeature(e)) return this.clickActiveFeature(state, e);\n if (isInactiveFeature(e)) return this.clickInactive(state, e);\n this.stopDragging(state);\n};\n\nDirectSelect.onTap = function(state, e) {\n if (noTarget(e)) return this.clickNoTarget(state, e);\n if (isActiveFeature(e)) return this.clickActiveFeature(state, e);\n if (isInactiveFeature(e)) return this.clickInactive(state, e);\n};\n\nDirectSelect.onTouchEnd = DirectSelect.onMouseUp = function(state) {\n if (state.dragMoving) {\n this.fireUpdate();\n }\n this.stopDragging(state);\n};\n\nexport default DirectSelect;\n\n","import * as CommonSelectors from '../lib/common_selectors';\nimport * as Constants from '../constants';\n\nconst DrawPoint = {};\n\nDrawPoint.onSetup = function() {\n const point = this.newFeature({\n type: Constants.geojsonTypes.FEATURE,\n properties: {},\n geometry: {\n type: Constants.geojsonTypes.POINT,\n coordinates: []\n }\n });\n\n this.addFeature(point);\n\n this.clearSelectedFeatures();\n this.updateUIClasses({ mouse: Constants.cursors.ADD });\n this.activateUIButton(Constants.types.POINT);\n\n this.setActionableState({\n trash: true\n });\n\n return { point };\n};\n\nDrawPoint.stopDrawingAndRemove = function(state) {\n this.deleteFeature([state.point.id], { silent: true });\n this.changeMode(Constants.modes.SIMPLE_SELECT);\n};\n\nDrawPoint.onTap = DrawPoint.onClick = function(state, e) {\n this.updateUIClasses({ mouse: Constants.cursors.MOVE });\n state.point.updateCoordinate('', e.lngLat.lng, e.lngLat.lat);\n this.map.fire(Constants.events.CREATE, {\n features: [state.point.toGeoJSON()]\n });\n this.changeMode(Constants.modes.SIMPLE_SELECT, { featureIds: [state.point.id] });\n};\n\nDrawPoint.onStop = function(state) {\n this.activateUIButton();\n if (!state.point.getCoordinate().length) {\n this.deleteFeature([state.point.id], { silent: true });\n }\n};\n\nDrawPoint.toDisplayFeatures = function(state, geojson, display) {\n // Never render the point we're drawing\n const isActivePoint = geojson.properties.id === state.point.id;\n geojson.properties.active = (isActivePoint) ? Constants.activeStates.ACTIVE : Constants.activeStates.INACTIVE;\n if (!isActivePoint) return display(geojson);\n};\n\nDrawPoint.onTrash = DrawPoint.stopDrawingAndRemove;\n\nDrawPoint.onKeyUp = function(state, e) {\n if (CommonSelectors.isEscapeKey(e) || CommonSelectors.isEnterKey(e)) {\n return this.stopDrawingAndRemove(state, e);\n }\n};\n\nexport default DrawPoint;\n","function isEventAtCoordinates(event, coordinates) {\n if (!event.lngLat) return false;\n return event.lngLat.lng === coordinates[0] && event.lngLat.lat === coordinates[1];\n}\n\nexport default isEventAtCoordinates;\n","import * as CommonSelectors from '../lib/common_selectors';\nimport doubleClickZoom from '../lib/double_click_zoom';\nimport * as Constants from '../constants';\nimport isEventAtCoordinates from '../lib/is_event_at_coordinates';\nimport createVertex from '../lib/create_vertex';\n\nconst DrawPolygon = {};\n\nDrawPolygon.onSetup = function() {\n const polygon = this.newFeature({\n type: Constants.geojsonTypes.FEATURE,\n properties: {},\n geometry: {\n type: Constants.geojsonTypes.POLYGON,\n coordinates: [[]]\n }\n });\n\n this.addFeature(polygon);\n\n this.clearSelectedFeatures();\n doubleClickZoom.disable(this);\n this.updateUIClasses({ mouse: Constants.cursors.ADD });\n this.activateUIButton(Constants.types.POLYGON);\n this.setActionableState({\n trash: true\n });\n\n return {\n polygon,\n currentVertexPosition: 0\n };\n};\n\nDrawPolygon.clickAnywhere = function(state, e) {\n if (state.currentVertexPosition > 0 && isEventAtCoordinates(e, state.polygon.coordinates[0][state.currentVertexPosition - 1])) {\n return this.changeMode(Constants.modes.SIMPLE_SELECT, { featureIds: [state.polygon.id] });\n }\n this.updateUIClasses({ mouse: Constants.cursors.ADD });\n state.polygon.updateCoordinate(`0.${state.currentVertexPosition}`, e.lngLat.lng, e.lngLat.lat);\n state.currentVertexPosition++;\n state.polygon.updateCoordinate(`0.${state.currentVertexPosition}`, e.lngLat.lng, e.lngLat.lat);\n};\n\nDrawPolygon.clickOnVertex = function(state) {\n return this.changeMode(Constants.modes.SIMPLE_SELECT, { featureIds: [state.polygon.id] });\n};\n\nDrawPolygon.onMouseMove = function(state, e) {\n state.polygon.updateCoordinate(`0.${state.currentVertexPosition}`, e.lngLat.lng, e.lngLat.lat);\n if (CommonSelectors.isVertex(e)) {\n this.updateUIClasses({ mouse: Constants.cursors.POINTER });\n }\n};\n\nDrawPolygon.onTap = DrawPolygon.onClick = function(state, e) {\n if (CommonSelectors.isVertex(e)) return this.clickOnVertex(state, e);\n return this.clickAnywhere(state, e);\n};\n\nDrawPolygon.onKeyUp = function(state, e) {\n if (CommonSelectors.isEscapeKey(e)) {\n this.deleteFeature([state.polygon.id], { silent: true });\n this.changeMode(Constants.modes.SIMPLE_SELECT);\n } else if (CommonSelectors.isEnterKey(e)) {\n this.changeMode(Constants.modes.SIMPLE_SELECT, { featureIds: [state.polygon.id] });\n }\n};\n\nDrawPolygon.onStop = function(state) {\n this.updateUIClasses({ mouse: Constants.cursors.NONE });\n doubleClickZoom.enable(this);\n this.activateUIButton();\n\n // check to see if we've deleted this feature\n if (this.getFeature(state.polygon.id) === undefined) return;\n\n //remove last added coordinate\n state.polygon.removeCoordinate(`0.${state.currentVertexPosition}`);\n if (state.polygon.isValid()) {\n this.map.fire(Constants.events.CREATE, {\n features: [state.polygon.toGeoJSON()]\n });\n } else {\n this.deleteFeature([state.polygon.id], { silent: true });\n this.changeMode(Constants.modes.SIMPLE_SELECT, {}, { silent: true });\n }\n};\n\nDrawPolygon.toDisplayFeatures = function(state, geojson, display) {\n const isActivePolygon = geojson.properties.id === state.polygon.id;\n geojson.properties.active = (isActivePolygon) ? Constants.activeStates.ACTIVE : Constants.activeStates.INACTIVE;\n if (!isActivePolygon) return display(geojson);\n\n // Don't render a polygon until it has two positions\n // (and a 3rd which is just the first repeated)\n if (geojson.geometry.coordinates.length === 0) return;\n\n const coordinateCount = geojson.geometry.coordinates[0].length;\n // 2 coordinates after selecting a draw type\n // 3 after creating the first point\n if (coordinateCount < 3) {\n return;\n }\n geojson.properties.meta = Constants.meta.FEATURE;\n display(createVertex(state.polygon.id, geojson.geometry.coordinates[0][0], '0.0', false));\n if (coordinateCount > 3) {\n // Add a start position marker to the map, clicking on this will finish the feature\n // This should only be shown when we're in a valid spot\n const endPos = geojson.geometry.coordinates[0].length - 3;\n display(createVertex(state.polygon.id, geojson.geometry.coordinates[0][endPos], `0.${endPos}`, false));\n }\n if (coordinateCount <= 4) {\n // If we've only drawn two positions (plus the closer),\n // make a LineString instead of a Polygon\n const lineCoordinates = [\n [geojson.geometry.coordinates[0][0][0], geojson.geometry.coordinates[0][0][1]], [geojson.geometry.coordinates[0][1][0], geojson.geometry.coordinates[0][1][1]]\n ];\n // create an initial vertex so that we can track the first point on mobile devices\n display({\n type: Constants.geojsonTypes.FEATURE,\n properties: geojson.properties,\n geometry: {\n coordinates: lineCoordinates,\n type: Constants.geojsonTypes.LINE_STRING\n }\n });\n if (coordinateCount === 3) {\n return;\n }\n }\n // render the Polygon\n return display(geojson);\n};\n\nDrawPolygon.onTrash = function(state) {\n this.deleteFeature([state.polygon.id], { silent: true });\n this.changeMode(Constants.modes.SIMPLE_SELECT);\n};\n\nexport default DrawPolygon;\n","import * as CommonSelectors from '../lib/common_selectors';\nimport isEventAtCoordinates from '../lib/is_event_at_coordinates';\nimport doubleClickZoom from '../lib/double_click_zoom';\nimport * as Constants from '../constants';\nimport createVertex from '../lib/create_vertex';\n\nconst DrawLineString = {};\n\nDrawLineString.onSetup = function(opts) {\n opts = opts || {};\n const featureId = opts.featureId;\n\n let line, currentVertexPosition;\n let direction = 'forward';\n if (featureId) {\n line = this.getFeature(featureId);\n if (!line) {\n throw new Error('Could not find a feature with the provided featureId');\n }\n let from = opts.from;\n if (from && from.type === 'Feature' && from.geometry && from.geometry.type === 'Point') {\n from = from.geometry;\n }\n if (from && from.type === 'Point' && from.coordinates && from.coordinates.length === 2) {\n from = from.coordinates;\n }\n if (!from || !Array.isArray(from)) {\n throw new Error('Please use the `from` property to indicate which point to continue the line from');\n }\n const lastCoord = line.coordinates.length - 1;\n if (line.coordinates[lastCoord][0] === from[0] && line.coordinates[lastCoord][1] === from[1]) {\n currentVertexPosition = lastCoord + 1;\n // add one new coordinate to continue from\n line.addCoordinate(currentVertexPosition, ...line.coordinates[lastCoord]);\n } else if (line.coordinates[0][0] === from[0] && line.coordinates[0][1] === from[1]) {\n direction = 'backwards';\n currentVertexPosition = 0;\n // add one new coordinate to continue from\n line.addCoordinate(currentVertexPosition, ...line.coordinates[0]);\n } else {\n throw new Error('`from` should match the point at either the start or the end of the provided LineString');\n }\n } else {\n line = this.newFeature({\n type: Constants.geojsonTypes.FEATURE,\n properties: {},\n geometry: {\n type: Constants.geojsonTypes.LINE_STRING,\n coordinates: []\n }\n });\n currentVertexPosition = 0;\n this.addFeature(line);\n }\n\n this.clearSelectedFeatures();\n doubleClickZoom.disable(this);\n this.updateUIClasses({ mouse: Constants.cursors.ADD });\n this.activateUIButton(Constants.types.LINE);\n this.setActionableState({\n trash: true\n });\n\n return {\n line,\n currentVertexPosition,\n direction\n };\n};\n\nDrawLineString.clickAnywhere = function(state, e) {\n if (state.currentVertexPosition > 0 && isEventAtCoordinates(e, state.line.coordinates[state.currentVertexPosition - 1]) ||\n state.direction === 'backwards' && isEventAtCoordinates(e, state.line.coordinates[state.currentVertexPosition + 1])) {\n return this.changeMode(Constants.modes.SIMPLE_SELECT, { featureIds: [state.line.id] });\n }\n this.updateUIClasses({ mouse: Constants.cursors.ADD });\n state.line.updateCoordinate(state.currentVertexPosition, e.lngLat.lng, e.lngLat.lat);\n if (state.direction === 'forward') {\n state.currentVertexPosition++;\n state.line.updateCoordinate(state.currentVertexPosition, e.lngLat.lng, e.lngLat.lat);\n } else {\n state.line.addCoordinate(0, e.lngLat.lng, e.lngLat.lat);\n }\n};\n\nDrawLineString.clickOnVertex = function(state) {\n return this.changeMode(Constants.modes.SIMPLE_SELECT, { featureIds: [state.line.id] });\n};\n\nDrawLineString.onMouseMove = function(state, e) {\n state.line.updateCoordinate(state.currentVertexPosition, e.lngLat.lng, e.lngLat.lat);\n if (CommonSelectors.isVertex(e)) {\n this.updateUIClasses({ mouse: Constants.cursors.POINTER });\n }\n};\n\nDrawLineString.onTap = DrawLineString.onClick = function(state, e) {\n if (CommonSelectors.isVertex(e)) return this.clickOnVertex(state, e);\n this.clickAnywhere(state, e);\n};\n\nDrawLineString.onKeyUp = function(state, e) {\n if (CommonSelectors.isEnterKey(e)) {\n this.changeMode(Constants.modes.SIMPLE_SELECT, { featureIds: [state.line.id] });\n } else if (CommonSelectors.isEscapeKey(e)) {\n this.deleteFeature([state.line.id], { silent: true });\n this.changeMode(Constants.modes.SIMPLE_SELECT);\n }\n};\n\nDrawLineString.onStop = function(state) {\n doubleClickZoom.enable(this);\n this.activateUIButton();\n\n // check to see if we've deleted this feature\n if (this.getFeature(state.line.id) === undefined) return;\n\n //remove last added coordinate\n state.line.removeCoordinate(`${state.currentVertexPosition}`);\n if (state.line.isValid()) {\n this.map.fire(Constants.events.CREATE, {\n features: [state.line.toGeoJSON()]\n });\n } else {\n this.deleteFeature([state.line.id], { silent: true });\n this.changeMode(Constants.modes.SIMPLE_SELECT, {}, { silent: true });\n }\n};\n\nDrawLineString.onTrash = function(state) {\n this.deleteFeature([state.line.id], { silent: true });\n this.changeMode(Constants.modes.SIMPLE_SELECT);\n};\n\nDrawLineString.toDisplayFeatures = function(state, geojson, display) {\n const isActiveLine = geojson.properties.id === state.line.id;\n geojson.properties.active = (isActiveLine) ? Constants.activeStates.ACTIVE : Constants.activeStates.INACTIVE;\n if (!isActiveLine) return display(geojson);\n // Only render the line if it has at least one real coordinate\n if (geojson.geometry.coordinates.length < 2) return;\n geojson.properties.meta = Constants.meta.FEATURE;\n display(createVertex(\n state.line.id,\n geojson.geometry.coordinates[state.direction === 'forward' ? geojson.geometry.coordinates.length - 2 : 1],\n `${state.direction === 'forward' ? geojson.geometry.coordinates.length - 2 : 1}`,\n false\n ));\n\n display(geojson);\n};\n\nexport default DrawLineString;\n","/**\n * @module helpers\n */\n/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n *\n * @memberof helpers\n * @type {number}\n */\nexport var earthRadius = 6371008.8;\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var factors = {\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n degrees: earthRadius / 111325,\n feet: earthRadius * 3.28084,\n inches: earthRadius * 39.37,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n meters: earthRadius,\n metres: earthRadius,\n miles: earthRadius / 1609.344,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n nauticalmiles: earthRadius / 1852,\n radians: 1,\n yards: earthRadius * 1.0936,\n};\n/**\n * Units of measurement factors based on 1 meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var unitsFactors = {\n centimeters: 100,\n centimetres: 100,\n degrees: 1 / 111325,\n feet: 3.28084,\n inches: 39.37,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n meters: 1,\n metres: 1,\n miles: 1 / 1609.344,\n millimeters: 1000,\n millimetres: 1000,\n nauticalmiles: 1 / 1852,\n radians: 1 / earthRadius,\n yards: 1.0936133,\n};\n/**\n * Area of measurement factors based on 1 square meter.\n *\n * @memberof helpers\n * @type {Object}\n */\nexport var areaFactors = {\n acres: 0.000247105,\n centimeters: 10000,\n centimetres: 10000,\n feet: 10.763910417,\n hectares: 0.0001,\n inches: 1550.003100006,\n kilometers: 0.000001,\n kilometres: 0.000001,\n meters: 1,\n metres: 1,\n miles: 3.86e-7,\n millimeters: 1000000,\n millimetres: 1000000,\n yards: 1.195990046,\n};\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nexport function feature(geom, properties, options) {\n if (options === void 0) { options = {}; }\n var feat = { type: \"Feature\" };\n if (options.id === 0 || options.id) {\n feat.id = options.id;\n }\n if (options.bbox) {\n feat.bbox = options.bbox;\n }\n feat.properties = properties || {};\n feat.geometry = geom;\n return feat;\n}\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array<any>} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = \"Point\";\n * var coordinates = [110, 50];\n * var geometry = turf.geometry(type, coordinates);\n * // => geometry\n */\nexport function geometry(type, coordinates, _options) {\n if (_options === void 0) { _options = {}; }\n switch (type) {\n case \"Point\":\n return point(coordinates).geometry;\n case \"LineString\":\n return lineString(coordinates).geometry;\n case \"Polygon\":\n return polygon(coordinates).geometry;\n case \"MultiPoint\":\n return multiPoint(coordinates).geometry;\n case \"MultiLineString\":\n return multiLineString(coordinates).geometry;\n case \"MultiPolygon\":\n return multiPolygon(coordinates).geometry;\n default:\n throw new Error(type + \" is invalid\");\n }\n}\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nexport function point(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (!coordinates) {\n throw new Error(\"coordinates is required\");\n }\n if (!Array.isArray(coordinates)) {\n throw new Error(\"coordinates must be an Array\");\n }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be at least 2 numbers long\");\n }\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) {\n throw new Error(\"coordinates must contain numbers\");\n }\n var geom = {\n type: \"Point\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array<Array<number>>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Point>} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nexport function points(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon>} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nexport function polygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n for (var _i = 0, coordinates_1 = coordinates; _i < coordinates_1.length; _i++) {\n var ring = coordinates_1[_i];\n if (ring.length < 4) {\n throw new Error(\"Each LinearRing of a Polygon must have 4 or more Positions.\");\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error(\"First and last Position are not equivalent.\");\n }\n }\n }\n var geom = {\n type: \"Polygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nexport function polygons(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString>} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nexport function lineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be an array of two or more positions\");\n }\n var geom = {\n type: \"LineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString>} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nexport function lineStrings(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nexport function featureCollection(features, options) {\n if (options === void 0) { options = {}; }\n var fc = { type: \"FeatureCollection\" };\n if (options.id) {\n fc.id = options.id;\n }\n if (options.bbox) {\n fc.bbox = options.bbox;\n }\n fc.features = features;\n return fc;\n}\n/**\n * Creates a {@link Feature<MultiLineString>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString>} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nexport function multiLineString(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiLineString\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature<MultiPoint>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint>} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nexport function multiPoint(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPoint\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature<MultiPolygon>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon>} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nexport function multiPolygon(coordinates, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"MultiPolygon\",\n coordinates: coordinates,\n };\n return feature(geom, properties, options);\n}\n/**\n * Creates a {@link Feature<GeometryCollection>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array<Geometry>} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = turf.geometry(\"Point\", [100, 0]);\n * var line = turf.geometry(\"LineString\", [[101, 0], [102, 1]]);\n * var collection = turf.geometryCollection([pt, line]);\n *\n * // => collection\n */\nexport function geometryCollection(geometries, properties, options) {\n if (options === void 0) { options = {}; }\n var geom = {\n type: \"GeometryCollection\",\n geometries: geometries,\n };\n return feature(geom, properties, options);\n}\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nexport function round(num, precision) {\n if (precision === void 0) { precision = 0; }\n if (precision && !(precision >= 0)) {\n throw new Error(\"precision must be a positive number\");\n }\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} distance\n */\nexport function radiansToLength(radians, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return radians * factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} radians\n */\nexport function lengthToRadians(distance, units) {\n if (units === void 0) { units = \"kilometers\"; }\n var factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\n return distance / factor;\n}\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nexport function lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nexport function bearingToAzimuth(bearing) {\n var angle = bearing % 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n}\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nexport function radiansToDegrees(radians) {\n var degrees = radians % (2 * Math.PI);\n return (degrees * 180) / Math.PI;\n}\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nexport function degreesToRadians(degrees) {\n var radians = degrees % 360;\n return (radians * Math.PI) / 180;\n}\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {Units} [originalUnit=\"kilometers\"] of the length\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted length\n */\nexport function convertLength(length, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"kilometers\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(length >= 0)) {\n throw new Error(\"length must be a positive number\");\n }\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit);\n}\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches, hectares\n * @param {number} area to be converted\n * @param {Units} [originalUnit=\"meters\"] of the distance\n * @param {Units} [finalUnit=\"kilometers\"] returned unit\n * @returns {number} the converted area\n */\nexport function convertArea(area, originalUnit, finalUnit) {\n if (originalUnit === void 0) { originalUnit = \"meters\"; }\n if (finalUnit === void 0) { finalUnit = \"kilometers\"; }\n if (!(area >= 0)) {\n throw new Error(\"area must be a positive number\");\n }\n var startFactor = areaFactors[originalUnit];\n if (!startFactor) {\n throw new Error(\"invalid original units\");\n }\n var finalFactor = areaFactors[finalUnit];\n if (!finalFactor) {\n throw new Error(\"invalid final units\");\n }\n return (area / startFactor) * finalFactor;\n}\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nexport function isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nexport function isObject(input) {\n return !!input && input.constructor === Object;\n}\n/**\n * Validate BBox\n *\n * @private\n * @param {Array<number>} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nexport function validateBBox(bbox) {\n if (!bbox) {\n throw new Error(\"bbox is required\");\n }\n if (!Array.isArray(bbox)) {\n throw new Error(\"bbox must be an Array\");\n }\n if (bbox.length !== 4 && bbox.length !== 6) {\n throw new Error(\"bbox must be an Array of 4 or 6 numbers\");\n }\n bbox.forEach(function (num) {\n if (!isNumber(num)) {\n throw new Error(\"bbox must only contain numbers\");\n }\n });\n}\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nexport function validateId(id) {\n if (!id) {\n throw new Error(\"id is required\");\n }\n if ([\"string\", \"number\"].indexOf(typeof id) === -1) {\n throw new Error(\"id must be a number or a string\");\n }\n}\n","/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n */\nvar earthRadius = 6371008.8;\n\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n */\nvar factors = {\n meters: earthRadius,\n metres: earthRadius,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n miles: earthRadius / 1609.344,\n nauticalmiles: earthRadius / 1852,\n inches: earthRadius * 39.370,\n yards: earthRadius / 1.0936,\n feet: earthRadius * 3.28084,\n radians: 1,\n degrees: earthRadius / 111325,\n};\n\n/**\n * Units of measurement factors based on 1 meter.\n */\nvar unitsFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000,\n millimetres: 1000,\n centimeters: 100,\n centimetres: 100,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n miles: 1 / 1609.344,\n nauticalmiles: 1 / 1852,\n inches: 39.370,\n yards: 1 / 1.0936,\n feet: 3.28084,\n radians: 1 / earthRadius,\n degrees: 1 / 111325,\n};\n\n/**\n * Area of measurement factors based on 1 square meter.\n */\nvar areaFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000000,\n millimetres: 1000000,\n centimeters: 10000,\n centimetres: 10000,\n kilometers: 0.000001,\n kilometres: 0.000001,\n acres: 0.000247105,\n miles: 3.86e-7,\n yards: 1.195990046,\n feet: 10.763910417,\n inches: 1550.003100006\n};\n\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nfunction feature(geometry, properties, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (geometry === undefined) throw new Error('geometry is required');\n if (properties && properties.constructor !== Object) throw new Error('properties must be an Object');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var feat = {type: 'Feature'};\n if (id) feat.id = id;\n if (bbox) feat.bbox = bbox;\n feat.properties = properties || {};\n feat.geometry = geometry;\n return feat;\n}\n\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array<number>} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = 'Point';\n * var coordinates = [110, 50];\n *\n * var geometry = turf.geometry(type, coordinates);\n *\n * //=geometry\n */\nfunction geometry(type, coordinates, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n\n // Validation\n if (!type) throw new Error('type is required');\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (bbox) validateBBox(bbox);\n\n // Main\n var geom;\n switch (type) {\n case 'Point': geom = point(coordinates).geometry; break;\n case 'LineString': geom = lineString(coordinates).geometry; break;\n case 'Polygon': geom = polygon(coordinates).geometry; break;\n case 'MultiPoint': geom = multiPoint(coordinates).geometry; break;\n case 'MultiLineString': geom = multiLineString(coordinates).geometry; break;\n case 'MultiPolygon': geom = multiPolygon(coordinates).geometry; break;\n default: throw new Error(type + ' is invalid');\n }\n if (bbox) geom.bbox = bbox;\n return geom;\n}\n\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nfunction point(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long');\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'Point',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array<Array<number>>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Point>} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nfunction points(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon>} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nfunction polygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n for (var i = 0; i < coordinates.length; i++) {\n var ring = coordinates[i];\n if (ring.length < 4) {\n throw new Error('Each LinearRing of a Polygon must have 4 or more Positions.');\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (i === 0 && j === 0 && !isNumber(ring[0][0]) || !isNumber(ring[0][1])) throw new Error('coordinates must contain numbers');\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error('First and last Position are not equivalent.');\n }\n }\n }\n\n return feature({\n type: 'Polygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nfunction polygons(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString>} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nfunction lineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions');\n // Check if first point of LineString contains two numbers\n if (!isNumber(coordinates[0][1]) || !isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'LineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array<Array<number>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString>} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nfunction lineStrings(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nfunction featureCollection(features, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (!features) throw new Error('No features passed');\n if (!Array.isArray(features)) throw new Error('features must be an Array');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var fc = {type: 'FeatureCollection'};\n if (id) fc.id = id;\n if (bbox) fc.bbox = bbox;\n fc.features = features;\n return fc;\n}\n\n/**\n * Creates a {@link Feature<MultiLineString>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString>} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nfunction multiLineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiLineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPoint>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint>} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nfunction multiPoint(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPoint',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPolygon>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon>} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nfunction multiPolygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPolygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<GeometryCollection>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array<Geometry>} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = {\n * \"type\": \"Point\",\n * \"coordinates\": [100, 0]\n * };\n * var line = {\n * \"type\": \"LineString\",\n * \"coordinates\": [ [101, 0], [102, 1] ]\n * };\n * var collection = turf.geometryCollection([pt, line]);\n *\n * //=collection\n */\nfunction geometryCollection(geometries, properties, options) {\n if (!geometries) throw new Error('geometries is required');\n if (!Array.isArray(geometries)) throw new Error('geometries must be an Array');\n\n return feature({\n type: 'GeometryCollection',\n geometries: geometries\n }, properties, options);\n}\n\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nfunction round(num, precision) {\n if (num === undefined || num === null || isNaN(num)) throw new Error('num is required');\n if (precision && !(precision >= 0)) throw new Error('precision must be a positive number');\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} distance\n */\nfunction radiansToLength(radians, units) {\n if (radians === undefined || radians === null) throw new Error('radians is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return radians * factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} radians\n */\nfunction lengthToRadians(distance, units) {\n if (distance === undefined || distance === null) throw new Error('distance is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return distance / factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nfunction lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nfunction bearingToAzimuth(bearing) {\n if (bearing === null || bearing === undefined) throw new Error('bearing is required');\n\n var angle = bearing % 360;\n if (angle < 0) angle += 360;\n return angle;\n}\n\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nfunction radiansToDegrees(radians) {\n if (radians === null || radians === undefined) throw new Error('radians is required');\n\n var degrees = radians % (2 * Math.PI);\n return degrees * 180 / Math.PI;\n}\n\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nfunction degreesToRadians(degrees) {\n if (degrees === null || degrees === undefined) throw new Error('degrees is required');\n\n var radians = degrees % 360;\n return radians * Math.PI / 180;\n}\n\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {string} originalUnit of the length\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted length\n */\nfunction convertLength(length, originalUnit, finalUnit) {\n if (length === null || length === undefined) throw new Error('length is required');\n if (!(length >= 0)) throw new Error('length must be a positive number');\n\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit || 'kilometers');\n}\n\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches\n * @param {number} area to be converted\n * @param {string} [originalUnit='meters'] of the distance\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted distance\n */\nfunction convertArea(area, originalUnit, finalUnit) {\n if (area === null || area === undefined) throw new Error('area is required');\n if (!(area >= 0)) throw new Error('area must be a positive number');\n\n var startFactor = areaFactors[originalUnit || 'meters'];\n if (!startFactor) throw new Error('invalid original units');\n\n var finalFactor = areaFactors[finalUnit || 'kilometers'];\n if (!finalFactor) throw new Error('invalid final units');\n\n return (area / startFactor) * finalFactor;\n}\n\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nfunction isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nfunction isObject(input) {\n return (!!input) && (input.constructor === Object);\n}\n\n/**\n * Validate BBox\n *\n * @private\n * @param {Array<number>} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nfunction validateBBox(bbox) {\n if (!bbox) throw new Error('bbox is required');\n if (!Array.isArray(bbox)) throw new Error('bbox must be an Array');\n if (bbox.length !== 4 && bbox.length !== 6) throw new Error('bbox must be an Array of 4 or 6 numbers');\n bbox.forEach(function (num) {\n if (!isNumber(num)) throw new Error('bbox must only contain numbers');\n });\n}\n\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nfunction validateId(id) {\n if (!id) throw new Error('id is required');\n if (['string', 'number'].indexOf(typeof id) === -1) throw new Error('id must be a number or a string');\n}\n\n// Deprecated methods\nfunction radians2degrees() {\n throw new Error('method has been renamed to `radiansToDegrees`');\n}\n\nfunction degrees2radians() {\n throw new Error('method has been renamed to `degreesToRadians`');\n}\n\nfunction distanceToDegrees() {\n throw new Error('method has been renamed to `lengthToDegrees`');\n}\n\nfunction distanceToRadians() {\n throw new Error('method has been renamed to `lengthToRadians`');\n}\n\nfunction radiansToDistance() {\n throw new Error('method has been renamed to `radiansToLength`');\n}\n\nfunction bearingToAngle() {\n throw new Error('method has been renamed to `bearingToAzimuth`');\n}\n\nfunction convertDistance() {\n throw new Error('method has been renamed to `convertLength`');\n}\n\nexport { earthRadius, factors, unitsFactors, areaFactors, feature, geometry, point, points, polygon, polygons, lineString, lineStrings, featureCollection, multiLineString, multiPoint, multiPolygon, geometryCollection, round, radiansToLength, lengthToRadians, lengthToDegrees, bearingToAzimuth, radiansToDegrees, degreesToRadians, convertLength, convertArea, isNumber, isObject, validateBBox, validateId, radians2degrees, degrees2radians, distanceToDegrees, distanceToRadians, radiansToDistance, bearingToAngle, convertDistance };\n","import { isNumber } from '@turf/helpers';\n\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers\n * @returns {Array<number>} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nfunction getCoord(coord) {\n if (!coord) throw new Error('coord is required');\n if (coord.type === 'Feature' && coord.geometry !== null && coord.geometry.type === 'Point') return coord.geometry.coordinates;\n if (coord.type === 'Point') return coord.coordinates;\n if (Array.isArray(coord) && coord.length >= 2 && coord[0].length === undefined && coord[1].length === undefined) return coord;\n\n throw new Error('coord must be GeoJSON Point or an Array of numbers');\n}\n\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array<any>|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array<any>} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nfunction getCoords(coords) {\n if (!coords) throw new Error('coords is required');\n\n // Feature\n if (coords.type === 'Feature' && coords.geometry !== null) return coords.geometry.coordinates;\n\n // Geometry\n if (coords.coordinates) return coords.coordinates;\n\n // Array of numbers\n if (Array.isArray(coords)) return coords;\n\n throw new Error('coords must be GeoJSON Feature, Geometry Object or an Array');\n}\n\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array<any>} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nfunction containsNumber(coordinates) {\n if (coordinates.length > 1 && isNumber(coordinates[0]) && isNumber(coordinates[1])) {\n return true;\n }\n\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error('coordinates must only contain numbers');\n}\n\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction geojsonType(value, type, name) {\n if (!type || !name) throw new Error('type and name required');\n\n if (!value || value.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + value.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nfunction featureOf(feature, type, name) {\n if (!feature) throw new Error('No feature passed');\n if (!name) throw new Error('.featureOf() requires a name');\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction collectionOf(featureCollection, type, name) {\n if (!featureCollection) throw new Error('No featureCollection passed');\n if (!name) throw new Error('.collectionOf() requires a name');\n if (!featureCollection || featureCollection.type !== 'FeatureCollection') {\n throw new Error('Invalid input to ' + name + ', FeatureCollection required');\n }\n for (var i = 0; i < featureCollection.features.length; i++) {\n var feature = featureCollection.features[i];\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n }\n}\n\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nfunction getGeom(geojson) {\n if (!geojson) throw new Error('geojson is required');\n if (geojson.geometry !== undefined) return geojson.geometry;\n if (geojson.coordinates || geojson.geometries) return geojson;\n throw new Error('geojson must be a valid Feature or Geometry Object');\n}\n\n/**\n * Get Geometry Type from Feature or Geometry Object\n *\n * @throws {Error} **DEPRECATED** in v5.0.0 in favor of getType\n */\nfunction getGeomType() {\n throw new Error('invariant.getGeomType has been deprecated in v5.0 in favor of invariant.getType');\n}\n\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nfunction getType(geojson, name) {\n if (!geojson) throw new Error((name || 'geojson') + ' is required');\n // GeoJSON Feature & GeometryCollection\n if (geojson.geometry && geojson.geometry.type) return geojson.geometry.type;\n // GeoJSON Geometry & FeatureCollection\n if (geojson.type) return geojson.type;\n throw new Error((name || 'geojson') + ' is invalid');\n}\n\nexport { getCoord, getCoords, containsNumber, geojsonType, featureOf, collectionOf, getGeom, getGeomType, getType };\n","import { getCoord } from '@turf/invariant';\nimport { degreesToRadians, isObject, radiansToDegrees } from '@turf/helpers';\n\n//http://en.wikipedia.org/wiki/Haversine_formula\n//http://www.movable-type.co.uk/scripts/latlong.html\n\n/**\n * Takes two {@link Point|points} and finds the geographic bearing between them,\n * i.e. the angle measured in degrees from the north line (0 degrees)\n *\n * @name bearing\n * @param {Coord} start starting Point\n * @param {Coord} end ending Point\n * @param {Object} [options={}] Optional parameters\n * @param {boolean} [options.final=false] calculates the final bearing if true\n * @returns {number} bearing in decimal degrees, between -180 and 180 degrees (positive clockwise)\n * @example\n * var point1 = turf.point([-75.343, 39.984]);\n * var point2 = turf.point([-75.534, 39.123]);\n *\n * var bearing = turf.bearing(point1, point2);\n *\n * //addToMap\n * var addToMap = [point1, point2]\n * point1.properties['marker-color'] = '#f00'\n * point2.properties['marker-color'] = '#0f0'\n * point1.properties.bearing = bearing\n */\nfunction bearing(start, end, options) {\n // Optional parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var final = options.final;\n\n // Reverse calculation\n if (final === true) return calculateFinalBearing(start, end);\n\n var coordinates1 = getCoord(start);\n var coordinates2 = getCoord(end);\n\n var lon1 = degreesToRadians(coordinates1[0]);\n var lon2 = degreesToRadians(coordinates2[0]);\n var lat1 = degreesToRadians(coordinates1[1]);\n var lat2 = degreesToRadians(coordinates2[1]);\n var a = Math.sin(lon2 - lon1) * Math.cos(lat2);\n var b = Math.cos(lat1) * Math.sin(lat2) -\n Math.sin(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1);\n\n return radiansToDegrees(Math.atan2(a, b));\n}\n\n/**\n * Calculates Final Bearing\n *\n * @private\n * @param {Coord} start starting Point\n * @param {Coord} end ending Point\n * @returns {number} bearing\n */\nfunction calculateFinalBearing(start, end) {\n // Swap start & end\n var bear = bearing(end, start);\n bear = (bear + 180) % 360;\n return bear;\n}\n\nexport default bearing;\n","import { feature, isObject, lineString, point } from '@turf/helpers';\n\n/**\n * Callback for coordEach\n *\n * @callback coordEachCallback\n * @param {Array<number>} currentCoord The current coordinate being processed.\n * @param {number} coordIndex The current index of the coordinate being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n */\n\n/**\n * Iterate over coordinates in any GeoJSON object, similar to Array.forEach()\n *\n * @name coordEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, multiFeatureIndex)\n * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=currentCoord\n * //=coordIndex\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * });\n */\nfunction coordEach(geojson, callback, excludeWrapCoord) {\n // Handles null Geometry -- Skips this GeoJSON\n if (geojson === null) return;\n var j, k, l, geometry, stopG, coords,\n geometryMaybeCollection,\n wrapShrink = 0,\n coordIndex = 0,\n isGeometryCollection,\n type = geojson.type,\n isFeatureCollection = type === 'FeatureCollection',\n isFeature = type === 'Feature',\n stop = isFeatureCollection ? geojson.features.length : 1;\n\n // This logic may look a little weird. The reason why it is that way\n // is because it's trying to be fast. GeoJSON supports multiple kinds\n // of objects at its root: FeatureCollection, Features, Geometries.\n // This function has the responsibility of handling all of them, and that\n // means that some of the `for` loops you see below actually just don't apply\n // to certain inputs. For instance, if you give this just a\n // Point geometry, then both loops are short-circuited and all we do\n // is gradually rename the input until it's called 'geometry'.\n //\n // This also aims to allocate as few resources as possible: just a\n // few numbers and booleans, rather than any temporary arrays as would\n // be required with the normalization approach.\n for (var featureIndex = 0; featureIndex < stop; featureIndex++) {\n geometryMaybeCollection = (isFeatureCollection ? geojson.features[featureIndex].geometry :\n (isFeature ? geojson.geometry : geojson));\n isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;\n stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;\n\n for (var geomIndex = 0; geomIndex < stopG; geomIndex++) {\n var multiFeatureIndex = 0;\n var geometryIndex = 0;\n geometry = isGeometryCollection ?\n geometryMaybeCollection.geometries[geomIndex] : geometryMaybeCollection;\n\n // Handles null Geometry -- Skips this geometry\n if (geometry === null) continue;\n coords = geometry.coordinates;\n var geomType = geometry.type;\n\n wrapShrink = (excludeWrapCoord && (geomType === 'Polygon' || geomType === 'MultiPolygon')) ? 1 : 0;\n\n switch (geomType) {\n case null:\n break;\n case 'Point':\n if (callback(coords, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n multiFeatureIndex++;\n break;\n case 'LineString':\n case 'MultiPoint':\n for (j = 0; j < coords.length; j++) {\n if (callback(coords[j], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n if (geomType === 'MultiPoint') multiFeatureIndex++;\n }\n if (geomType === 'LineString') multiFeatureIndex++;\n break;\n case 'Polygon':\n case 'MultiLineString':\n for (j = 0; j < coords.length; j++) {\n for (k = 0; k < coords[j].length - wrapShrink; k++) {\n if (callback(coords[j][k], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n }\n if (geomType === 'MultiLineString') multiFeatureIndex++;\n if (geomType === 'Polygon') geometryIndex++;\n }\n if (geomType === 'Polygon') multiFeatureIndex++;\n break;\n case 'MultiPolygon':\n for (j = 0; j < coords.length; j++) {\n if (geomType === 'MultiPolygon') geometryIndex = 0;\n for (k = 0; k < coords[j].length; k++) {\n for (l = 0; l < coords[j][k].length - wrapShrink; l++) {\n if (callback(coords[j][k][l], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n }\n geometryIndex++;\n }\n multiFeatureIndex++;\n }\n break;\n case 'GeometryCollection':\n for (j = 0; j < geometry.geometries.length; j++)\n if (coordEach(geometry.geometries[j], callback, excludeWrapCoord) === false) return false;\n break;\n default:\n throw new Error('Unknown Geometry Type');\n }\n }\n }\n}\n\n/**\n * Callback for coordReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback coordReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Array<number>} currentCoord The current coordinate being processed.\n * @param {number} coordIndex The current index of the coordinate being processed.\n * Starts at index 0, if an initialValue is provided, and at index 1 otherwise.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n */\n\n/**\n * Reduce coordinates in any GeoJSON object, similar to Array.reduce()\n *\n * @name coordReduce\n * @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=previousValue\n * //=currentCoord\n * //=coordIndex\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * return currentCoord;\n * });\n */\nfunction coordReduce(geojson, callback, initialValue, excludeWrapCoord) {\n var previousValue = initialValue;\n coordEach(geojson, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n if (coordIndex === 0 && initialValue === undefined) previousValue = currentCoord;\n else previousValue = callback(previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex);\n }, excludeWrapCoord);\n return previousValue;\n}\n\n/**\n * Callback for propEach\n *\n * @callback propEachCallback\n * @param {Object} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Iterate over properties in any GeoJSON object, similar to Array.forEach()\n *\n * @name propEach\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentProperties, featureIndex)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.propEach(features, function (currentProperties, featureIndex) {\n * //=currentProperties\n * //=featureIndex\n * });\n */\nfunction propEach(geojson, callback) {\n var i;\n switch (geojson.type) {\n case 'FeatureCollection':\n for (i = 0; i < geojson.features.length; i++) {\n if (callback(geojson.features[i].properties, i) === false) break;\n }\n break;\n case 'Feature':\n callback(geojson.properties, 0);\n break;\n }\n}\n\n\n/**\n * Callback for propReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback propReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {*} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Reduce properties in any GeoJSON object into a single value,\n * similar to how Array.reduce works. However, in this case we lazily run\n * the reduction, so an array of all properties is unnecessary.\n *\n * @name propReduce\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.propReduce(features, function (previousValue, currentProperties, featureIndex) {\n * //=previousValue\n * //=currentProperties\n * //=featureIndex\n * return currentProperties\n * });\n */\nfunction propReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n propEach(geojson, function (currentProperties, featureIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties;\n else previousValue = callback(previousValue, currentProperties, featureIndex);\n });\n return previousValue;\n}\n\n/**\n * Callback for featureEach\n *\n * @callback featureEachCallback\n * @param {Feature<any>} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Iterate over features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @name featureEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentFeature, featureIndex)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.featureEach(features, function (currentFeature, featureIndex) {\n * //=currentFeature\n * //=featureIndex\n * });\n */\nfunction featureEach(geojson, callback) {\n if (geojson.type === 'Feature') {\n callback(geojson, 0);\n } else if (geojson.type === 'FeatureCollection') {\n for (var i = 0; i < geojson.features.length; i++) {\n if (callback(geojson.features[i], i) === false) break;\n }\n }\n}\n\n/**\n * Callback for featureReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback featureReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @name featureReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.featureReduce(features, function (previousValue, currentFeature, featureIndex) {\n * //=previousValue\n * //=currentFeature\n * //=featureIndex\n * return currentFeature\n * });\n */\nfunction featureReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n featureEach(geojson, function (currentFeature, featureIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature;\n else previousValue = callback(previousValue, currentFeature, featureIndex);\n });\n return previousValue;\n}\n\n/**\n * Get all coordinates from any GeoJSON object.\n *\n * @name coordAll\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @returns {Array<Array<number>>} coordinate position array\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * var coords = turf.coordAll(features);\n * //= [[26, 37], [36, 53]]\n */\nfunction coordAll(geojson) {\n var coords = [];\n coordEach(geojson, function (coord) {\n coords.push(coord);\n });\n return coords;\n}\n\n/**\n * Callback for geomEach\n *\n * @callback geomEachCallback\n * @param {Geometry} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {Object} featureProperties The current Feature Properties being processed.\n * @param {Array<number>} featureBBox The current Feature BBox being processed.\n * @param {number|string} featureId The current Feature Id being processed.\n */\n\n/**\n * Iterate over each geometry in any GeoJSON object, similar to Array.forEach()\n *\n * @name geomEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n * //=currentGeometry\n * //=featureIndex\n * //=featureProperties\n * //=featureBBox\n * //=featureId\n * });\n */\nfunction geomEach(geojson, callback) {\n var i, j, g, geometry, stopG,\n geometryMaybeCollection,\n isGeometryCollection,\n featureProperties,\n featureBBox,\n featureId,\n featureIndex = 0,\n isFeatureCollection = geojson.type === 'FeatureCollection',\n isFeature = geojson.type === 'Feature',\n stop = isFeatureCollection ? geojson.features.length : 1;\n\n // This logic may look a little weird. The reason why it is that way\n // is because it's trying to be fast. GeoJSON supports multiple kinds\n // of objects at its root: FeatureCollection, Features, Geometries.\n // This function has the responsibility of handling all of them, and that\n // means that some of the `for` loops you see below actually just don't apply\n // to certain inputs. For instance, if you give this just a\n // Point geometry, then both loops are short-circuited and all we do\n // is gradually rename the input until it's called 'geometry'.\n //\n // This also aims to allocate as few resources as possible: just a\n // few numbers and booleans, rather than any temporary arrays as would\n // be required with the normalization approach.\n for (i = 0; i < stop; i++) {\n\n geometryMaybeCollection = (isFeatureCollection ? geojson.features[i].geometry :\n (isFeature ? geojson.geometry : geojson));\n featureProperties = (isFeatureCollection ? geojson.features[i].properties :\n (isFeature ? geojson.properties : {}));\n featureBBox = (isFeatureCollection ? geojson.features[i].bbox :\n (isFeature ? geojson.bbox : undefined));\n featureId = (isFeatureCollection ? geojson.features[i].id :\n (isFeature ? geojson.id : undefined));\n isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;\n stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;\n\n for (g = 0; g < stopG; g++) {\n geometry = isGeometryCollection ?\n geometryMaybeCollection.geometries[g] : geometryMaybeCollection;\n\n // Handle null Geometry\n if (geometry === null) {\n if (callback(null, featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n continue;\n }\n switch (geometry.type) {\n case 'Point':\n case 'LineString':\n case 'MultiPoint':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon': {\n if (callback(geometry, featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n break;\n }\n case 'GeometryCollection': {\n for (j = 0; j < geometry.geometries.length; j++) {\n if (callback(geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n }\n break;\n }\n default:\n throw new Error('Unknown Geometry Type');\n }\n }\n // Only increase `featureIndex` per each feature\n featureIndex++;\n }\n}\n\n/**\n * Callback for geomReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback geomReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Geometry} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {Object} featureProperties The current Feature Properties being processed.\n * @param {Array<number>} featureBBox The current Feature BBox being processed.\n * @param {number|string} featureId The current Feature Id being processed.\n */\n\n/**\n * Reduce geometry in any GeoJSON object, similar to Array.reduce().\n *\n * @name geomReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n * //=previousValue\n * //=currentGeometry\n * //=featureIndex\n * //=featureProperties\n * //=featureBBox\n * //=featureId\n * return currentGeometry\n * });\n */\nfunction geomReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n geomEach(geojson, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry;\n else previousValue = callback(previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId);\n });\n return previousValue;\n}\n\n/**\n * Callback for flattenEach\n *\n * @callback flattenEachCallback\n * @param {Feature} currentFeature The current flattened feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n */\n\n/**\n * Iterate over flattened features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @name flattenEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex)\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})\n * ]);\n *\n * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) {\n * //=currentFeature\n * //=featureIndex\n * //=multiFeatureIndex\n * });\n */\nfunction flattenEach(geojson, callback) {\n geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) {\n // Callback for single geometry\n var type = (geometry === null) ? null : geometry.type;\n switch (type) {\n case null:\n case 'Point':\n case 'LineString':\n case 'Polygon':\n if (callback(feature(geometry, properties, {bbox: bbox, id: id}), featureIndex, 0) === false) return false;\n return;\n }\n\n var geomType;\n\n // Callback for multi-geometry\n switch (type) {\n case 'MultiPoint':\n geomType = 'Point';\n break;\n case 'MultiLineString':\n geomType = 'LineString';\n break;\n case 'MultiPolygon':\n geomType = 'Polygon';\n break;\n }\n\n for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) {\n var coordinate = geometry.coordinates[multiFeatureIndex];\n var geom = {\n type: geomType,\n coordinates: coordinate\n };\n if (callback(feature(geom, properties), featureIndex, multiFeatureIndex) === false) return false;\n }\n });\n}\n\n/**\n * Callback for flattenReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback flattenReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n */\n\n/**\n * Reduce flattened features in any GeoJSON object, similar to Array.reduce().\n *\n * @name flattenReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})\n * ]);\n *\n * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) {\n * //=previousValue\n * //=currentFeature\n * //=featureIndex\n * //=multiFeatureIndex\n * return currentFeature\n * });\n */\nfunction flattenReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n flattenEach(geojson, function (currentFeature, featureIndex, multiFeatureIndex) {\n if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined) previousValue = currentFeature;\n else previousValue = callback(previousValue, currentFeature, featureIndex, multiFeatureIndex);\n });\n return previousValue;\n}\n\n/**\n * Callback for segmentEach\n *\n * @callback segmentEachCallback\n * @param {Feature<LineString>} currentSegment The current Segment being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n * @param {number} segmentIndex The current index of the Segment being processed.\n * @returns {void}\n */\n\n/**\n * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach()\n * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON\n * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex)\n * @returns {void}\n * @example\n * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);\n *\n * // Iterate over GeoJSON by 2-vertex segments\n * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n * //=currentSegment\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * //=segmentIndex\n * });\n *\n * // Calculate the total number of segments\n * var total = 0;\n * turf.segmentEach(polygon, function () {\n * total++;\n * });\n */\nfunction segmentEach(geojson, callback) {\n flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) {\n var segmentIndex = 0;\n\n // Exclude null Geometries\n if (!feature$$1.geometry) return;\n // (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n var type = feature$$1.geometry.type;\n if (type === 'Point' || type === 'MultiPoint') return;\n\n // Generate 2-vertex line segments\n var previousCoords;\n if (coordEach(feature$$1, function (currentCoord, coordIndex, featureIndexCoord, mutliPartIndexCoord, geometryIndex) {\n // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false`\n if (previousCoords === undefined) {\n previousCoords = currentCoord;\n return;\n }\n var currentSegment = lineString([previousCoords, currentCoord], feature$$1.properties);\n if (callback(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) === false) return false;\n segmentIndex++;\n previousCoords = currentCoord;\n }) === false) return false;\n });\n}\n\n/**\n * Callback for segmentReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback segmentReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature<LineString>} currentSegment The current Segment being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n * @param {number} segmentIndex The current index of the Segment being processed.\n */\n\n/**\n * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce()\n * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON\n * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {void}\n * @example\n * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);\n *\n * // Iterate over GeoJSON by 2-vertex segments\n * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n * //= previousSegment\n * //= currentSegment\n * //= featureIndex\n * //= multiFeatureIndex\n * //= geometryIndex\n * //= segmentInex\n * return currentSegment\n * });\n *\n * // Calculate the total number of segments\n * var initialValue = 0\n * var total = turf.segmentReduce(polygon, function (previousValue) {\n * previousValue++;\n * return previousValue;\n * }, initialValue);\n */\nfunction segmentReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n var started = false;\n segmentEach(geojson, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n if (started === false && initialValue === undefined) previousValue = currentSegment;\n else previousValue = callback(previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex);\n started = true;\n });\n return previousValue;\n}\n\n/**\n * Callback for lineEach\n *\n * @callback lineEachCallback\n * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed\n * @param {number} featureIndex The current index of the Feature being processed\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed\n * @param {number} geometryIndex The current index of the Geometry being processed\n */\n\n/**\n * Iterate over line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries,\n * similar to Array.forEach.\n *\n * @name lineEach\n * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object\n * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @example\n * var multiLine = turf.multiLineString([\n * [[26, 37], [35, 45]],\n * [[36, 53], [38, 50], [41, 55]]\n * ]);\n *\n * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=currentLine\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * });\n */\nfunction lineEach(geojson, callback) {\n // validation\n if (!geojson) throw new Error('geojson is required');\n\n flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) {\n if (feature$$1.geometry === null) return;\n var type = feature$$1.geometry.type;\n var coords = feature$$1.geometry.coordinates;\n switch (type) {\n case 'LineString':\n if (callback(feature$$1, featureIndex, multiFeatureIndex, 0, 0) === false) return false;\n break;\n case 'Polygon':\n for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) {\n if (callback(lineString(coords[geometryIndex], feature$$1.properties), featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n }\n break;\n }\n });\n}\n\n/**\n * Callback for lineReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback lineReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed.\n * @param {number} featureIndex The current index of the Feature being processed\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed\n * @param {number} geometryIndex The current index of the Geometry being processed\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @name lineReduce\n * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object\n * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var multiPoly = turf.multiPolygon([\n * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]),\n * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]])\n * ]);\n *\n * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=previousValue\n * //=currentLine\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * return currentLine\n * });\n */\nfunction lineReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n lineEach(geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine;\n else previousValue = callback(previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex);\n });\n return previousValue;\n}\n\n/**\n * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes.\n *\n * Negative indexes are permitted.\n * Point & MultiPoint will always return null.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry\n * @param {Object} [options={}] Optional parameters\n * @param {number} [options.featureIndex=0] Feature Index\n * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index\n * @param {number} [options.geometryIndex=0] Geometry Index\n * @param {number} [options.segmentIndex=0] Segment Index\n * @param {Object} [options.properties={}] Translate Properties to output LineString\n * @param {BBox} [options.bbox={}] Translate BBox to output LineString\n * @param {number|string} [options.id={}] Translate Id to output LineString\n * @returns {Feature<LineString>} 2-vertex GeoJSON Feature LineString\n * @example\n * var multiLine = turf.multiLineString([\n * [[10, 10], [50, 30], [30, 40]],\n * [[-10, -10], [-50, -30], [-30, -40]]\n * ]);\n *\n * // First Segment (defaults are 0)\n * turf.findSegment(multiLine);\n * // => Feature<LineString<[[10, 10], [50, 30]]>>\n *\n * // First Segment of 2nd Multi Feature\n * turf.findSegment(multiLine, {multiFeatureIndex: 1});\n * // => Feature<LineString<[[-10, -10], [-50, -30]]>>\n *\n * // Last Segment of Last Multi Feature\n * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1});\n * // => Feature<LineString<[[-50, -30], [-30, -40]]>>\n */\nfunction findSegment(geojson, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var featureIndex = options.featureIndex || 0;\n var multiFeatureIndex = options.multiFeatureIndex || 0;\n var geometryIndex = options.geometryIndex || 0;\n var segmentIndex = options.segmentIndex || 0;\n\n // Find FeatureIndex\n var properties = options.properties;\n var geometry;\n\n switch (geojson.type) {\n case 'FeatureCollection':\n if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;\n properties = properties || geojson.features[featureIndex].properties;\n geometry = geojson.features[featureIndex].geometry;\n break;\n case 'Feature':\n properties = properties || geojson.properties;\n geometry = geojson.geometry;\n break;\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon':\n geometry = geojson;\n break;\n default:\n throw new Error('geojson is invalid');\n }\n\n // Find SegmentIndex\n if (geometry === null) return null;\n var coords = geometry.coordinates;\n switch (geometry.type) {\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1;\n return lineString([coords[segmentIndex], coords[segmentIndex + 1]], properties, options);\n case 'Polygon':\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1;\n return lineString([coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1]], properties, options);\n case 'MultiLineString':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1;\n return lineString([coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1]], properties, options);\n case 'MultiPolygon':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1;\n return lineString([coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]], properties, options);\n }\n throw new Error('geojson is invalid');\n}\n\n/**\n * Finds a particular Point from a GeoJSON using `@turf/meta` indexes.\n *\n * Negative indexes are permitted.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry\n * @param {Object} [options={}] Optional parameters\n * @param {number} [options.featureIndex=0] Feature Index\n * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index\n * @param {number} [options.geometryIndex=0] Geometry Index\n * @param {number} [options.coordIndex=0] Coord Index\n * @param {Object} [options.properties={}] Translate Properties to output Point\n * @param {BBox} [options.bbox={}] Translate BBox to output Point\n * @param {number|string} [options.id={}] Translate Id to output Point\n * @returns {Feature<Point>} 2-vertex GeoJSON Feature Point\n * @example\n * var multiLine = turf.multiLineString([\n * [[10, 10], [50, 30], [30, 40]],\n * [[-10, -10], [-50, -30], [-30, -40]]\n * ]);\n *\n * // First Segment (defaults are 0)\n * turf.findPoint(multiLine);\n * // => Feature<Point<[10, 10]>>\n *\n * // First Segment of the 2nd Multi-Feature\n * turf.findPoint(multiLine, {multiFeatureIndex: 1});\n * // => Feature<Point<[-10, -10]>>\n *\n * // Last Segment of last Multi-Feature\n * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1});\n * // => Feature<Point<[-30, -40]>>\n */\nfunction findPoint(geojson, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var featureIndex = options.featureIndex || 0;\n var multiFeatureIndex = options.multiFeatureIndex || 0;\n var geometryIndex = options.geometryIndex || 0;\n var coordIndex = options.coordIndex || 0;\n\n // Find FeatureIndex\n var properties = options.properties;\n var geometry;\n\n switch (geojson.type) {\n case 'FeatureCollection':\n if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;\n properties = properties || geojson.features[featureIndex].properties;\n geometry = geojson.features[featureIndex].geometry;\n break;\n case 'Feature':\n properties = properties || geojson.properties;\n geometry = geojson.geometry;\n break;\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon':\n geometry = geojson;\n break;\n default:\n throw new Error('geojson is invalid');\n }\n\n // Find Coord Index\n if (geometry === null) return null;\n var coords = geometry.coordinates;\n switch (geometry.type) {\n case 'Point':\n return point(coords, properties, options);\n case 'MultiPoint':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n return point(coords[multiFeatureIndex], properties, options);\n case 'LineString':\n if (coordIndex < 0) coordIndex = coords.length + coordIndex;\n return point(coords[coordIndex], properties, options);\n case 'Polygon':\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex;\n return point(coords[geometryIndex][coordIndex], properties, options);\n case 'MultiLineString':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex;\n return point(coords[multiFeatureIndex][coordIndex], properties, options);\n case 'MultiPolygon':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex;\n return point(coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options);\n }\n throw new Error('geojson is invalid');\n}\n\nexport { coordEach, coordReduce, propEach, propReduce, featureEach, featureReduce, coordAll, geomEach, geomReduce, flattenEach, flattenReduce, segmentEach, segmentReduce, lineEach, lineReduce, findSegment, findPoint };\n","import { coordEach } from '@turf/meta';\n\n/**\n * Takes a set of features, calculates the bbox of all input features, and returns a bounding box.\n *\n * @name bbox\n * @param {GeoJSON} geojson any GeoJSON object\n * @returns {BBox} bbox extent in [minX, minY, maxX, maxY] order\n * @example\n * var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]]);\n * var bbox = turf.bbox(line);\n * var bboxPolygon = turf.bboxPolygon(bbox);\n *\n * //addToMap\n * var addToMap = [line, bboxPolygon]\n */\nfunction bbox(geojson) {\n var BBox = [Infinity, Infinity, -Infinity, -Infinity];\n coordEach(geojson, function (coord) {\n if (BBox[0] > coord[0]) BBox[0] = coord[0];\n if (BBox[1] > coord[1]) BBox[1] = coord[1];\n if (BBox[2] < coord[0]) BBox[2] = coord[0];\n if (BBox[3] < coord[1]) BBox[3] = coord[1];\n });\n return BBox;\n}\n\nexport default bbox;\n","/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n */\nvar earthRadius = 6371008.8;\n\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n */\nvar factors = {\n meters: earthRadius,\n metres: earthRadius,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n miles: earthRadius / 1609.344,\n nauticalmiles: earthRadius / 1852,\n inches: earthRadius * 39.370,\n yards: earthRadius / 1.0936,\n feet: earthRadius * 3.28084,\n radians: 1,\n degrees: earthRadius / 111325,\n};\n\n/**\n * Units of measurement factors based on 1 meter.\n */\nvar unitsFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000,\n millimetres: 1000,\n centimeters: 100,\n centimetres: 100,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n miles: 1 / 1609.344,\n nauticalmiles: 1 / 1852,\n inches: 39.370,\n yards: 1 / 1.0936,\n feet: 3.28084,\n radians: 1 / earthRadius,\n degrees: 1 / 111325,\n};\n\n/**\n * Area of measurement factors based on 1 square meter.\n */\nvar areaFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000000,\n millimetres: 1000000,\n centimeters: 10000,\n centimetres: 10000,\n kilometers: 0.000001,\n kilometres: 0.000001,\n acres: 0.000247105,\n miles: 3.86e-7,\n yards: 1.195990046,\n feet: 10.763910417,\n inches: 1550.003100006\n};\n\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nfunction feature(geometry, properties, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (geometry === undefined) throw new Error('geometry is required');\n if (properties && properties.constructor !== Object) throw new Error('properties must be an Object');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var feat = {type: 'Feature'};\n if (id) feat.id = id;\n if (bbox) feat.bbox = bbox;\n feat.properties = properties || {};\n feat.geometry = geometry;\n return feat;\n}\n\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array<number>} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = 'Point';\n * var coordinates = [110, 50];\n *\n * var geometry = turf.geometry(type, coordinates);\n *\n * //=geometry\n */\nfunction geometry(type, coordinates, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n\n // Validation\n if (!type) throw new Error('type is required');\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (bbox) validateBBox(bbox);\n\n // Main\n var geom;\n switch (type) {\n case 'Point': geom = point(coordinates).geometry; break;\n case 'LineString': geom = lineString(coordinates).geometry; break;\n case 'Polygon': geom = polygon(coordinates).geometry; break;\n case 'MultiPoint': geom = multiPoint(coordinates).geometry; break;\n case 'MultiLineString': geom = multiLineString(coordinates).geometry; break;\n case 'MultiPolygon': geom = multiPolygon(coordinates).geometry; break;\n default: throw new Error(type + ' is invalid');\n }\n if (bbox) geom.bbox = bbox;\n return geom;\n}\n\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nfunction point(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long');\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'Point',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array<Array<number>>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Point>} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nfunction points(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon>} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nfunction polygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n for (var i = 0; i < coordinates.length; i++) {\n var ring = coordinates[i];\n if (ring.length < 4) {\n throw new Error('Each LinearRing of a Polygon must have 4 or more Positions.');\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (i === 0 && j === 0 && !isNumber(ring[0][0]) || !isNumber(ring[0][1])) throw new Error('coordinates must contain numbers');\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error('First and last Position are not equivalent.');\n }\n }\n }\n\n return feature({\n type: 'Polygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nfunction polygons(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString>} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nfunction lineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions');\n // Check if first point of LineString contains two numbers\n if (!isNumber(coordinates[0][1]) || !isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'LineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array<Array<number>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString>} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nfunction lineStrings(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nfunction featureCollection(features, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (!features) throw new Error('No features passed');\n if (!Array.isArray(features)) throw new Error('features must be an Array');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var fc = {type: 'FeatureCollection'};\n if (id) fc.id = id;\n if (bbox) fc.bbox = bbox;\n fc.features = features;\n return fc;\n}\n\n/**\n * Creates a {@link Feature<MultiLineString>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString>} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nfunction multiLineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiLineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPoint>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint>} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nfunction multiPoint(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPoint',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPolygon>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon>} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nfunction multiPolygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPolygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<GeometryCollection>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array<Geometry>} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = {\n * \"type\": \"Point\",\n * \"coordinates\": [100, 0]\n * };\n * var line = {\n * \"type\": \"LineString\",\n * \"coordinates\": [ [101, 0], [102, 1] ]\n * };\n * var collection = turf.geometryCollection([pt, line]);\n *\n * //=collection\n */\nfunction geometryCollection(geometries, properties, options) {\n if (!geometries) throw new Error('geometries is required');\n if (!Array.isArray(geometries)) throw new Error('geometries must be an Array');\n\n return feature({\n type: 'GeometryCollection',\n geometries: geometries\n }, properties, options);\n}\n\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nfunction round(num, precision) {\n if (num === undefined || num === null || isNaN(num)) throw new Error('num is required');\n if (precision && !(precision >= 0)) throw new Error('precision must be a positive number');\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} distance\n */\nfunction radiansToLength(radians, units) {\n if (radians === undefined || radians === null) throw new Error('radians is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return radians * factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} radians\n */\nfunction lengthToRadians(distance, units) {\n if (distance === undefined || distance === null) throw new Error('distance is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return distance / factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nfunction lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nfunction bearingToAzimuth(bearing) {\n if (bearing === null || bearing === undefined) throw new Error('bearing is required');\n\n var angle = bearing % 360;\n if (angle < 0) angle += 360;\n return angle;\n}\n\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nfunction radiansToDegrees(radians) {\n if (radians === null || radians === undefined) throw new Error('radians is required');\n\n var degrees = radians % (2 * Math.PI);\n return degrees * 180 / Math.PI;\n}\n\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nfunction degreesToRadians(degrees) {\n if (degrees === null || degrees === undefined) throw new Error('degrees is required');\n\n var radians = degrees % 360;\n return radians * Math.PI / 180;\n}\n\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {string} originalUnit of the length\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted length\n */\nfunction convertLength(length, originalUnit, finalUnit) {\n if (length === null || length === undefined) throw new Error('length is required');\n if (!(length >= 0)) throw new Error('length must be a positive number');\n\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit || 'kilometers');\n}\n\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches\n * @param {number} area to be converted\n * @param {string} [originalUnit='meters'] of the distance\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted distance\n */\nfunction convertArea(area, originalUnit, finalUnit) {\n if (area === null || area === undefined) throw new Error('area is required');\n if (!(area >= 0)) throw new Error('area must be a positive number');\n\n var startFactor = areaFactors[originalUnit || 'meters'];\n if (!startFactor) throw new Error('invalid original units');\n\n var finalFactor = areaFactors[finalUnit || 'kilometers'];\n if (!finalFactor) throw new Error('invalid final units');\n\n return (area / startFactor) * finalFactor;\n}\n\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nfunction isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nfunction isObject(input) {\n return (!!input) && (input.constructor === Object);\n}\n\n/**\n * Validate BBox\n *\n * @private\n * @param {Array<number>} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nfunction validateBBox(bbox) {\n if (!bbox) throw new Error('bbox is required');\n if (!Array.isArray(bbox)) throw new Error('bbox must be an Array');\n if (bbox.length !== 4 && bbox.length !== 6) throw new Error('bbox must be an Array of 4 or 6 numbers');\n bbox.forEach(function (num) {\n if (!isNumber(num)) throw new Error('bbox must only contain numbers');\n });\n}\n\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nfunction validateId(id) {\n if (!id) throw new Error('id is required');\n if (['string', 'number'].indexOf(typeof id) === -1) throw new Error('id must be a number or a string');\n}\n\n// Deprecated methods\nfunction radians2degrees() {\n throw new Error('method has been renamed to `radiansToDegrees`');\n}\n\nfunction degrees2radians() {\n throw new Error('method has been renamed to `degreesToRadians`');\n}\n\nfunction distanceToDegrees() {\n throw new Error('method has been renamed to `lengthToDegrees`');\n}\n\nfunction distanceToRadians() {\n throw new Error('method has been renamed to `lengthToRadians`');\n}\n\nfunction radiansToDistance() {\n throw new Error('method has been renamed to `radiansToLength`');\n}\n\nfunction bearingToAngle() {\n throw new Error('method has been renamed to `bearingToAzimuth`');\n}\n\nfunction convertDistance() {\n throw new Error('method has been renamed to `convertLength`');\n}\n\nexport { earthRadius, factors, unitsFactors, areaFactors, feature, geometry, point, points, polygon, polygons, lineString, lineStrings, featureCollection, multiLineString, multiPoint, multiPolygon, geometryCollection, round, radiansToLength, lengthToRadians, lengthToDegrees, bearingToAzimuth, radiansToDegrees, degreesToRadians, convertLength, convertArea, isNumber, isObject, validateBBox, validateId, radians2degrees, degrees2radians, distanceToDegrees, distanceToRadians, radiansToDistance, bearingToAngle, convertDistance };\n","import bbox from '@turf/bbox';\nimport { isObject, point } from '@turf/helpers';\n\n/**\n * Takes a {@link Feature} or {@link FeatureCollection} and returns the absolute center point of all features.\n *\n * @name center\n * @param {GeoJSON} geojson GeoJSON to be centered\n * @param {Object} [options={}] Optional parameters\n * @param {Object} [options.properties={}] an Object that is used as the {@link Feature}'s properties\n * @returns {Feature<Point>} a Point feature at the absolute center point of all input features\n * @example\n * var features = turf.featureCollection([\n * turf.point( [-97.522259, 35.4691]),\n * turf.point( [-97.502754, 35.463455]),\n * turf.point( [-97.508269, 35.463245])\n * ]);\n *\n * var center = turf.center(features);\n *\n * //addToMap\n * var addToMap = [features, center]\n * center.properties['marker-size'] = 'large';\n * center.properties['marker-color'] = '#000';\n */\nfunction center(geojson, options) {\n // Optional parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var properties = options.properties;\n\n // Input validation\n if (!geojson) throw new Error('geojson is required');\n\n var ext = bbox(geojson);\n var x = (ext[0] + ext[2]) / 2;\n var y = (ext[1] + ext[3]) / 2;\n return point([x, y], properties);\n}\n\nexport default center;\n","/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n */\nvar earthRadius = 6371008.8;\n\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n */\nvar factors = {\n meters: earthRadius,\n metres: earthRadius,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n miles: earthRadius / 1609.344,\n nauticalmiles: earthRadius / 1852,\n inches: earthRadius * 39.370,\n yards: earthRadius / 1.0936,\n feet: earthRadius * 3.28084,\n radians: 1,\n degrees: earthRadius / 111325,\n};\n\n/**\n * Units of measurement factors based on 1 meter.\n */\nvar unitsFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000,\n millimetres: 1000,\n centimeters: 100,\n centimetres: 100,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n miles: 1 / 1609.344,\n nauticalmiles: 1 / 1852,\n inches: 39.370,\n yards: 1 / 1.0936,\n feet: 3.28084,\n radians: 1 / earthRadius,\n degrees: 1 / 111325,\n};\n\n/**\n * Area of measurement factors based on 1 square meter.\n */\nvar areaFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000000,\n millimetres: 1000000,\n centimeters: 10000,\n centimetres: 10000,\n kilometers: 0.000001,\n kilometres: 0.000001,\n acres: 0.000247105,\n miles: 3.86e-7,\n yards: 1.195990046,\n feet: 10.763910417,\n inches: 1550.003100006\n};\n\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nfunction feature(geometry, properties, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (geometry === undefined) throw new Error('geometry is required');\n if (properties && properties.constructor !== Object) throw new Error('properties must be an Object');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var feat = {type: 'Feature'};\n if (id) feat.id = id;\n if (bbox) feat.bbox = bbox;\n feat.properties = properties || {};\n feat.geometry = geometry;\n return feat;\n}\n\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array<number>} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = 'Point';\n * var coordinates = [110, 50];\n *\n * var geometry = turf.geometry(type, coordinates);\n *\n * //=geometry\n */\nfunction geometry(type, coordinates, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n\n // Validation\n if (!type) throw new Error('type is required');\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (bbox) validateBBox(bbox);\n\n // Main\n var geom;\n switch (type) {\n case 'Point': geom = point(coordinates).geometry; break;\n case 'LineString': geom = lineString(coordinates).geometry; break;\n case 'Polygon': geom = polygon(coordinates).geometry; break;\n case 'MultiPoint': geom = multiPoint(coordinates).geometry; break;\n case 'MultiLineString': geom = multiLineString(coordinates).geometry; break;\n case 'MultiPolygon': geom = multiPolygon(coordinates).geometry; break;\n default: throw new Error(type + ' is invalid');\n }\n if (bbox) geom.bbox = bbox;\n return geom;\n}\n\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nfunction point(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long');\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'Point',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array<Array<number>>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Point>} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nfunction points(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon>} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nfunction polygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n for (var i = 0; i < coordinates.length; i++) {\n var ring = coordinates[i];\n if (ring.length < 4) {\n throw new Error('Each LinearRing of a Polygon must have 4 or more Positions.');\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (i === 0 && j === 0 && !isNumber(ring[0][0]) || !isNumber(ring[0][1])) throw new Error('coordinates must contain numbers');\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error('First and last Position are not equivalent.');\n }\n }\n }\n\n return feature({\n type: 'Polygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nfunction polygons(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString>} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nfunction lineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions');\n // Check if first point of LineString contains two numbers\n if (!isNumber(coordinates[0][1]) || !isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'LineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array<Array<number>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString>} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nfunction lineStrings(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nfunction featureCollection(features, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (!features) throw new Error('No features passed');\n if (!Array.isArray(features)) throw new Error('features must be an Array');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var fc = {type: 'FeatureCollection'};\n if (id) fc.id = id;\n if (bbox) fc.bbox = bbox;\n fc.features = features;\n return fc;\n}\n\n/**\n * Creates a {@link Feature<MultiLineString>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString>} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nfunction multiLineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiLineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPoint>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint>} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nfunction multiPoint(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPoint',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPolygon>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon>} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nfunction multiPolygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPolygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<GeometryCollection>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array<Geometry>} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = {\n * \"type\": \"Point\",\n * \"coordinates\": [100, 0]\n * };\n * var line = {\n * \"type\": \"LineString\",\n * \"coordinates\": [ [101, 0], [102, 1] ]\n * };\n * var collection = turf.geometryCollection([pt, line]);\n *\n * //=collection\n */\nfunction geometryCollection(geometries, properties, options) {\n if (!geometries) throw new Error('geometries is required');\n if (!Array.isArray(geometries)) throw new Error('geometries must be an Array');\n\n return feature({\n type: 'GeometryCollection',\n geometries: geometries\n }, properties, options);\n}\n\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nfunction round(num, precision) {\n if (num === undefined || num === null || isNaN(num)) throw new Error('num is required');\n if (precision && !(precision >= 0)) throw new Error('precision must be a positive number');\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} distance\n */\nfunction radiansToLength(radians, units) {\n if (radians === undefined || radians === null) throw new Error('radians is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return radians * factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} radians\n */\nfunction lengthToRadians(distance, units) {\n if (distance === undefined || distance === null) throw new Error('distance is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return distance / factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nfunction lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nfunction bearingToAzimuth(bearing) {\n if (bearing === null || bearing === undefined) throw new Error('bearing is required');\n\n var angle = bearing % 360;\n if (angle < 0) angle += 360;\n return angle;\n}\n\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nfunction radiansToDegrees(radians) {\n if (radians === null || radians === undefined) throw new Error('radians is required');\n\n var degrees = radians % (2 * Math.PI);\n return degrees * 180 / Math.PI;\n}\n\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nfunction degreesToRadians(degrees) {\n if (degrees === null || degrees === undefined) throw new Error('degrees is required');\n\n var radians = degrees % 360;\n return radians * Math.PI / 180;\n}\n\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {string} originalUnit of the length\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted length\n */\nfunction convertLength(length, originalUnit, finalUnit) {\n if (length === null || length === undefined) throw new Error('length is required');\n if (!(length >= 0)) throw new Error('length must be a positive number');\n\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit || 'kilometers');\n}\n\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches\n * @param {number} area to be converted\n * @param {string} [originalUnit='meters'] of the distance\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted distance\n */\nfunction convertArea(area, originalUnit, finalUnit) {\n if (area === null || area === undefined) throw new Error('area is required');\n if (!(area >= 0)) throw new Error('area must be a positive number');\n\n var startFactor = areaFactors[originalUnit || 'meters'];\n if (!startFactor) throw new Error('invalid original units');\n\n var finalFactor = areaFactors[finalUnit || 'kilometers'];\n if (!finalFactor) throw new Error('invalid final units');\n\n return (area / startFactor) * finalFactor;\n}\n\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nfunction isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nfunction isObject(input) {\n return (!!input) && (input.constructor === Object);\n}\n\n/**\n * Validate BBox\n *\n * @private\n * @param {Array<number>} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nfunction validateBBox(bbox) {\n if (!bbox) throw new Error('bbox is required');\n if (!Array.isArray(bbox)) throw new Error('bbox must be an Array');\n if (bbox.length !== 4 && bbox.length !== 6) throw new Error('bbox must be an Array of 4 or 6 numbers');\n bbox.forEach(function (num) {\n if (!isNumber(num)) throw new Error('bbox must only contain numbers');\n });\n}\n\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nfunction validateId(id) {\n if (!id) throw new Error('id is required');\n if (['string', 'number'].indexOf(typeof id) === -1) throw new Error('id must be a number or a string');\n}\n\n// Deprecated methods\nfunction radians2degrees() {\n throw new Error('method has been renamed to `radiansToDegrees`');\n}\n\nfunction degrees2radians() {\n throw new Error('method has been renamed to `degreesToRadians`');\n}\n\nfunction distanceToDegrees() {\n throw new Error('method has been renamed to `lengthToDegrees`');\n}\n\nfunction distanceToRadians() {\n throw new Error('method has been renamed to `lengthToRadians`');\n}\n\nfunction radiansToDistance() {\n throw new Error('method has been renamed to `radiansToLength`');\n}\n\nfunction bearingToAngle() {\n throw new Error('method has been renamed to `bearingToAzimuth`');\n}\n\nfunction convertDistance() {\n throw new Error('method has been renamed to `convertLength`');\n}\n\nexport { earthRadius, factors, unitsFactors, areaFactors, feature, geometry, point, points, polygon, polygons, lineString, lineStrings, featureCollection, multiLineString, multiPoint, multiPolygon, geometryCollection, round, radiansToLength, lengthToRadians, lengthToDegrees, bearingToAzimuth, radiansToDegrees, degreesToRadians, convertLength, convertArea, isNumber, isObject, validateBBox, validateId, radians2degrees, degrees2radians, distanceToDegrees, distanceToRadians, radiansToDistance, bearingToAngle, convertDistance };\n","import { isNumber } from '@turf/helpers';\n\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers\n * @returns {Array<number>} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nfunction getCoord(coord) {\n if (!coord) throw new Error('coord is required');\n if (coord.type === 'Feature' && coord.geometry !== null && coord.geometry.type === 'Point') return coord.geometry.coordinates;\n if (coord.type === 'Point') return coord.coordinates;\n if (Array.isArray(coord) && coord.length >= 2 && coord[0].length === undefined && coord[1].length === undefined) return coord;\n\n throw new Error('coord must be GeoJSON Point or an Array of numbers');\n}\n\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array<any>|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array<any>} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nfunction getCoords(coords) {\n if (!coords) throw new Error('coords is required');\n\n // Feature\n if (coords.type === 'Feature' && coords.geometry !== null) return coords.geometry.coordinates;\n\n // Geometry\n if (coords.coordinates) return coords.coordinates;\n\n // Array of numbers\n if (Array.isArray(coords)) return coords;\n\n throw new Error('coords must be GeoJSON Feature, Geometry Object or an Array');\n}\n\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array<any>} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nfunction containsNumber(coordinates) {\n if (coordinates.length > 1 && isNumber(coordinates[0]) && isNumber(coordinates[1])) {\n return true;\n }\n\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error('coordinates must only contain numbers');\n}\n\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction geojsonType(value, type, name) {\n if (!type || !name) throw new Error('type and name required');\n\n if (!value || value.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + value.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nfunction featureOf(feature, type, name) {\n if (!feature) throw new Error('No feature passed');\n if (!name) throw new Error('.featureOf() requires a name');\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction collectionOf(featureCollection, type, name) {\n if (!featureCollection) throw new Error('No featureCollection passed');\n if (!name) throw new Error('.collectionOf() requires a name');\n if (!featureCollection || featureCollection.type !== 'FeatureCollection') {\n throw new Error('Invalid input to ' + name + ', FeatureCollection required');\n }\n for (var i = 0; i < featureCollection.features.length; i++) {\n var feature = featureCollection.features[i];\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n }\n}\n\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nfunction getGeom(geojson) {\n if (!geojson) throw new Error('geojson is required');\n if (geojson.geometry !== undefined) return geojson.geometry;\n if (geojson.coordinates || geojson.geometries) return geojson;\n throw new Error('geojson must be a valid Feature or Geometry Object');\n}\n\n/**\n * Get Geometry Type from Feature or Geometry Object\n *\n * @throws {Error} **DEPRECATED** in v5.0.0 in favor of getType\n */\nfunction getGeomType() {\n throw new Error('invariant.getGeomType has been deprecated in v5.0 in favor of invariant.getType');\n}\n\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nfunction getType(geojson, name) {\n if (!geojson) throw new Error((name || 'geojson') + ' is required');\n // GeoJSON Feature & GeometryCollection\n if (geojson.geometry && geojson.geometry.type) return geojson.geometry.type;\n // GeoJSON Geometry & FeatureCollection\n if (geojson.type) return geojson.type;\n throw new Error((name || 'geojson') + ' is invalid');\n}\n\nexport { getCoord, getCoords, containsNumber, geojsonType, featureOf, collectionOf, getGeom, getGeomType, getType };\n","import { getCoord } from '@turf/invariant';\nimport { degreesToRadians, isObject, lengthToRadians, point, radiansToDegrees } from '@turf/helpers';\n\n//http://en.wikipedia.org/wiki/Haversine_formula\n//http://www.movable-type.co.uk/scripts/latlong.html\n/**\n * Takes a {@link Point} and calculates the location of a destination point given a distance in degrees, radians, miles, or kilometers; and bearing in degrees. This uses the [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula) to account for global curvature.\n *\n * @name destination\n * @param {Coord} origin starting point\n * @param {number} distance distance from the origin point\n * @param {number} bearing ranging from -180 to 180\n * @param {Object} [options={}] Optional parameters\n * @param {string} [options.units='kilometers'] miles, kilometers, degrees, or radians\n * @param {Object} [options.properties={}] Translate properties to Point\n * @returns {Feature<Point>} destination point\n * @example\n * var point = turf.point([-75.343, 39.984]);\n * var distance = 50;\n * var bearing = 90;\n * var options = {units: 'miles'};\n *\n * var destination = turf.destination(point, distance, bearing, options);\n *\n * //addToMap\n * var addToMap = [point, destination]\n * destination.properties['marker-color'] = '#f00';\n * point.properties['marker-color'] = '#0f0';\n */\nfunction destination(origin, distance, bearing, options) {\n // Optional parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var units = options.units;\n var properties = options.properties;\n\n // Handle input\n var coordinates1 = getCoord(origin);\n var longitude1 = degreesToRadians(coordinates1[0]);\n var latitude1 = degreesToRadians(coordinates1[1]);\n var bearing_rad = degreesToRadians(bearing);\n var radians = lengthToRadians(distance, units);\n\n // Main\n var latitude2 = Math.asin(Math.sin(latitude1) * Math.cos(radians) +\n Math.cos(latitude1) * Math.sin(radians) * Math.cos(bearing_rad));\n var longitude2 = longitude1 + Math.atan2(Math.sin(bearing_rad) * Math.sin(radians) * Math.cos(latitude1),\n Math.cos(radians) - Math.sin(latitude1) * Math.sin(latitude2));\n var lng = radiansToDegrees(longitude2);\n var lat = radiansToDegrees(latitude2);\n\n return point([lng, lat], properties);\n}\n\nexport default destination;\n","/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n */\nvar earthRadius = 6371008.8;\n\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n */\nvar factors = {\n meters: earthRadius,\n metres: earthRadius,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n miles: earthRadius / 1609.344,\n nauticalmiles: earthRadius / 1852,\n inches: earthRadius * 39.370,\n yards: earthRadius / 1.0936,\n feet: earthRadius * 3.28084,\n radians: 1,\n degrees: earthRadius / 111325,\n};\n\n/**\n * Units of measurement factors based on 1 meter.\n */\nvar unitsFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000,\n millimetres: 1000,\n centimeters: 100,\n centimetres: 100,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n miles: 1 / 1609.344,\n nauticalmiles: 1 / 1852,\n inches: 39.370,\n yards: 1 / 1.0936,\n feet: 3.28084,\n radians: 1 / earthRadius,\n degrees: 1 / 111325,\n};\n\n/**\n * Area of measurement factors based on 1 square meter.\n */\nvar areaFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000000,\n millimetres: 1000000,\n centimeters: 10000,\n centimetres: 10000,\n kilometers: 0.000001,\n kilometres: 0.000001,\n acres: 0.000247105,\n miles: 3.86e-7,\n yards: 1.195990046,\n feet: 10.763910417,\n inches: 1550.003100006\n};\n\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nfunction feature(geometry, properties, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (geometry === undefined) throw new Error('geometry is required');\n if (properties && properties.constructor !== Object) throw new Error('properties must be an Object');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var feat = {type: 'Feature'};\n if (id) feat.id = id;\n if (bbox) feat.bbox = bbox;\n feat.properties = properties || {};\n feat.geometry = geometry;\n return feat;\n}\n\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array<number>} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = 'Point';\n * var coordinates = [110, 50];\n *\n * var geometry = turf.geometry(type, coordinates);\n *\n * //=geometry\n */\nfunction geometry(type, coordinates, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n\n // Validation\n if (!type) throw new Error('type is required');\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (bbox) validateBBox(bbox);\n\n // Main\n var geom;\n switch (type) {\n case 'Point': geom = point(coordinates).geometry; break;\n case 'LineString': geom = lineString(coordinates).geometry; break;\n case 'Polygon': geom = polygon(coordinates).geometry; break;\n case 'MultiPoint': geom = multiPoint(coordinates).geometry; break;\n case 'MultiLineString': geom = multiLineString(coordinates).geometry; break;\n case 'MultiPolygon': geom = multiPolygon(coordinates).geometry; break;\n default: throw new Error(type + ' is invalid');\n }\n if (bbox) geom.bbox = bbox;\n return geom;\n}\n\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nfunction point(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long');\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'Point',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array<Array<number>>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Point>} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nfunction points(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon>} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nfunction polygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n for (var i = 0; i < coordinates.length; i++) {\n var ring = coordinates[i];\n if (ring.length < 4) {\n throw new Error('Each LinearRing of a Polygon must have 4 or more Positions.');\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (i === 0 && j === 0 && !isNumber(ring[0][0]) || !isNumber(ring[0][1])) throw new Error('coordinates must contain numbers');\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error('First and last Position are not equivalent.');\n }\n }\n }\n\n return feature({\n type: 'Polygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nfunction polygons(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString>} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nfunction lineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions');\n // Check if first point of LineString contains two numbers\n if (!isNumber(coordinates[0][1]) || !isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'LineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array<Array<number>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString>} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nfunction lineStrings(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nfunction featureCollection(features, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (!features) throw new Error('No features passed');\n if (!Array.isArray(features)) throw new Error('features must be an Array');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var fc = {type: 'FeatureCollection'};\n if (id) fc.id = id;\n if (bbox) fc.bbox = bbox;\n fc.features = features;\n return fc;\n}\n\n/**\n * Creates a {@link Feature<MultiLineString>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString>} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nfunction multiLineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiLineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPoint>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint>} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nfunction multiPoint(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPoint',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPolygon>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon>} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nfunction multiPolygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPolygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<GeometryCollection>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array<Geometry>} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = {\n * \"type\": \"Point\",\n * \"coordinates\": [100, 0]\n * };\n * var line = {\n * \"type\": \"LineString\",\n * \"coordinates\": [ [101, 0], [102, 1] ]\n * };\n * var collection = turf.geometryCollection([pt, line]);\n *\n * //=collection\n */\nfunction geometryCollection(geometries, properties, options) {\n if (!geometries) throw new Error('geometries is required');\n if (!Array.isArray(geometries)) throw new Error('geometries must be an Array');\n\n return feature({\n type: 'GeometryCollection',\n geometries: geometries\n }, properties, options);\n}\n\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nfunction round(num, precision) {\n if (num === undefined || num === null || isNaN(num)) throw new Error('num is required');\n if (precision && !(precision >= 0)) throw new Error('precision must be a positive number');\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} distance\n */\nfunction radiansToLength(radians, units) {\n if (radians === undefined || radians === null) throw new Error('radians is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return radians * factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} radians\n */\nfunction lengthToRadians(distance, units) {\n if (distance === undefined || distance === null) throw new Error('distance is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return distance / factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nfunction lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nfunction bearingToAzimuth(bearing) {\n if (bearing === null || bearing === undefined) throw new Error('bearing is required');\n\n var angle = bearing % 360;\n if (angle < 0) angle += 360;\n return angle;\n}\n\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nfunction radiansToDegrees(radians) {\n if (radians === null || radians === undefined) throw new Error('radians is required');\n\n var degrees = radians % (2 * Math.PI);\n return degrees * 180 / Math.PI;\n}\n\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nfunction degreesToRadians(degrees) {\n if (degrees === null || degrees === undefined) throw new Error('degrees is required');\n\n var radians = degrees % 360;\n return radians * Math.PI / 180;\n}\n\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {string} originalUnit of the length\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted length\n */\nfunction convertLength(length, originalUnit, finalUnit) {\n if (length === null || length === undefined) throw new Error('length is required');\n if (!(length >= 0)) throw new Error('length must be a positive number');\n\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit || 'kilometers');\n}\n\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches\n * @param {number} area to be converted\n * @param {string} [originalUnit='meters'] of the distance\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted distance\n */\nfunction convertArea(area, originalUnit, finalUnit) {\n if (area === null || area === undefined) throw new Error('area is required');\n if (!(area >= 0)) throw new Error('area must be a positive number');\n\n var startFactor = areaFactors[originalUnit || 'meters'];\n if (!startFactor) throw new Error('invalid original units');\n\n var finalFactor = areaFactors[finalUnit || 'kilometers'];\n if (!finalFactor) throw new Error('invalid final units');\n\n return (area / startFactor) * finalFactor;\n}\n\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nfunction isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nfunction isObject(input) {\n return (!!input) && (input.constructor === Object);\n}\n\n/**\n * Validate BBox\n *\n * @private\n * @param {Array<number>} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nfunction validateBBox(bbox) {\n if (!bbox) throw new Error('bbox is required');\n if (!Array.isArray(bbox)) throw new Error('bbox must be an Array');\n if (bbox.length !== 4 && bbox.length !== 6) throw new Error('bbox must be an Array of 4 or 6 numbers');\n bbox.forEach(function (num) {\n if (!isNumber(num)) throw new Error('bbox must only contain numbers');\n });\n}\n\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nfunction validateId(id) {\n if (!id) throw new Error('id is required');\n if (['string', 'number'].indexOf(typeof id) === -1) throw new Error('id must be a number or a string');\n}\n\n// Deprecated methods\nfunction radians2degrees() {\n throw new Error('method has been renamed to `radiansToDegrees`');\n}\n\nfunction degrees2radians() {\n throw new Error('method has been renamed to `degreesToRadians`');\n}\n\nfunction distanceToDegrees() {\n throw new Error('method has been renamed to `lengthToDegrees`');\n}\n\nfunction distanceToRadians() {\n throw new Error('method has been renamed to `lengthToRadians`');\n}\n\nfunction radiansToDistance() {\n throw new Error('method has been renamed to `radiansToLength`');\n}\n\nfunction bearingToAngle() {\n throw new Error('method has been renamed to `bearingToAzimuth`');\n}\n\nfunction convertDistance() {\n throw new Error('method has been renamed to `convertLength`');\n}\n\nexport { earthRadius, factors, unitsFactors, areaFactors, feature, geometry, point, points, polygon, polygons, lineString, lineStrings, featureCollection, multiLineString, multiPoint, multiPolygon, geometryCollection, round, radiansToLength, lengthToRadians, lengthToDegrees, bearingToAzimuth, radiansToDegrees, degreesToRadians, convertLength, convertArea, isNumber, isObject, validateBBox, validateId, radians2degrees, degrees2radians, distanceToDegrees, distanceToRadians, radiansToDistance, bearingToAngle, convertDistance };\n","import { isNumber } from '@turf/helpers';\n\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers\n * @returns {Array<number>} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nfunction getCoord(coord) {\n if (!coord) throw new Error('coord is required');\n if (coord.type === 'Feature' && coord.geometry !== null && coord.geometry.type === 'Point') return coord.geometry.coordinates;\n if (coord.type === 'Point') return coord.coordinates;\n if (Array.isArray(coord) && coord.length >= 2 && coord[0].length === undefined && coord[1].length === undefined) return coord;\n\n throw new Error('coord must be GeoJSON Point or an Array of numbers');\n}\n\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array<any>|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array<any>} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nfunction getCoords(coords) {\n if (!coords) throw new Error('coords is required');\n\n // Feature\n if (coords.type === 'Feature' && coords.geometry !== null) return coords.geometry.coordinates;\n\n // Geometry\n if (coords.coordinates) return coords.coordinates;\n\n // Array of numbers\n if (Array.isArray(coords)) return coords;\n\n throw new Error('coords must be GeoJSON Feature, Geometry Object or an Array');\n}\n\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array<any>} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nfunction containsNumber(coordinates) {\n if (coordinates.length > 1 && isNumber(coordinates[0]) && isNumber(coordinates[1])) {\n return true;\n }\n\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error('coordinates must only contain numbers');\n}\n\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction geojsonType(value, type, name) {\n if (!type || !name) throw new Error('type and name required');\n\n if (!value || value.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + value.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nfunction featureOf(feature, type, name) {\n if (!feature) throw new Error('No feature passed');\n if (!name) throw new Error('.featureOf() requires a name');\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction collectionOf(featureCollection, type, name) {\n if (!featureCollection) throw new Error('No featureCollection passed');\n if (!name) throw new Error('.collectionOf() requires a name');\n if (!featureCollection || featureCollection.type !== 'FeatureCollection') {\n throw new Error('Invalid input to ' + name + ', FeatureCollection required');\n }\n for (var i = 0; i < featureCollection.features.length; i++) {\n var feature = featureCollection.features[i];\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n }\n}\n\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nfunction getGeom(geojson) {\n if (!geojson) throw new Error('geojson is required');\n if (geojson.geometry !== undefined) return geojson.geometry;\n if (geojson.coordinates || geojson.geometries) return geojson;\n throw new Error('geojson must be a valid Feature or Geometry Object');\n}\n\n/**\n * Get Geometry Type from Feature or Geometry Object\n *\n * @throws {Error} **DEPRECATED** in v5.0.0 in favor of getType\n */\nfunction getGeomType() {\n throw new Error('invariant.getGeomType has been deprecated in v5.0 in favor of invariant.getType');\n}\n\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nfunction getType(geojson, name) {\n if (!geojson) throw new Error((name || 'geojson') + ' is required');\n // GeoJSON Feature & GeometryCollection\n if (geojson.geometry && geojson.geometry.type) return geojson.geometry.type;\n // GeoJSON Geometry & FeatureCollection\n if (geojson.type) return geojson.type;\n throw new Error((name || 'geojson') + ' is invalid');\n}\n\nexport { getCoord, getCoords, containsNumber, geojsonType, featureOf, collectionOf, getGeom, getGeomType, getType };\n","import { getCoord } from '@turf/invariant';\nimport { degreesToRadians, isObject, radiansToLength } from '@turf/helpers';\n\n//http://en.wikipedia.org/wiki/Haversine_formula\n//http://www.movable-type.co.uk/scripts/latlong.html\n\n/**\n * Calculates the distance between two {@link Point|points} in degrees, radians,\n * miles, or kilometers. This uses the\n * [Haversine formula](http://en.wikipedia.org/wiki/Haversine_formula)\n * to account for global curvature.\n *\n * @name distance\n * @param {Coord} from origin point\n * @param {Coord} to destination point\n * @param {Object} [options={}] Optional parameters\n * @param {string} [options.units='kilometers'] can be degrees, radians, miles, or kilometers\n * @returns {number} distance between the two points\n * @example\n * var from = turf.point([-75.343, 39.984]);\n * var to = turf.point([-75.534, 39.123]);\n * var options = {units: 'miles'};\n *\n * var distance = turf.distance(from, to, options);\n *\n * //addToMap\n * var addToMap = [from, to];\n * from.properties.distance = distance;\n * to.properties.distance = distance;\n */\nfunction distance(from, to, options) {\n // Optional parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var units = options.units;\n\n var coordinates1 = getCoord(from);\n var coordinates2 = getCoord(to);\n var dLat = degreesToRadians((coordinates2[1] - coordinates1[1]));\n var dLon = degreesToRadians((coordinates2[0] - coordinates1[0]));\n var lat1 = degreesToRadians(coordinates1[1]);\n var lat2 = degreesToRadians(coordinates2[1]);\n\n var a = Math.pow(Math.sin(dLat / 2), 2) +\n Math.pow(Math.sin(dLon / 2), 2) * Math.cos(lat1) * Math.cos(lat2);\n\n return radiansToLength(2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)), units);\n}\n\nexport default distance;\n","import bearing from '@turf/bearing';\nimport destination from '@turf/destination';\nimport distance from '@turf/distance';\n\n/**\n * Takes two {@link Point|points} and returns a point midway between them.\n * The midpoint is calculated geodesically, meaning the curvature of the earth is taken into account.\n *\n * @name midpoint\n * @param {Coord} point1 first point\n * @param {Coord} point2 second point\n * @returns {Feature<Point>} a point midway between `pt1` and `pt2`\n * @example\n * var point1 = turf.point([144.834823, -37.771257]);\n * var point2 = turf.point([145.14244, -37.830937]);\n *\n * var midpoint = turf.midpoint(point1, point2);\n *\n * //addToMap\n * var addToMap = [point1, point2, midpoint];\n * midpoint.properties['marker-color'] = '#f00';\n */\nfunction midpoint(point1, point2) {\n var dist = distance(point1, point2);\n var heading = bearing(point1, point2);\n var midpoint = destination(point1, dist / 2, heading);\n\n return midpoint;\n}\n\nexport default midpoint;\n","/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n */\nvar earthRadius = 6371008.8;\n\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n */\nvar factors = {\n meters: earthRadius,\n metres: earthRadius,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n miles: earthRadius / 1609.344,\n nauticalmiles: earthRadius / 1852,\n inches: earthRadius * 39.370,\n yards: earthRadius / 1.0936,\n feet: earthRadius * 3.28084,\n radians: 1,\n degrees: earthRadius / 111325,\n};\n\n/**\n * Units of measurement factors based on 1 meter.\n */\nvar unitsFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000,\n millimetres: 1000,\n centimeters: 100,\n centimetres: 100,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n miles: 1 / 1609.344,\n nauticalmiles: 1 / 1852,\n inches: 39.370,\n yards: 1 / 1.0936,\n feet: 3.28084,\n radians: 1 / earthRadius,\n degrees: 1 / 111325,\n};\n\n/**\n * Area of measurement factors based on 1 square meter.\n */\nvar areaFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000000,\n millimetres: 1000000,\n centimeters: 10000,\n centimetres: 10000,\n kilometers: 0.000001,\n kilometres: 0.000001,\n acres: 0.000247105,\n miles: 3.86e-7,\n yards: 1.195990046,\n feet: 10.763910417,\n inches: 1550.003100006\n};\n\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nfunction feature(geometry, properties, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (geometry === undefined) throw new Error('geometry is required');\n if (properties && properties.constructor !== Object) throw new Error('properties must be an Object');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var feat = {type: 'Feature'};\n if (id) feat.id = id;\n if (bbox) feat.bbox = bbox;\n feat.properties = properties || {};\n feat.geometry = geometry;\n return feat;\n}\n\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array<number>} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = 'Point';\n * var coordinates = [110, 50];\n *\n * var geometry = turf.geometry(type, coordinates);\n *\n * //=geometry\n */\nfunction geometry(type, coordinates, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n\n // Validation\n if (!type) throw new Error('type is required');\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (bbox) validateBBox(bbox);\n\n // Main\n var geom;\n switch (type) {\n case 'Point': geom = point(coordinates).geometry; break;\n case 'LineString': geom = lineString(coordinates).geometry; break;\n case 'Polygon': geom = polygon(coordinates).geometry; break;\n case 'MultiPoint': geom = multiPoint(coordinates).geometry; break;\n case 'MultiLineString': geom = multiLineString(coordinates).geometry; break;\n case 'MultiPolygon': geom = multiPolygon(coordinates).geometry; break;\n default: throw new Error(type + ' is invalid');\n }\n if (bbox) geom.bbox = bbox;\n return geom;\n}\n\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nfunction point(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long');\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'Point',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array<Array<number>>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Point>} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nfunction points(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon>} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nfunction polygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n for (var i = 0; i < coordinates.length; i++) {\n var ring = coordinates[i];\n if (ring.length < 4) {\n throw new Error('Each LinearRing of a Polygon must have 4 or more Positions.');\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (i === 0 && j === 0 && !isNumber(ring[0][0]) || !isNumber(ring[0][1])) throw new Error('coordinates must contain numbers');\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error('First and last Position are not equivalent.');\n }\n }\n }\n\n return feature({\n type: 'Polygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nfunction polygons(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString>} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nfunction lineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions');\n // Check if first point of LineString contains two numbers\n if (!isNumber(coordinates[0][1]) || !isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'LineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array<Array<number>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString>} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nfunction lineStrings(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nfunction featureCollection(features, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (!features) throw new Error('No features passed');\n if (!Array.isArray(features)) throw new Error('features must be an Array');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var fc = {type: 'FeatureCollection'};\n if (id) fc.id = id;\n if (bbox) fc.bbox = bbox;\n fc.features = features;\n return fc;\n}\n\n/**\n * Creates a {@link Feature<MultiLineString>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString>} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nfunction multiLineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiLineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPoint>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint>} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nfunction multiPoint(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPoint',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPolygon>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon>} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nfunction multiPolygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPolygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<GeometryCollection>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array<Geometry>} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = {\n * \"type\": \"Point\",\n * \"coordinates\": [100, 0]\n * };\n * var line = {\n * \"type\": \"LineString\",\n * \"coordinates\": [ [101, 0], [102, 1] ]\n * };\n * var collection = turf.geometryCollection([pt, line]);\n *\n * //=collection\n */\nfunction geometryCollection(geometries, properties, options) {\n if (!geometries) throw new Error('geometries is required');\n if (!Array.isArray(geometries)) throw new Error('geometries must be an Array');\n\n return feature({\n type: 'GeometryCollection',\n geometries: geometries\n }, properties, options);\n}\n\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nfunction round(num, precision) {\n if (num === undefined || num === null || isNaN(num)) throw new Error('num is required');\n if (precision && !(precision >= 0)) throw new Error('precision must be a positive number');\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} distance\n */\nfunction radiansToLength(radians, units) {\n if (radians === undefined || radians === null) throw new Error('radians is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return radians * factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} radians\n */\nfunction lengthToRadians(distance, units) {\n if (distance === undefined || distance === null) throw new Error('distance is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return distance / factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nfunction lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nfunction bearingToAzimuth(bearing) {\n if (bearing === null || bearing === undefined) throw new Error('bearing is required');\n\n var angle = bearing % 360;\n if (angle < 0) angle += 360;\n return angle;\n}\n\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nfunction radiansToDegrees(radians) {\n if (radians === null || radians === undefined) throw new Error('radians is required');\n\n var degrees = radians % (2 * Math.PI);\n return degrees * 180 / Math.PI;\n}\n\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nfunction degreesToRadians(degrees) {\n if (degrees === null || degrees === undefined) throw new Error('degrees is required');\n\n var radians = degrees % 360;\n return radians * Math.PI / 180;\n}\n\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {string} originalUnit of the length\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted length\n */\nfunction convertLength(length, originalUnit, finalUnit) {\n if (length === null || length === undefined) throw new Error('length is required');\n if (!(length >= 0)) throw new Error('length must be a positive number');\n\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit || 'kilometers');\n}\n\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches\n * @param {number} area to be converted\n * @param {string} [originalUnit='meters'] of the distance\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted distance\n */\nfunction convertArea(area, originalUnit, finalUnit) {\n if (area === null || area === undefined) throw new Error('area is required');\n if (!(area >= 0)) throw new Error('area must be a positive number');\n\n var startFactor = areaFactors[originalUnit || 'meters'];\n if (!startFactor) throw new Error('invalid original units');\n\n var finalFactor = areaFactors[finalUnit || 'kilometers'];\n if (!finalFactor) throw new Error('invalid final units');\n\n return (area / startFactor) * finalFactor;\n}\n\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nfunction isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nfunction isObject(input) {\n return (!!input) && (input.constructor === Object);\n}\n\n/**\n * Validate BBox\n *\n * @private\n * @param {Array<number>} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nfunction validateBBox(bbox) {\n if (!bbox) throw new Error('bbox is required');\n if (!Array.isArray(bbox)) throw new Error('bbox must be an Array');\n if (bbox.length !== 4 && bbox.length !== 6) throw new Error('bbox must be an Array of 4 or 6 numbers');\n bbox.forEach(function (num) {\n if (!isNumber(num)) throw new Error('bbox must only contain numbers');\n });\n}\n\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nfunction validateId(id) {\n if (!id) throw new Error('id is required');\n if (['string', 'number'].indexOf(typeof id) === -1) throw new Error('id must be a number or a string');\n}\n\n// Deprecated methods\nfunction radians2degrees() {\n throw new Error('method has been renamed to `radiansToDegrees`');\n}\n\nfunction degrees2radians() {\n throw new Error('method has been renamed to `degreesToRadians`');\n}\n\nfunction distanceToDegrees() {\n throw new Error('method has been renamed to `lengthToDegrees`');\n}\n\nfunction distanceToRadians() {\n throw new Error('method has been renamed to `lengthToRadians`');\n}\n\nfunction radiansToDistance() {\n throw new Error('method has been renamed to `radiansToLength`');\n}\n\nfunction bearingToAngle() {\n throw new Error('method has been renamed to `bearingToAzimuth`');\n}\n\nfunction convertDistance() {\n throw new Error('method has been renamed to `convertLength`');\n}\n\nexport { earthRadius, factors, unitsFactors, areaFactors, feature, geometry, point, points, polygon, polygons, lineString, lineStrings, featureCollection, multiLineString, multiPoint, multiPolygon, geometryCollection, round, radiansToLength, lengthToRadians, lengthToDegrees, bearingToAzimuth, radiansToDegrees, degreesToRadians, convertLength, convertArea, isNumber, isObject, validateBBox, validateId, radians2degrees, degrees2radians, distanceToDegrees, distanceToRadians, radiansToDistance, bearingToAngle, convertDistance };\n","import { feature, isObject, lineString, point } from '@turf/helpers';\n\n/**\n * Callback for coordEach\n *\n * @callback coordEachCallback\n * @param {Array<number>} currentCoord The current coordinate being processed.\n * @param {number} coordIndex The current index of the coordinate being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n */\n\n/**\n * Iterate over coordinates in any GeoJSON object, similar to Array.forEach()\n *\n * @name coordEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, multiFeatureIndex)\n * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=currentCoord\n * //=coordIndex\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * });\n */\nfunction coordEach(geojson, callback, excludeWrapCoord) {\n // Handles null Geometry -- Skips this GeoJSON\n if (geojson === null) return;\n var j, k, l, geometry, stopG, coords,\n geometryMaybeCollection,\n wrapShrink = 0,\n coordIndex = 0,\n isGeometryCollection,\n type = geojson.type,\n isFeatureCollection = type === 'FeatureCollection',\n isFeature = type === 'Feature',\n stop = isFeatureCollection ? geojson.features.length : 1;\n\n // This logic may look a little weird. The reason why it is that way\n // is because it's trying to be fast. GeoJSON supports multiple kinds\n // of objects at its root: FeatureCollection, Features, Geometries.\n // This function has the responsibility of handling all of them, and that\n // means that some of the `for` loops you see below actually just don't apply\n // to certain inputs. For instance, if you give this just a\n // Point geometry, then both loops are short-circuited and all we do\n // is gradually rename the input until it's called 'geometry'.\n //\n // This also aims to allocate as few resources as possible: just a\n // few numbers and booleans, rather than any temporary arrays as would\n // be required with the normalization approach.\n for (var featureIndex = 0; featureIndex < stop; featureIndex++) {\n geometryMaybeCollection = (isFeatureCollection ? geojson.features[featureIndex].geometry :\n (isFeature ? geojson.geometry : geojson));\n isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;\n stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;\n\n for (var geomIndex = 0; geomIndex < stopG; geomIndex++) {\n var multiFeatureIndex = 0;\n var geometryIndex = 0;\n geometry = isGeometryCollection ?\n geometryMaybeCollection.geometries[geomIndex] : geometryMaybeCollection;\n\n // Handles null Geometry -- Skips this geometry\n if (geometry === null) continue;\n coords = geometry.coordinates;\n var geomType = geometry.type;\n\n wrapShrink = (excludeWrapCoord && (geomType === 'Polygon' || geomType === 'MultiPolygon')) ? 1 : 0;\n\n switch (geomType) {\n case null:\n break;\n case 'Point':\n if (callback(coords, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n multiFeatureIndex++;\n break;\n case 'LineString':\n case 'MultiPoint':\n for (j = 0; j < coords.length; j++) {\n if (callback(coords[j], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n if (geomType === 'MultiPoint') multiFeatureIndex++;\n }\n if (geomType === 'LineString') multiFeatureIndex++;\n break;\n case 'Polygon':\n case 'MultiLineString':\n for (j = 0; j < coords.length; j++) {\n for (k = 0; k < coords[j].length - wrapShrink; k++) {\n if (callback(coords[j][k], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n }\n if (geomType === 'MultiLineString') multiFeatureIndex++;\n if (geomType === 'Polygon') geometryIndex++;\n }\n if (geomType === 'Polygon') multiFeatureIndex++;\n break;\n case 'MultiPolygon':\n for (j = 0; j < coords.length; j++) {\n if (geomType === 'MultiPolygon') geometryIndex = 0;\n for (k = 0; k < coords[j].length; k++) {\n for (l = 0; l < coords[j][k].length - wrapShrink; l++) {\n if (callback(coords[j][k][l], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n }\n geometryIndex++;\n }\n multiFeatureIndex++;\n }\n break;\n case 'GeometryCollection':\n for (j = 0; j < geometry.geometries.length; j++)\n if (coordEach(geometry.geometries[j], callback, excludeWrapCoord) === false) return false;\n break;\n default:\n throw new Error('Unknown Geometry Type');\n }\n }\n }\n}\n\n/**\n * Callback for coordReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback coordReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Array<number>} currentCoord The current coordinate being processed.\n * @param {number} coordIndex The current index of the coordinate being processed.\n * Starts at index 0, if an initialValue is provided, and at index 1 otherwise.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n */\n\n/**\n * Reduce coordinates in any GeoJSON object, similar to Array.reduce()\n *\n * @name coordReduce\n * @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=previousValue\n * //=currentCoord\n * //=coordIndex\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * return currentCoord;\n * });\n */\nfunction coordReduce(geojson, callback, initialValue, excludeWrapCoord) {\n var previousValue = initialValue;\n coordEach(geojson, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n if (coordIndex === 0 && initialValue === undefined) previousValue = currentCoord;\n else previousValue = callback(previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex);\n }, excludeWrapCoord);\n return previousValue;\n}\n\n/**\n * Callback for propEach\n *\n * @callback propEachCallback\n * @param {Object} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Iterate over properties in any GeoJSON object, similar to Array.forEach()\n *\n * @name propEach\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentProperties, featureIndex)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.propEach(features, function (currentProperties, featureIndex) {\n * //=currentProperties\n * //=featureIndex\n * });\n */\nfunction propEach(geojson, callback) {\n var i;\n switch (geojson.type) {\n case 'FeatureCollection':\n for (i = 0; i < geojson.features.length; i++) {\n if (callback(geojson.features[i].properties, i) === false) break;\n }\n break;\n case 'Feature':\n callback(geojson.properties, 0);\n break;\n }\n}\n\n\n/**\n * Callback for propReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback propReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {*} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Reduce properties in any GeoJSON object into a single value,\n * similar to how Array.reduce works. However, in this case we lazily run\n * the reduction, so an array of all properties is unnecessary.\n *\n * @name propReduce\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.propReduce(features, function (previousValue, currentProperties, featureIndex) {\n * //=previousValue\n * //=currentProperties\n * //=featureIndex\n * return currentProperties\n * });\n */\nfunction propReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n propEach(geojson, function (currentProperties, featureIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties;\n else previousValue = callback(previousValue, currentProperties, featureIndex);\n });\n return previousValue;\n}\n\n/**\n * Callback for featureEach\n *\n * @callback featureEachCallback\n * @param {Feature<any>} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Iterate over features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @name featureEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentFeature, featureIndex)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.featureEach(features, function (currentFeature, featureIndex) {\n * //=currentFeature\n * //=featureIndex\n * });\n */\nfunction featureEach(geojson, callback) {\n if (geojson.type === 'Feature') {\n callback(geojson, 0);\n } else if (geojson.type === 'FeatureCollection') {\n for (var i = 0; i < geojson.features.length; i++) {\n if (callback(geojson.features[i], i) === false) break;\n }\n }\n}\n\n/**\n * Callback for featureReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback featureReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @name featureReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.featureReduce(features, function (previousValue, currentFeature, featureIndex) {\n * //=previousValue\n * //=currentFeature\n * //=featureIndex\n * return currentFeature\n * });\n */\nfunction featureReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n featureEach(geojson, function (currentFeature, featureIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature;\n else previousValue = callback(previousValue, currentFeature, featureIndex);\n });\n return previousValue;\n}\n\n/**\n * Get all coordinates from any GeoJSON object.\n *\n * @name coordAll\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @returns {Array<Array<number>>} coordinate position array\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * var coords = turf.coordAll(features);\n * //= [[26, 37], [36, 53]]\n */\nfunction coordAll(geojson) {\n var coords = [];\n coordEach(geojson, function (coord) {\n coords.push(coord);\n });\n return coords;\n}\n\n/**\n * Callback for geomEach\n *\n * @callback geomEachCallback\n * @param {Geometry} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {Object} featureProperties The current Feature Properties being processed.\n * @param {Array<number>} featureBBox The current Feature BBox being processed.\n * @param {number|string} featureId The current Feature Id being processed.\n */\n\n/**\n * Iterate over each geometry in any GeoJSON object, similar to Array.forEach()\n *\n * @name geomEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n * //=currentGeometry\n * //=featureIndex\n * //=featureProperties\n * //=featureBBox\n * //=featureId\n * });\n */\nfunction geomEach(geojson, callback) {\n var i, j, g, geometry, stopG,\n geometryMaybeCollection,\n isGeometryCollection,\n featureProperties,\n featureBBox,\n featureId,\n featureIndex = 0,\n isFeatureCollection = geojson.type === 'FeatureCollection',\n isFeature = geojson.type === 'Feature',\n stop = isFeatureCollection ? geojson.features.length : 1;\n\n // This logic may look a little weird. The reason why it is that way\n // is because it's trying to be fast. GeoJSON supports multiple kinds\n // of objects at its root: FeatureCollection, Features, Geometries.\n // This function has the responsibility of handling all of them, and that\n // means that some of the `for` loops you see below actually just don't apply\n // to certain inputs. For instance, if you give this just a\n // Point geometry, then both loops are short-circuited and all we do\n // is gradually rename the input until it's called 'geometry'.\n //\n // This also aims to allocate as few resources as possible: just a\n // few numbers and booleans, rather than any temporary arrays as would\n // be required with the normalization approach.\n for (i = 0; i < stop; i++) {\n\n geometryMaybeCollection = (isFeatureCollection ? geojson.features[i].geometry :\n (isFeature ? geojson.geometry : geojson));\n featureProperties = (isFeatureCollection ? geojson.features[i].properties :\n (isFeature ? geojson.properties : {}));\n featureBBox = (isFeatureCollection ? geojson.features[i].bbox :\n (isFeature ? geojson.bbox : undefined));\n featureId = (isFeatureCollection ? geojson.features[i].id :\n (isFeature ? geojson.id : undefined));\n isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;\n stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;\n\n for (g = 0; g < stopG; g++) {\n geometry = isGeometryCollection ?\n geometryMaybeCollection.geometries[g] : geometryMaybeCollection;\n\n // Handle null Geometry\n if (geometry === null) {\n if (callback(null, featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n continue;\n }\n switch (geometry.type) {\n case 'Point':\n case 'LineString':\n case 'MultiPoint':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon': {\n if (callback(geometry, featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n break;\n }\n case 'GeometryCollection': {\n for (j = 0; j < geometry.geometries.length; j++) {\n if (callback(geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n }\n break;\n }\n default:\n throw new Error('Unknown Geometry Type');\n }\n }\n // Only increase `featureIndex` per each feature\n featureIndex++;\n }\n}\n\n/**\n * Callback for geomReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback geomReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Geometry} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {Object} featureProperties The current Feature Properties being processed.\n * @param {Array<number>} featureBBox The current Feature BBox being processed.\n * @param {number|string} featureId The current Feature Id being processed.\n */\n\n/**\n * Reduce geometry in any GeoJSON object, similar to Array.reduce().\n *\n * @name geomReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n * //=previousValue\n * //=currentGeometry\n * //=featureIndex\n * //=featureProperties\n * //=featureBBox\n * //=featureId\n * return currentGeometry\n * });\n */\nfunction geomReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n geomEach(geojson, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry;\n else previousValue = callback(previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId);\n });\n return previousValue;\n}\n\n/**\n * Callback for flattenEach\n *\n * @callback flattenEachCallback\n * @param {Feature} currentFeature The current flattened feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n */\n\n/**\n * Iterate over flattened features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @name flattenEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex)\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})\n * ]);\n *\n * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) {\n * //=currentFeature\n * //=featureIndex\n * //=multiFeatureIndex\n * });\n */\nfunction flattenEach(geojson, callback) {\n geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) {\n // Callback for single geometry\n var type = (geometry === null) ? null : geometry.type;\n switch (type) {\n case null:\n case 'Point':\n case 'LineString':\n case 'Polygon':\n if (callback(feature(geometry, properties, {bbox: bbox, id: id}), featureIndex, 0) === false) return false;\n return;\n }\n\n var geomType;\n\n // Callback for multi-geometry\n switch (type) {\n case 'MultiPoint':\n geomType = 'Point';\n break;\n case 'MultiLineString':\n geomType = 'LineString';\n break;\n case 'MultiPolygon':\n geomType = 'Polygon';\n break;\n }\n\n for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) {\n var coordinate = geometry.coordinates[multiFeatureIndex];\n var geom = {\n type: geomType,\n coordinates: coordinate\n };\n if (callback(feature(geom, properties), featureIndex, multiFeatureIndex) === false) return false;\n }\n });\n}\n\n/**\n * Callback for flattenReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback flattenReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n */\n\n/**\n * Reduce flattened features in any GeoJSON object, similar to Array.reduce().\n *\n * @name flattenReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})\n * ]);\n *\n * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) {\n * //=previousValue\n * //=currentFeature\n * //=featureIndex\n * //=multiFeatureIndex\n * return currentFeature\n * });\n */\nfunction flattenReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n flattenEach(geojson, function (currentFeature, featureIndex, multiFeatureIndex) {\n if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined) previousValue = currentFeature;\n else previousValue = callback(previousValue, currentFeature, featureIndex, multiFeatureIndex);\n });\n return previousValue;\n}\n\n/**\n * Callback for segmentEach\n *\n * @callback segmentEachCallback\n * @param {Feature<LineString>} currentSegment The current Segment being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n * @param {number} segmentIndex The current index of the Segment being processed.\n * @returns {void}\n */\n\n/**\n * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach()\n * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON\n * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex)\n * @returns {void}\n * @example\n * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);\n *\n * // Iterate over GeoJSON by 2-vertex segments\n * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n * //=currentSegment\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * //=segmentIndex\n * });\n *\n * // Calculate the total number of segments\n * var total = 0;\n * turf.segmentEach(polygon, function () {\n * total++;\n * });\n */\nfunction segmentEach(geojson, callback) {\n flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) {\n var segmentIndex = 0;\n\n // Exclude null Geometries\n if (!feature$$1.geometry) return;\n // (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n var type = feature$$1.geometry.type;\n if (type === 'Point' || type === 'MultiPoint') return;\n\n // Generate 2-vertex line segments\n var previousCoords;\n if (coordEach(feature$$1, function (currentCoord, coordIndex, featureIndexCoord, mutliPartIndexCoord, geometryIndex) {\n // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false`\n if (previousCoords === undefined) {\n previousCoords = currentCoord;\n return;\n }\n var currentSegment = lineString([previousCoords, currentCoord], feature$$1.properties);\n if (callback(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) === false) return false;\n segmentIndex++;\n previousCoords = currentCoord;\n }) === false) return false;\n });\n}\n\n/**\n * Callback for segmentReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback segmentReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature<LineString>} currentSegment The current Segment being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n * @param {number} segmentIndex The current index of the Segment being processed.\n */\n\n/**\n * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce()\n * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON\n * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {void}\n * @example\n * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);\n *\n * // Iterate over GeoJSON by 2-vertex segments\n * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n * //= previousSegment\n * //= currentSegment\n * //= featureIndex\n * //= multiFeatureIndex\n * //= geometryIndex\n * //= segmentInex\n * return currentSegment\n * });\n *\n * // Calculate the total number of segments\n * var initialValue = 0\n * var total = turf.segmentReduce(polygon, function (previousValue) {\n * previousValue++;\n * return previousValue;\n * }, initialValue);\n */\nfunction segmentReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n var started = false;\n segmentEach(geojson, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n if (started === false && initialValue === undefined) previousValue = currentSegment;\n else previousValue = callback(previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex);\n started = true;\n });\n return previousValue;\n}\n\n/**\n * Callback for lineEach\n *\n * @callback lineEachCallback\n * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed\n * @param {number} featureIndex The current index of the Feature being processed\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed\n * @param {number} geometryIndex The current index of the Geometry being processed\n */\n\n/**\n * Iterate over line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries,\n * similar to Array.forEach.\n *\n * @name lineEach\n * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object\n * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @example\n * var multiLine = turf.multiLineString([\n * [[26, 37], [35, 45]],\n * [[36, 53], [38, 50], [41, 55]]\n * ]);\n *\n * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=currentLine\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * });\n */\nfunction lineEach(geojson, callback) {\n // validation\n if (!geojson) throw new Error('geojson is required');\n\n flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) {\n if (feature$$1.geometry === null) return;\n var type = feature$$1.geometry.type;\n var coords = feature$$1.geometry.coordinates;\n switch (type) {\n case 'LineString':\n if (callback(feature$$1, featureIndex, multiFeatureIndex, 0, 0) === false) return false;\n break;\n case 'Polygon':\n for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) {\n if (callback(lineString(coords[geometryIndex], feature$$1.properties), featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n }\n break;\n }\n });\n}\n\n/**\n * Callback for lineReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback lineReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed.\n * @param {number} featureIndex The current index of the Feature being processed\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed\n * @param {number} geometryIndex The current index of the Geometry being processed\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @name lineReduce\n * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object\n * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var multiPoly = turf.multiPolygon([\n * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]),\n * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]])\n * ]);\n *\n * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=previousValue\n * //=currentLine\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * return currentLine\n * });\n */\nfunction lineReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n lineEach(geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine;\n else previousValue = callback(previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex);\n });\n return previousValue;\n}\n\n/**\n * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes.\n *\n * Negative indexes are permitted.\n * Point & MultiPoint will always return null.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry\n * @param {Object} [options={}] Optional parameters\n * @param {number} [options.featureIndex=0] Feature Index\n * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index\n * @param {number} [options.geometryIndex=0] Geometry Index\n * @param {number} [options.segmentIndex=0] Segment Index\n * @param {Object} [options.properties={}] Translate Properties to output LineString\n * @param {BBox} [options.bbox={}] Translate BBox to output LineString\n * @param {number|string} [options.id={}] Translate Id to output LineString\n * @returns {Feature<LineString>} 2-vertex GeoJSON Feature LineString\n * @example\n * var multiLine = turf.multiLineString([\n * [[10, 10], [50, 30], [30, 40]],\n * [[-10, -10], [-50, -30], [-30, -40]]\n * ]);\n *\n * // First Segment (defaults are 0)\n * turf.findSegment(multiLine);\n * // => Feature<LineString<[[10, 10], [50, 30]]>>\n *\n * // First Segment of 2nd Multi Feature\n * turf.findSegment(multiLine, {multiFeatureIndex: 1});\n * // => Feature<LineString<[[-10, -10], [-50, -30]]>>\n *\n * // Last Segment of Last Multi Feature\n * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1});\n * // => Feature<LineString<[[-50, -30], [-30, -40]]>>\n */\nfunction findSegment(geojson, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var featureIndex = options.featureIndex || 0;\n var multiFeatureIndex = options.multiFeatureIndex || 0;\n var geometryIndex = options.geometryIndex || 0;\n var segmentIndex = options.segmentIndex || 0;\n\n // Find FeatureIndex\n var properties = options.properties;\n var geometry;\n\n switch (geojson.type) {\n case 'FeatureCollection':\n if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;\n properties = properties || geojson.features[featureIndex].properties;\n geometry = geojson.features[featureIndex].geometry;\n break;\n case 'Feature':\n properties = properties || geojson.properties;\n geometry = geojson.geometry;\n break;\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon':\n geometry = geojson;\n break;\n default:\n throw new Error('geojson is invalid');\n }\n\n // Find SegmentIndex\n if (geometry === null) return null;\n var coords = geometry.coordinates;\n switch (geometry.type) {\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1;\n return lineString([coords[segmentIndex], coords[segmentIndex + 1]], properties, options);\n case 'Polygon':\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1;\n return lineString([coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1]], properties, options);\n case 'MultiLineString':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1;\n return lineString([coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1]], properties, options);\n case 'MultiPolygon':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1;\n return lineString([coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]], properties, options);\n }\n throw new Error('geojson is invalid');\n}\n\n/**\n * Finds a particular Point from a GeoJSON using `@turf/meta` indexes.\n *\n * Negative indexes are permitted.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry\n * @param {Object} [options={}] Optional parameters\n * @param {number} [options.featureIndex=0] Feature Index\n * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index\n * @param {number} [options.geometryIndex=0] Geometry Index\n * @param {number} [options.coordIndex=0] Coord Index\n * @param {Object} [options.properties={}] Translate Properties to output Point\n * @param {BBox} [options.bbox={}] Translate BBox to output Point\n * @param {number|string} [options.id={}] Translate Id to output Point\n * @returns {Feature<Point>} 2-vertex GeoJSON Feature Point\n * @example\n * var multiLine = turf.multiLineString([\n * [[10, 10], [50, 30], [30, 40]],\n * [[-10, -10], [-50, -30], [-30, -40]]\n * ]);\n *\n * // First Segment (defaults are 0)\n * turf.findPoint(multiLine);\n * // => Feature<Point<[10, 10]>>\n *\n * // First Segment of the 2nd Multi-Feature\n * turf.findPoint(multiLine, {multiFeatureIndex: 1});\n * // => Feature<Point<[-10, -10]>>\n *\n * // Last Segment of last Multi-Feature\n * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1});\n * // => Feature<Point<[-30, -40]>>\n */\nfunction findPoint(geojson, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var featureIndex = options.featureIndex || 0;\n var multiFeatureIndex = options.multiFeatureIndex || 0;\n var geometryIndex = options.geometryIndex || 0;\n var coordIndex = options.coordIndex || 0;\n\n // Find FeatureIndex\n var properties = options.properties;\n var geometry;\n\n switch (geojson.type) {\n case 'FeatureCollection':\n if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;\n properties = properties || geojson.features[featureIndex].properties;\n geometry = geojson.features[featureIndex].geometry;\n break;\n case 'Feature':\n properties = properties || geojson.properties;\n geometry = geojson.geometry;\n break;\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon':\n geometry = geojson;\n break;\n default:\n throw new Error('geojson is invalid');\n }\n\n // Find Coord Index\n if (geometry === null) return null;\n var coords = geometry.coordinates;\n switch (geometry.type) {\n case 'Point':\n return point(coords, properties, options);\n case 'MultiPoint':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n return point(coords[multiFeatureIndex], properties, options);\n case 'LineString':\n if (coordIndex < 0) coordIndex = coords.length + coordIndex;\n return point(coords[coordIndex], properties, options);\n case 'Polygon':\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex;\n return point(coords[geometryIndex][coordIndex], properties, options);\n case 'MultiLineString':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex;\n return point(coords[multiFeatureIndex][coordIndex], properties, options);\n case 'MultiPolygon':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex;\n return point(coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options);\n }\n throw new Error('geojson is invalid');\n}\n\nexport { coordEach, coordReduce, propEach, propReduce, featureEach, featureReduce, coordAll, geomEach, geomReduce, flattenEach, flattenReduce, segmentEach, segmentReduce, lineEach, lineReduce, findSegment, findPoint };\n","import { coordEach } from '@turf/meta';\nimport { point } from '@turf/helpers';\n\n/**\n * Takes one or more features and calculates the centroid using the mean of all vertices.\n * This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons.\n *\n * @name centroid\n * @param {GeoJSON} geojson GeoJSON to be centered\n * @param {Object} [properties={}] an Object that is used as the {@link Feature}'s properties\n * @returns {Feature<Point>} the centroid of the input features\n * @example\n * var polygon = turf.polygon([[[-81, 41], [-88, 36], [-84, 31], [-80, 33], [-77, 39], [-81, 41]]]);\n *\n * var centroid = turf.centroid(polygon);\n *\n * //addToMap\n * var addToMap = [polygon, centroid]\n */\nfunction centroid(geojson, properties) {\n var xSum = 0;\n var ySum = 0;\n var len = 0;\n coordEach(geojson, function (coord) {\n xSum += coord[0];\n ySum += coord[1];\n len++;\n }, true);\n return point([xSum / len, ySum / len], properties);\n}\n\nexport default centroid;\n","/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n */\nvar earthRadius = 6371008.8;\n\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n */\nvar factors = {\n meters: earthRadius,\n metres: earthRadius,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n miles: earthRadius / 1609.344,\n nauticalmiles: earthRadius / 1852,\n inches: earthRadius * 39.370,\n yards: earthRadius / 1.0936,\n feet: earthRadius * 3.28084,\n radians: 1,\n degrees: earthRadius / 111325,\n};\n\n/**\n * Units of measurement factors based on 1 meter.\n */\nvar unitsFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000,\n millimetres: 1000,\n centimeters: 100,\n centimetres: 100,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n miles: 1 / 1609.344,\n nauticalmiles: 1 / 1852,\n inches: 39.370,\n yards: 1 / 1.0936,\n feet: 3.28084,\n radians: 1 / earthRadius,\n degrees: 1 / 111325,\n};\n\n/**\n * Area of measurement factors based on 1 square meter.\n */\nvar areaFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000000,\n millimetres: 1000000,\n centimeters: 10000,\n centimetres: 10000,\n kilometers: 0.000001,\n kilometres: 0.000001,\n acres: 0.000247105,\n miles: 3.86e-7,\n yards: 1.195990046,\n feet: 10.763910417,\n inches: 1550.003100006\n};\n\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nfunction feature(geometry, properties, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (geometry === undefined) throw new Error('geometry is required');\n if (properties && properties.constructor !== Object) throw new Error('properties must be an Object');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var feat = {type: 'Feature'};\n if (id) feat.id = id;\n if (bbox) feat.bbox = bbox;\n feat.properties = properties || {};\n feat.geometry = geometry;\n return feat;\n}\n\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array<number>} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = 'Point';\n * var coordinates = [110, 50];\n *\n * var geometry = turf.geometry(type, coordinates);\n *\n * //=geometry\n */\nfunction geometry(type, coordinates, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n\n // Validation\n if (!type) throw new Error('type is required');\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (bbox) validateBBox(bbox);\n\n // Main\n var geom;\n switch (type) {\n case 'Point': geom = point(coordinates).geometry; break;\n case 'LineString': geom = lineString(coordinates).geometry; break;\n case 'Polygon': geom = polygon(coordinates).geometry; break;\n case 'MultiPoint': geom = multiPoint(coordinates).geometry; break;\n case 'MultiLineString': geom = multiLineString(coordinates).geometry; break;\n case 'MultiPolygon': geom = multiPolygon(coordinates).geometry; break;\n default: throw new Error(type + ' is invalid');\n }\n if (bbox) geom.bbox = bbox;\n return geom;\n}\n\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nfunction point(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long');\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'Point',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array<Array<number>>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Point>} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nfunction points(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon>} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nfunction polygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n for (var i = 0; i < coordinates.length; i++) {\n var ring = coordinates[i];\n if (ring.length < 4) {\n throw new Error('Each LinearRing of a Polygon must have 4 or more Positions.');\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (i === 0 && j === 0 && !isNumber(ring[0][0]) || !isNumber(ring[0][1])) throw new Error('coordinates must contain numbers');\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error('First and last Position are not equivalent.');\n }\n }\n }\n\n return feature({\n type: 'Polygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nfunction polygons(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString>} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nfunction lineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions');\n // Check if first point of LineString contains two numbers\n if (!isNumber(coordinates[0][1]) || !isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'LineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array<Array<number>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString>} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nfunction lineStrings(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nfunction featureCollection(features, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (!features) throw new Error('No features passed');\n if (!Array.isArray(features)) throw new Error('features must be an Array');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var fc = {type: 'FeatureCollection'};\n if (id) fc.id = id;\n if (bbox) fc.bbox = bbox;\n fc.features = features;\n return fc;\n}\n\n/**\n * Creates a {@link Feature<MultiLineString>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString>} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nfunction multiLineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiLineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPoint>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint>} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nfunction multiPoint(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPoint',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPolygon>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon>} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nfunction multiPolygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPolygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<GeometryCollection>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array<Geometry>} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = {\n * \"type\": \"Point\",\n * \"coordinates\": [100, 0]\n * };\n * var line = {\n * \"type\": \"LineString\",\n * \"coordinates\": [ [101, 0], [102, 1] ]\n * };\n * var collection = turf.geometryCollection([pt, line]);\n *\n * //=collection\n */\nfunction geometryCollection(geometries, properties, options) {\n if (!geometries) throw new Error('geometries is required');\n if (!Array.isArray(geometries)) throw new Error('geometries must be an Array');\n\n return feature({\n type: 'GeometryCollection',\n geometries: geometries\n }, properties, options);\n}\n\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nfunction round(num, precision) {\n if (num === undefined || num === null || isNaN(num)) throw new Error('num is required');\n if (precision && !(precision >= 0)) throw new Error('precision must be a positive number');\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} distance\n */\nfunction radiansToLength(radians, units) {\n if (radians === undefined || radians === null) throw new Error('radians is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return radians * factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} radians\n */\nfunction lengthToRadians(distance, units) {\n if (distance === undefined || distance === null) throw new Error('distance is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return distance / factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nfunction lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nfunction bearingToAzimuth(bearing) {\n if (bearing === null || bearing === undefined) throw new Error('bearing is required');\n\n var angle = bearing % 360;\n if (angle < 0) angle += 360;\n return angle;\n}\n\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nfunction radiansToDegrees(radians) {\n if (radians === null || radians === undefined) throw new Error('radians is required');\n\n var degrees = radians % (2 * Math.PI);\n return degrees * 180 / Math.PI;\n}\n\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nfunction degreesToRadians(degrees) {\n if (degrees === null || degrees === undefined) throw new Error('degrees is required');\n\n var radians = degrees % 360;\n return radians * Math.PI / 180;\n}\n\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {string} originalUnit of the length\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted length\n */\nfunction convertLength(length, originalUnit, finalUnit) {\n if (length === null || length === undefined) throw new Error('length is required');\n if (!(length >= 0)) throw new Error('length must be a positive number');\n\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit || 'kilometers');\n}\n\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches\n * @param {number} area to be converted\n * @param {string} [originalUnit='meters'] of the distance\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted distance\n */\nfunction convertArea(area, originalUnit, finalUnit) {\n if (area === null || area === undefined) throw new Error('area is required');\n if (!(area >= 0)) throw new Error('area must be a positive number');\n\n var startFactor = areaFactors[originalUnit || 'meters'];\n if (!startFactor) throw new Error('invalid original units');\n\n var finalFactor = areaFactors[finalUnit || 'kilometers'];\n if (!finalFactor) throw new Error('invalid final units');\n\n return (area / startFactor) * finalFactor;\n}\n\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nfunction isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nfunction isObject(input) {\n return (!!input) && (input.constructor === Object);\n}\n\n/**\n * Validate BBox\n *\n * @private\n * @param {Array<number>} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nfunction validateBBox(bbox) {\n if (!bbox) throw new Error('bbox is required');\n if (!Array.isArray(bbox)) throw new Error('bbox must be an Array');\n if (bbox.length !== 4 && bbox.length !== 6) throw new Error('bbox must be an Array of 4 or 6 numbers');\n bbox.forEach(function (num) {\n if (!isNumber(num)) throw new Error('bbox must only contain numbers');\n });\n}\n\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nfunction validateId(id) {\n if (!id) throw new Error('id is required');\n if (['string', 'number'].indexOf(typeof id) === -1) throw new Error('id must be a number or a string');\n}\n\n// Deprecated methods\nfunction radians2degrees() {\n throw new Error('method has been renamed to `radiansToDegrees`');\n}\n\nfunction degrees2radians() {\n throw new Error('method has been renamed to `degreesToRadians`');\n}\n\nfunction distanceToDegrees() {\n throw new Error('method has been renamed to `lengthToDegrees`');\n}\n\nfunction distanceToRadians() {\n throw new Error('method has been renamed to `lengthToRadians`');\n}\n\nfunction radiansToDistance() {\n throw new Error('method has been renamed to `radiansToLength`');\n}\n\nfunction bearingToAngle() {\n throw new Error('method has been renamed to `bearingToAzimuth`');\n}\n\nfunction convertDistance() {\n throw new Error('method has been renamed to `convertLength`');\n}\n\nexport { earthRadius, factors, unitsFactors, areaFactors, feature, geometry, point, points, polygon, polygons, lineString, lineStrings, featureCollection, multiLineString, multiPoint, multiPolygon, geometryCollection, round, radiansToLength, lengthToRadians, lengthToDegrees, bearingToAzimuth, radiansToDegrees, degreesToRadians, convertLength, convertArea, isNumber, isObject, validateBBox, validateId, radians2degrees, degrees2radians, distanceToDegrees, distanceToRadians, radiansToDistance, bearingToAngle, convertDistance };\n","import { isNumber } from '@turf/helpers';\n\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers\n * @returns {Array<number>} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nfunction getCoord(coord) {\n if (!coord) throw new Error('coord is required');\n if (coord.type === 'Feature' && coord.geometry !== null && coord.geometry.type === 'Point') return coord.geometry.coordinates;\n if (coord.type === 'Point') return coord.coordinates;\n if (Array.isArray(coord) && coord.length >= 2 && coord[0].length === undefined && coord[1].length === undefined) return coord;\n\n throw new Error('coord must be GeoJSON Point or an Array of numbers');\n}\n\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array<any>|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array<any>} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nfunction getCoords(coords) {\n if (!coords) throw new Error('coords is required');\n\n // Feature\n if (coords.type === 'Feature' && coords.geometry !== null) return coords.geometry.coordinates;\n\n // Geometry\n if (coords.coordinates) return coords.coordinates;\n\n // Array of numbers\n if (Array.isArray(coords)) return coords;\n\n throw new Error('coords must be GeoJSON Feature, Geometry Object or an Array');\n}\n\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array<any>} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nfunction containsNumber(coordinates) {\n if (coordinates.length > 1 && isNumber(coordinates[0]) && isNumber(coordinates[1])) {\n return true;\n }\n\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error('coordinates must only contain numbers');\n}\n\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction geojsonType(value, type, name) {\n if (!type || !name) throw new Error('type and name required');\n\n if (!value || value.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + value.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nfunction featureOf(feature, type, name) {\n if (!feature) throw new Error('No feature passed');\n if (!name) throw new Error('.featureOf() requires a name');\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction collectionOf(featureCollection, type, name) {\n if (!featureCollection) throw new Error('No featureCollection passed');\n if (!name) throw new Error('.collectionOf() requires a name');\n if (!featureCollection || featureCollection.type !== 'FeatureCollection') {\n throw new Error('Invalid input to ' + name + ', FeatureCollection required');\n }\n for (var i = 0; i < featureCollection.features.length; i++) {\n var feature = featureCollection.features[i];\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n }\n}\n\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nfunction getGeom(geojson) {\n if (!geojson) throw new Error('geojson is required');\n if (geojson.geometry !== undefined) return geojson.geometry;\n if (geojson.coordinates || geojson.geometries) return geojson;\n throw new Error('geojson must be a valid Feature or Geometry Object');\n}\n\n/**\n * Get Geometry Type from Feature or Geometry Object\n *\n * @throws {Error} **DEPRECATED** in v5.0.0 in favor of getType\n */\nfunction getGeomType() {\n throw new Error('invariant.getGeomType has been deprecated in v5.0 in favor of invariant.getType');\n}\n\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nfunction getType(geojson, name) {\n if (!geojson) throw new Error((name || 'geojson') + ' is required');\n // GeoJSON Feature & GeometryCollection\n if (geojson.geometry && geojson.geometry.type) return geojson.geometry.type;\n // GeoJSON Geometry & FeatureCollection\n if (geojson.type) return geojson.type;\n throw new Error((name || 'geojson') + ' is invalid');\n}\n\nexport { getCoord, getCoords, containsNumber, geojsonType, featureOf, collectionOf, getGeom, getGeomType, getType };\n","import { getCoord } from '@turf/invariant';\nimport { degreesToRadians, isObject, radiansToDegrees } from '@turf/helpers';\n\n// https://en.wikipedia.org/wiki/Rhumb_line\n/**\n * Takes two {@link Point|points} and finds the bearing angle between them along a Rhumb line\n * i.e. the angle measured in degrees start the north line (0 degrees)\n *\n * @name rhumbBearing\n * @param {Coord} start starting Point\n * @param {Coord} end ending Point\n * @param {Object} [options] Optional parameters\n * @param {boolean} [options.final=false] calculates the final bearing if true\n * @returns {number} bearing from north in decimal degrees, between -180 and 180 degrees (positive clockwise)\n * @example\n * var point1 = turf.point([-75.343, 39.984], {\"marker-color\": \"#F00\"});\n * var point2 = turf.point([-75.534, 39.123], {\"marker-color\": \"#00F\"});\n *\n * var bearing = turf.rhumbBearing(point1, point2);\n *\n * //addToMap\n * var addToMap = [point1, point2];\n * point1.properties.bearing = bearing;\n * point2.properties.bearing = bearing;\n */\nfunction rhumbBearing(start, end, options) {\n // Optional parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var final = options.final;\n\n // validation\n if (!start) throw new Error('start point is required');\n if (!end) throw new Error('end point is required');\n\n var bear360;\n\n if (final) bear360 = calculateRhumbBearing(getCoord(end), getCoord(start));\n else bear360 = calculateRhumbBearing(getCoord(start), getCoord(end));\n\n var bear180 = (bear360 > 180) ? -(360 - bear360) : bear360;\n\n return bear180;\n}\n\n/**\n * Returns the bearing from ‘this’ point to destination point along a rhumb line.\n * Adapted from Geodesy: https://github.com/chrisveness/geodesy/blob/master/latlon-spherical.js\n *\n * @private\n * @param {Array<number>} from - origin point.\n * @param {Array<number>} to - destination point.\n * @returns {number} Bearing in degrees from north.\n * @example\n * var p1 = new LatLon(51.127, 1.338);\n * var p2 = new LatLon(50.964, 1.853);\n * var d = p1.rhumbBearingTo(p2); // 116.7 m\n */\nfunction calculateRhumbBearing(from, to) {\n // φ => phi\n // Δλ => deltaLambda\n // Δψ => deltaPsi\n // θ => theta\n var phi1 = degreesToRadians(from[1]);\n var phi2 = degreesToRadians(to[1]);\n var deltaLambda = degreesToRadians((to[0] - from[0]));\n // if deltaLambdaon over 180° take shorter rhumb line across the anti-meridian:\n if (deltaLambda > Math.PI) deltaLambda -= 2 * Math.PI;\n if (deltaLambda < -Math.PI) deltaLambda += 2 * Math.PI;\n\n var deltaPsi = Math.log(Math.tan(phi2 / 2 + Math.PI / 4) / Math.tan(phi1 / 2 + Math.PI / 4));\n\n var theta = Math.atan2(deltaLambda, deltaPsi);\n\n return (radiansToDegrees(theta) + 360) % 360;\n}\n\nexport default rhumbBearing;\n","/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n */\nvar earthRadius = 6371008.8;\n\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n */\nvar factors = {\n meters: earthRadius,\n metres: earthRadius,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n miles: earthRadius / 1609.344,\n nauticalmiles: earthRadius / 1852,\n inches: earthRadius * 39.370,\n yards: earthRadius / 1.0936,\n feet: earthRadius * 3.28084,\n radians: 1,\n degrees: earthRadius / 111325,\n};\n\n/**\n * Units of measurement factors based on 1 meter.\n */\nvar unitsFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000,\n millimetres: 1000,\n centimeters: 100,\n centimetres: 100,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n miles: 1 / 1609.344,\n nauticalmiles: 1 / 1852,\n inches: 39.370,\n yards: 1 / 1.0936,\n feet: 3.28084,\n radians: 1 / earthRadius,\n degrees: 1 / 111325,\n};\n\n/**\n * Area of measurement factors based on 1 square meter.\n */\nvar areaFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000000,\n millimetres: 1000000,\n centimeters: 10000,\n centimetres: 10000,\n kilometers: 0.000001,\n kilometres: 0.000001,\n acres: 0.000247105,\n miles: 3.86e-7,\n yards: 1.195990046,\n feet: 10.763910417,\n inches: 1550.003100006\n};\n\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nfunction feature(geometry, properties, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (geometry === undefined) throw new Error('geometry is required');\n if (properties && properties.constructor !== Object) throw new Error('properties must be an Object');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var feat = {type: 'Feature'};\n if (id) feat.id = id;\n if (bbox) feat.bbox = bbox;\n feat.properties = properties || {};\n feat.geometry = geometry;\n return feat;\n}\n\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array<number>} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = 'Point';\n * var coordinates = [110, 50];\n *\n * var geometry = turf.geometry(type, coordinates);\n *\n * //=geometry\n */\nfunction geometry(type, coordinates, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n\n // Validation\n if (!type) throw new Error('type is required');\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (bbox) validateBBox(bbox);\n\n // Main\n var geom;\n switch (type) {\n case 'Point': geom = point(coordinates).geometry; break;\n case 'LineString': geom = lineString(coordinates).geometry; break;\n case 'Polygon': geom = polygon(coordinates).geometry; break;\n case 'MultiPoint': geom = multiPoint(coordinates).geometry; break;\n case 'MultiLineString': geom = multiLineString(coordinates).geometry; break;\n case 'MultiPolygon': geom = multiPolygon(coordinates).geometry; break;\n default: throw new Error(type + ' is invalid');\n }\n if (bbox) geom.bbox = bbox;\n return geom;\n}\n\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nfunction point(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long');\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'Point',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array<Array<number>>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Point>} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nfunction points(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon>} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nfunction polygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n for (var i = 0; i < coordinates.length; i++) {\n var ring = coordinates[i];\n if (ring.length < 4) {\n throw new Error('Each LinearRing of a Polygon must have 4 or more Positions.');\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (i === 0 && j === 0 && !isNumber(ring[0][0]) || !isNumber(ring[0][1])) throw new Error('coordinates must contain numbers');\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error('First and last Position are not equivalent.');\n }\n }\n }\n\n return feature({\n type: 'Polygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nfunction polygons(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString>} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nfunction lineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions');\n // Check if first point of LineString contains two numbers\n if (!isNumber(coordinates[0][1]) || !isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'LineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array<Array<number>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString>} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nfunction lineStrings(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nfunction featureCollection(features, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (!features) throw new Error('No features passed');\n if (!Array.isArray(features)) throw new Error('features must be an Array');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var fc = {type: 'FeatureCollection'};\n if (id) fc.id = id;\n if (bbox) fc.bbox = bbox;\n fc.features = features;\n return fc;\n}\n\n/**\n * Creates a {@link Feature<MultiLineString>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString>} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nfunction multiLineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiLineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPoint>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint>} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nfunction multiPoint(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPoint',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPolygon>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon>} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nfunction multiPolygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPolygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<GeometryCollection>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array<Geometry>} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = {\n * \"type\": \"Point\",\n * \"coordinates\": [100, 0]\n * };\n * var line = {\n * \"type\": \"LineString\",\n * \"coordinates\": [ [101, 0], [102, 1] ]\n * };\n * var collection = turf.geometryCollection([pt, line]);\n *\n * //=collection\n */\nfunction geometryCollection(geometries, properties, options) {\n if (!geometries) throw new Error('geometries is required');\n if (!Array.isArray(geometries)) throw new Error('geometries must be an Array');\n\n return feature({\n type: 'GeometryCollection',\n geometries: geometries\n }, properties, options);\n}\n\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nfunction round(num, precision) {\n if (num === undefined || num === null || isNaN(num)) throw new Error('num is required');\n if (precision && !(precision >= 0)) throw new Error('precision must be a positive number');\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} distance\n */\nfunction radiansToLength(radians, units) {\n if (radians === undefined || radians === null) throw new Error('radians is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return radians * factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} radians\n */\nfunction lengthToRadians(distance, units) {\n if (distance === undefined || distance === null) throw new Error('distance is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return distance / factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nfunction lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nfunction bearingToAzimuth(bearing) {\n if (bearing === null || bearing === undefined) throw new Error('bearing is required');\n\n var angle = bearing % 360;\n if (angle < 0) angle += 360;\n return angle;\n}\n\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nfunction radiansToDegrees(radians) {\n if (radians === null || radians === undefined) throw new Error('radians is required');\n\n var degrees = radians % (2 * Math.PI);\n return degrees * 180 / Math.PI;\n}\n\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nfunction degreesToRadians(degrees) {\n if (degrees === null || degrees === undefined) throw new Error('degrees is required');\n\n var radians = degrees % 360;\n return radians * Math.PI / 180;\n}\n\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {string} originalUnit of the length\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted length\n */\nfunction convertLength(length, originalUnit, finalUnit) {\n if (length === null || length === undefined) throw new Error('length is required');\n if (!(length >= 0)) throw new Error('length must be a positive number');\n\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit || 'kilometers');\n}\n\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches\n * @param {number} area to be converted\n * @param {string} [originalUnit='meters'] of the distance\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted distance\n */\nfunction convertArea(area, originalUnit, finalUnit) {\n if (area === null || area === undefined) throw new Error('area is required');\n if (!(area >= 0)) throw new Error('area must be a positive number');\n\n var startFactor = areaFactors[originalUnit || 'meters'];\n if (!startFactor) throw new Error('invalid original units');\n\n var finalFactor = areaFactors[finalUnit || 'kilometers'];\n if (!finalFactor) throw new Error('invalid final units');\n\n return (area / startFactor) * finalFactor;\n}\n\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nfunction isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nfunction isObject(input) {\n return (!!input) && (input.constructor === Object);\n}\n\n/**\n * Validate BBox\n *\n * @private\n * @param {Array<number>} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nfunction validateBBox(bbox) {\n if (!bbox) throw new Error('bbox is required');\n if (!Array.isArray(bbox)) throw new Error('bbox must be an Array');\n if (bbox.length !== 4 && bbox.length !== 6) throw new Error('bbox must be an Array of 4 or 6 numbers');\n bbox.forEach(function (num) {\n if (!isNumber(num)) throw new Error('bbox must only contain numbers');\n });\n}\n\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nfunction validateId(id) {\n if (!id) throw new Error('id is required');\n if (['string', 'number'].indexOf(typeof id) === -1) throw new Error('id must be a number or a string');\n}\n\n// Deprecated methods\nfunction radians2degrees() {\n throw new Error('method has been renamed to `radiansToDegrees`');\n}\n\nfunction degrees2radians() {\n throw new Error('method has been renamed to `degreesToRadians`');\n}\n\nfunction distanceToDegrees() {\n throw new Error('method has been renamed to `lengthToDegrees`');\n}\n\nfunction distanceToRadians() {\n throw new Error('method has been renamed to `lengthToRadians`');\n}\n\nfunction radiansToDistance() {\n throw new Error('method has been renamed to `radiansToLength`');\n}\n\nfunction bearingToAngle() {\n throw new Error('method has been renamed to `bearingToAzimuth`');\n}\n\nfunction convertDistance() {\n throw new Error('method has been renamed to `convertLength`');\n}\n\nexport { earthRadius, factors, unitsFactors, areaFactors, feature, geometry, point, points, polygon, polygons, lineString, lineStrings, featureCollection, multiLineString, multiPoint, multiPolygon, geometryCollection, round, radiansToLength, lengthToRadians, lengthToDegrees, bearingToAzimuth, radiansToDegrees, degreesToRadians, convertLength, convertArea, isNumber, isObject, validateBBox, validateId, radians2degrees, degrees2radians, distanceToDegrees, distanceToRadians, radiansToDistance, bearingToAngle, convertDistance };\n","import { isNumber } from '@turf/helpers';\n\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers\n * @returns {Array<number>} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nfunction getCoord(coord) {\n if (!coord) throw new Error('coord is required');\n if (coord.type === 'Feature' && coord.geometry !== null && coord.geometry.type === 'Point') return coord.geometry.coordinates;\n if (coord.type === 'Point') return coord.coordinates;\n if (Array.isArray(coord) && coord.length >= 2 && coord[0].length === undefined && coord[1].length === undefined) return coord;\n\n throw new Error('coord must be GeoJSON Point or an Array of numbers');\n}\n\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array<any>|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array<any>} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nfunction getCoords(coords) {\n if (!coords) throw new Error('coords is required');\n\n // Feature\n if (coords.type === 'Feature' && coords.geometry !== null) return coords.geometry.coordinates;\n\n // Geometry\n if (coords.coordinates) return coords.coordinates;\n\n // Array of numbers\n if (Array.isArray(coords)) return coords;\n\n throw new Error('coords must be GeoJSON Feature, Geometry Object or an Array');\n}\n\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array<any>} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nfunction containsNumber(coordinates) {\n if (coordinates.length > 1 && isNumber(coordinates[0]) && isNumber(coordinates[1])) {\n return true;\n }\n\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error('coordinates must only contain numbers');\n}\n\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction geojsonType(value, type, name) {\n if (!type || !name) throw new Error('type and name required');\n\n if (!value || value.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + value.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nfunction featureOf(feature, type, name) {\n if (!feature) throw new Error('No feature passed');\n if (!name) throw new Error('.featureOf() requires a name');\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction collectionOf(featureCollection, type, name) {\n if (!featureCollection) throw new Error('No featureCollection passed');\n if (!name) throw new Error('.collectionOf() requires a name');\n if (!featureCollection || featureCollection.type !== 'FeatureCollection') {\n throw new Error('Invalid input to ' + name + ', FeatureCollection required');\n }\n for (var i = 0; i < featureCollection.features.length; i++) {\n var feature = featureCollection.features[i];\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n }\n}\n\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nfunction getGeom(geojson) {\n if (!geojson) throw new Error('geojson is required');\n if (geojson.geometry !== undefined) return geojson.geometry;\n if (geojson.coordinates || geojson.geometries) return geojson;\n throw new Error('geojson must be a valid Feature or Geometry Object');\n}\n\n/**\n * Get Geometry Type from Feature or Geometry Object\n *\n * @throws {Error} **DEPRECATED** in v5.0.0 in favor of getType\n */\nfunction getGeomType() {\n throw new Error('invariant.getGeomType has been deprecated in v5.0 in favor of invariant.getType');\n}\n\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nfunction getType(geojson, name) {\n if (!geojson) throw new Error((name || 'geojson') + ' is required');\n // GeoJSON Feature & GeometryCollection\n if (geojson.geometry && geojson.geometry.type) return geojson.geometry.type;\n // GeoJSON Geometry & FeatureCollection\n if (geojson.type) return geojson.type;\n throw new Error((name || 'geojson') + ' is invalid');\n}\n\nexport { getCoord, getCoords, containsNumber, geojsonType, featureOf, collectionOf, getGeom, getGeomType, getType };\n","import { convertLength, earthRadius, isObject } from '@turf/helpers';\nimport { getCoord } from '@turf/invariant';\n\n// https://en.wikipedia.org/wiki/Rhumb_line\n/**\n * Calculates the distance along a rhumb line between two {@link Point|points} in degrees, radians,\n * miles, or kilometers.\n *\n * @name rhumbDistance\n * @param {Coord} from origin point\n * @param {Coord} to destination point\n * @param {Object} [options] Optional parameters\n * @param {string} [options.units=\"kilometers\"] can be degrees, radians, miles, or kilometers\n * @returns {number} distance between the two points\n * @example\n * var from = turf.point([-75.343, 39.984]);\n * var to = turf.point([-75.534, 39.123]);\n * var options = {units: 'miles'};\n *\n * var distance = turf.rhumbDistance(from, to, options);\n *\n * //addToMap\n * var addToMap = [from, to];\n * from.properties.distance = distance;\n * to.properties.distance = distance;\n */\nfunction rhumbDistance(from, to, options) {\n // Optional parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var units = options.units;\n\n // validation\n if (!from) throw new Error('from point is required');\n if (!to) throw new Error('to point is required');\n\n var origin = getCoord(from);\n var destination = getCoord(to);\n\n // compensate the crossing of the 180th meridian (https://macwright.org/2016/09/26/the-180th-meridian.html)\n // solution from https://github.com/mapbox/mapbox-gl-js/issues/3250#issuecomment-294887678\n destination[0] += (destination[0] - origin[0] > 180) ? -360 : (origin[0] - destination[0] > 180) ? 360 : 0;\n var distanceInMeters = calculateRhumbDistance(origin, destination);\n var distance = convertLength(distanceInMeters, 'meters', units);\n return distance;\n}\n\n/**\n * Returns the distance travelling from ‘this’ point to destination point along a rhumb line.\n * Adapted from Geodesy: https://github.com/chrisveness/geodesy/blob/master/latlon-spherical.js\n *\n * @private\n * @param {Array<number>} origin point.\n * @param {Array<number>} destination point.\n * @param {number} [radius=6371e3] - (Mean) radius of earth (defaults to radius in metres).\n * @returns {number} Distance in km between this point and destination point (same units as radius).\n *\n * @example\n * var p1 = new LatLon(51.127, 1.338);\n * var p2 = new LatLon(50.964, 1.853);\n * var d = p1.distanceTo(p2); // 40.31 km\n */\nfunction calculateRhumbDistance(origin, destination, radius) {\n // φ => phi\n // λ => lambda\n // ψ => psi\n // Δ => Delta\n // δ => delta\n // θ => theta\n\n radius = (radius === undefined) ? earthRadius : Number(radius);\n // see www.edwilliams.org/avform.htm#Rhumb\n\n var R = radius;\n var phi1 = origin[1] * Math.PI / 180;\n var phi2 = destination[1] * Math.PI / 180;\n var DeltaPhi = phi2 - phi1;\n var DeltaLambda = Math.abs(destination[0] - origin[0]) * Math.PI / 180;\n // if dLon over 180° take shorter rhumb line across the anti-meridian:\n if (DeltaLambda > Math.PI) DeltaLambda -= 2 * Math.PI;\n\n // on Mercator projection, longitude distances shrink by latitude; q is the 'stretch factor'\n // q becomes ill-conditioned along E-W line (0/0); use empirical tolerance to avoid it\n var DeltaPsi = Math.log(Math.tan(phi2 / 2 + Math.PI / 4) / Math.tan(phi1 / 2 + Math.PI / 4));\n var q = Math.abs(DeltaPsi) > 10e-12 ? DeltaPhi / DeltaPsi : Math.cos(phi1);\n\n // distance is pythagoras on 'stretched' Mercator projection\n var delta = Math.sqrt(DeltaPhi * DeltaPhi + q * q * DeltaLambda * DeltaLambda); // angular distance in radians\n var dist = delta * R;\n\n return dist;\n}\n\nexport default rhumbDistance;\n","/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n */\nvar earthRadius = 6371008.8;\n\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n */\nvar factors = {\n meters: earthRadius,\n metres: earthRadius,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n miles: earthRadius / 1609.344,\n nauticalmiles: earthRadius / 1852,\n inches: earthRadius * 39.370,\n yards: earthRadius / 1.0936,\n feet: earthRadius * 3.28084,\n radians: 1,\n degrees: earthRadius / 111325,\n};\n\n/**\n * Units of measurement factors based on 1 meter.\n */\nvar unitsFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000,\n millimetres: 1000,\n centimeters: 100,\n centimetres: 100,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n miles: 1 / 1609.344,\n nauticalmiles: 1 / 1852,\n inches: 39.370,\n yards: 1 / 1.0936,\n feet: 3.28084,\n radians: 1 / earthRadius,\n degrees: 1 / 111325,\n};\n\n/**\n * Area of measurement factors based on 1 square meter.\n */\nvar areaFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000000,\n millimetres: 1000000,\n centimeters: 10000,\n centimetres: 10000,\n kilometers: 0.000001,\n kilometres: 0.000001,\n acres: 0.000247105,\n miles: 3.86e-7,\n yards: 1.195990046,\n feet: 10.763910417,\n inches: 1550.003100006\n};\n\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nfunction feature(geometry, properties, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (geometry === undefined) throw new Error('geometry is required');\n if (properties && properties.constructor !== Object) throw new Error('properties must be an Object');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var feat = {type: 'Feature'};\n if (id) feat.id = id;\n if (bbox) feat.bbox = bbox;\n feat.properties = properties || {};\n feat.geometry = geometry;\n return feat;\n}\n\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array<number>} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = 'Point';\n * var coordinates = [110, 50];\n *\n * var geometry = turf.geometry(type, coordinates);\n *\n * //=geometry\n */\nfunction geometry(type, coordinates, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n\n // Validation\n if (!type) throw new Error('type is required');\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (bbox) validateBBox(bbox);\n\n // Main\n var geom;\n switch (type) {\n case 'Point': geom = point(coordinates).geometry; break;\n case 'LineString': geom = lineString(coordinates).geometry; break;\n case 'Polygon': geom = polygon(coordinates).geometry; break;\n case 'MultiPoint': geom = multiPoint(coordinates).geometry; break;\n case 'MultiLineString': geom = multiLineString(coordinates).geometry; break;\n case 'MultiPolygon': geom = multiPolygon(coordinates).geometry; break;\n default: throw new Error(type + ' is invalid');\n }\n if (bbox) geom.bbox = bbox;\n return geom;\n}\n\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nfunction point(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long');\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'Point',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array<Array<number>>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Point>} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nfunction points(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon>} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nfunction polygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n for (var i = 0; i < coordinates.length; i++) {\n var ring = coordinates[i];\n if (ring.length < 4) {\n throw new Error('Each LinearRing of a Polygon must have 4 or more Positions.');\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (i === 0 && j === 0 && !isNumber(ring[0][0]) || !isNumber(ring[0][1])) throw new Error('coordinates must contain numbers');\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error('First and last Position are not equivalent.');\n }\n }\n }\n\n return feature({\n type: 'Polygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nfunction polygons(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString>} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nfunction lineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions');\n // Check if first point of LineString contains two numbers\n if (!isNumber(coordinates[0][1]) || !isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'LineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array<Array<number>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString>} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nfunction lineStrings(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nfunction featureCollection(features, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (!features) throw new Error('No features passed');\n if (!Array.isArray(features)) throw new Error('features must be an Array');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var fc = {type: 'FeatureCollection'};\n if (id) fc.id = id;\n if (bbox) fc.bbox = bbox;\n fc.features = features;\n return fc;\n}\n\n/**\n * Creates a {@link Feature<MultiLineString>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString>} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nfunction multiLineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiLineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPoint>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint>} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nfunction multiPoint(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPoint',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPolygon>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon>} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nfunction multiPolygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPolygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<GeometryCollection>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array<Geometry>} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = {\n * \"type\": \"Point\",\n * \"coordinates\": [100, 0]\n * };\n * var line = {\n * \"type\": \"LineString\",\n * \"coordinates\": [ [101, 0], [102, 1] ]\n * };\n * var collection = turf.geometryCollection([pt, line]);\n *\n * //=collection\n */\nfunction geometryCollection(geometries, properties, options) {\n if (!geometries) throw new Error('geometries is required');\n if (!Array.isArray(geometries)) throw new Error('geometries must be an Array');\n\n return feature({\n type: 'GeometryCollection',\n geometries: geometries\n }, properties, options);\n}\n\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nfunction round(num, precision) {\n if (num === undefined || num === null || isNaN(num)) throw new Error('num is required');\n if (precision && !(precision >= 0)) throw new Error('precision must be a positive number');\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} distance\n */\nfunction radiansToLength(radians, units) {\n if (radians === undefined || radians === null) throw new Error('radians is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return radians * factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} radians\n */\nfunction lengthToRadians(distance, units) {\n if (distance === undefined || distance === null) throw new Error('distance is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return distance / factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nfunction lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nfunction bearingToAzimuth(bearing) {\n if (bearing === null || bearing === undefined) throw new Error('bearing is required');\n\n var angle = bearing % 360;\n if (angle < 0) angle += 360;\n return angle;\n}\n\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nfunction radiansToDegrees(radians) {\n if (radians === null || radians === undefined) throw new Error('radians is required');\n\n var degrees = radians % (2 * Math.PI);\n return degrees * 180 / Math.PI;\n}\n\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nfunction degreesToRadians(degrees) {\n if (degrees === null || degrees === undefined) throw new Error('degrees is required');\n\n var radians = degrees % 360;\n return radians * Math.PI / 180;\n}\n\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {string} originalUnit of the length\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted length\n */\nfunction convertLength(length, originalUnit, finalUnit) {\n if (length === null || length === undefined) throw new Error('length is required');\n if (!(length >= 0)) throw new Error('length must be a positive number');\n\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit || 'kilometers');\n}\n\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches\n * @param {number} area to be converted\n * @param {string} [originalUnit='meters'] of the distance\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted distance\n */\nfunction convertArea(area, originalUnit, finalUnit) {\n if (area === null || area === undefined) throw new Error('area is required');\n if (!(area >= 0)) throw new Error('area must be a positive number');\n\n var startFactor = areaFactors[originalUnit || 'meters'];\n if (!startFactor) throw new Error('invalid original units');\n\n var finalFactor = areaFactors[finalUnit || 'kilometers'];\n if (!finalFactor) throw new Error('invalid final units');\n\n return (area / startFactor) * finalFactor;\n}\n\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nfunction isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nfunction isObject(input) {\n return (!!input) && (input.constructor === Object);\n}\n\n/**\n * Validate BBox\n *\n * @private\n * @param {Array<number>} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nfunction validateBBox(bbox) {\n if (!bbox) throw new Error('bbox is required');\n if (!Array.isArray(bbox)) throw new Error('bbox must be an Array');\n if (bbox.length !== 4 && bbox.length !== 6) throw new Error('bbox must be an Array of 4 or 6 numbers');\n bbox.forEach(function (num) {\n if (!isNumber(num)) throw new Error('bbox must only contain numbers');\n });\n}\n\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nfunction validateId(id) {\n if (!id) throw new Error('id is required');\n if (['string', 'number'].indexOf(typeof id) === -1) throw new Error('id must be a number or a string');\n}\n\n// Deprecated methods\nfunction radians2degrees() {\n throw new Error('method has been renamed to `radiansToDegrees`');\n}\n\nfunction degrees2radians() {\n throw new Error('method has been renamed to `degreesToRadians`');\n}\n\nfunction distanceToDegrees() {\n throw new Error('method has been renamed to `lengthToDegrees`');\n}\n\nfunction distanceToRadians() {\n throw new Error('method has been renamed to `lengthToRadians`');\n}\n\nfunction radiansToDistance() {\n throw new Error('method has been renamed to `radiansToLength`');\n}\n\nfunction bearingToAngle() {\n throw new Error('method has been renamed to `bearingToAzimuth`');\n}\n\nfunction convertDistance() {\n throw new Error('method has been renamed to `convertLength`');\n}\n\nexport { earthRadius, factors, unitsFactors, areaFactors, feature, geometry, point, points, polygon, polygons, lineString, lineStrings, featureCollection, multiLineString, multiPoint, multiPolygon, geometryCollection, round, radiansToLength, lengthToRadians, lengthToDegrees, bearingToAzimuth, radiansToDegrees, degreesToRadians, convertLength, convertArea, isNumber, isObject, validateBBox, validateId, radians2degrees, degrees2radians, distanceToDegrees, distanceToRadians, radiansToDistance, bearingToAngle, convertDistance };\n","import { isNumber } from '@turf/helpers';\n\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers\n * @returns {Array<number>} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nfunction getCoord(coord) {\n if (!coord) throw new Error('coord is required');\n if (coord.type === 'Feature' && coord.geometry !== null && coord.geometry.type === 'Point') return coord.geometry.coordinates;\n if (coord.type === 'Point') return coord.coordinates;\n if (Array.isArray(coord) && coord.length >= 2 && coord[0].length === undefined && coord[1].length === undefined) return coord;\n\n throw new Error('coord must be GeoJSON Point or an Array of numbers');\n}\n\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array<any>|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array<any>} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nfunction getCoords(coords) {\n if (!coords) throw new Error('coords is required');\n\n // Feature\n if (coords.type === 'Feature' && coords.geometry !== null) return coords.geometry.coordinates;\n\n // Geometry\n if (coords.coordinates) return coords.coordinates;\n\n // Array of numbers\n if (Array.isArray(coords)) return coords;\n\n throw new Error('coords must be GeoJSON Feature, Geometry Object or an Array');\n}\n\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array<any>} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nfunction containsNumber(coordinates) {\n if (coordinates.length > 1 && isNumber(coordinates[0]) && isNumber(coordinates[1])) {\n return true;\n }\n\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error('coordinates must only contain numbers');\n}\n\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction geojsonType(value, type, name) {\n if (!type || !name) throw new Error('type and name required');\n\n if (!value || value.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + value.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nfunction featureOf(feature, type, name) {\n if (!feature) throw new Error('No feature passed');\n if (!name) throw new Error('.featureOf() requires a name');\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction collectionOf(featureCollection, type, name) {\n if (!featureCollection) throw new Error('No featureCollection passed');\n if (!name) throw new Error('.collectionOf() requires a name');\n if (!featureCollection || featureCollection.type !== 'FeatureCollection') {\n throw new Error('Invalid input to ' + name + ', FeatureCollection required');\n }\n for (var i = 0; i < featureCollection.features.length; i++) {\n var feature = featureCollection.features[i];\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n }\n}\n\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nfunction getGeom(geojson) {\n if (!geojson) throw new Error('geojson is required');\n if (geojson.geometry !== undefined) return geojson.geometry;\n if (geojson.coordinates || geojson.geometries) return geojson;\n throw new Error('geojson must be a valid Feature or Geometry Object');\n}\n\n/**\n * Get Geometry Type from Feature or Geometry Object\n *\n * @throws {Error} **DEPRECATED** in v5.0.0 in favor of getType\n */\nfunction getGeomType() {\n throw new Error('invariant.getGeomType has been deprecated in v5.0 in favor of invariant.getType');\n}\n\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nfunction getType(geojson, name) {\n if (!geojson) throw new Error((name || 'geojson') + ' is required');\n // GeoJSON Feature & GeometryCollection\n if (geojson.geometry && geojson.geometry.type) return geojson.geometry.type;\n // GeoJSON Geometry & FeatureCollection\n if (geojson.type) return geojson.type;\n throw new Error((name || 'geojson') + ' is invalid');\n}\n\nexport { getCoord, getCoords, containsNumber, geojsonType, featureOf, collectionOf, getGeom, getGeomType, getType };\n","import { convertLength, degreesToRadians, earthRadius, isObject, point } from '@turf/helpers';\nimport { getCoord } from '@turf/invariant';\n\n// https://en.wikipedia.org/wiki/Rhumb_line\n/**\n * Returns the destination {@link Point} having travelled the given distance along a Rhumb line from the\n * origin Point with the (varant) given bearing.\n *\n * @name rhumbDestination\n * @param {Coord} origin starting point\n * @param {number} distance distance from the starting point\n * @param {number} bearing varant bearing angle ranging from -180 to 180 degrees from north\n * @param {Object} [options={}] Optional parameters\n * @param {string} [options.units='kilometers'] can be degrees, radians, miles, or kilometers\n * @param {Object} [options.properties={}] translate properties to destination point\n * @returns {Feature<Point>} Destination point.\n * @example\n * var pt = turf.point([-75.343, 39.984], {\"marker-color\": \"F00\"});\n * var distance = 50;\n * var bearing = 90;\n * var options = {units: 'miles'};\n *\n * var destination = turf.rhumbDestination(pt, distance, bearing, options);\n *\n * //addToMap\n * var addToMap = [pt, destination]\n * destination.properties['marker-color'] = '#00F';\n */\nfunction rhumbDestination(origin, distance, bearing, options) {\n // Optional parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var units = options.units;\n var properties = options.properties;\n\n // validation\n if (!origin) throw new Error('origin is required');\n if (distance === undefined || distance === null) throw new Error('distance is required');\n if (bearing === undefined || bearing === null) throw new Error('bearing is required');\n if (!(distance >= 0)) throw new Error('distance must be greater than 0');\n\n var distanceInMeters = convertLength(distance, units, 'meters');\n var coords = getCoord(origin);\n var destination = calculateRhumbDestination(coords, distanceInMeters, bearing);\n\n // compensate the crossing of the 180th meridian (https://macwright.org/2016/09/26/the-180th-meridian.html)\n // solution from https://github.com/mapbox/mapbox-gl-js/issues/3250#issuecomment-294887678\n destination[0] += (destination[0] - coords[0] > 180) ? -360 : (coords[0] - destination[0] > 180) ? 360 : 0;\n return point(destination, properties);\n}\n\n/**\n * Returns the destination point having travelled along a rhumb line from origin point the given\n * distance on the given bearing.\n * Adapted from Geodesy: http://www.movable-type.co.uk/scripts/latlong.html#rhumblines\n *\n * @private\n * @param {Array<number>} origin - point\n * @param {number} distance - Distance travelled, in same units as earth radius (default: metres).\n * @param {number} bearing - Bearing in degrees from north.\n * @param {number} [radius=6371e3] - (Mean) radius of earth (defaults to radius in metres).\n * @returns {Array<number>} Destination point.\n */\nfunction calculateRhumbDestination(origin, distance, bearing, radius) {\n // φ => phi\n // λ => lambda\n // ψ => psi\n // Δ => Delta\n // δ => delta\n // θ => theta\n\n radius = (radius === undefined) ? earthRadius : Number(radius);\n\n var delta = distance / radius; // angular distance in radians\n var lambda1 = origin[0] * Math.PI / 180; // to radians, but without normalize to 𝜋\n var phi1 = degreesToRadians(origin[1]);\n var theta = degreesToRadians(bearing);\n\n var DeltaPhi = delta * Math.cos(theta);\n var phi2 = phi1 + DeltaPhi;\n\n // check for some daft bugger going past the pole, normalise latitude if so\n if (Math.abs(phi2) > Math.PI / 2) phi2 = phi2 > 0 ? Math.PI - phi2 : -Math.PI - phi2;\n\n var DeltaPsi = Math.log(Math.tan(phi2 / 2 + Math.PI / 4) / Math.tan(phi1 / 2 + Math.PI / 4));\n var q = Math.abs(DeltaPsi) > 10e-12 ? DeltaPhi / DeltaPsi : Math.cos(phi1); // E-W course becomes ill-conditioned with 0/0\n\n var DeltaLambda = delta * Math.sin(theta) / q;\n var lambda2 = lambda1 + DeltaLambda;\n\n return [((lambda2 * 180 / Math.PI) + 540) % 360 - 180, phi2 * 180 / Math.PI]; // normalise to −180..+180°\n}\n\nexport default rhumbDestination;\n","/**\n * Returns a cloned copy of the passed GeoJSON Object, including possible 'Foreign Members'.\n * ~3-5x faster than the common JSON.parse + JSON.stringify combo method.\n *\n * @name clone\n * @param {GeoJSON} geojson GeoJSON Object\n * @returns {GeoJSON} cloned GeoJSON Object\n * @example\n * var line = turf.lineString([[-74, 40], [-78, 42], [-82, 35]], {color: 'red'});\n *\n * var lineCloned = turf.clone(line);\n */\nfunction clone(geojson) {\n if (!geojson) throw new Error('geojson is required');\n\n switch (geojson.type) {\n case 'Feature':\n return cloneFeature(geojson);\n case 'FeatureCollection':\n return cloneFeatureCollection(geojson);\n case 'Point':\n case 'LineString':\n case 'Polygon':\n case 'MultiPoint':\n case 'MultiLineString':\n case 'MultiPolygon':\n case 'GeometryCollection':\n return cloneGeometry(geojson);\n default:\n throw new Error('unknown GeoJSON type');\n }\n}\n\n/**\n * Clone Feature\n *\n * @private\n * @param {Feature<any>} geojson GeoJSON Feature\n * @returns {Feature<any>} cloned Feature\n */\nfunction cloneFeature(geojson) {\n var cloned = {type: 'Feature'};\n // Preserve Foreign Members\n Object.keys(geojson).forEach(function (key) {\n switch (key) {\n case 'type':\n case 'properties':\n case 'geometry':\n return;\n default:\n cloned[key] = geojson[key];\n }\n });\n // Add properties & geometry last\n cloned.properties = cloneProperties(geojson.properties);\n cloned.geometry = cloneGeometry(geojson.geometry);\n return cloned;\n}\n\n/**\n * Clone Properties\n *\n * @private\n * @param {Object} properties GeoJSON Properties\n * @returns {Object} cloned Properties\n */\nfunction cloneProperties(properties) {\n var cloned = {};\n if (!properties) return cloned;\n Object.keys(properties).forEach(function (key) {\n var value = properties[key];\n if (typeof value === 'object') {\n if (value === null) {\n // handle null\n cloned[key] = null;\n } else if (value.length) {\n // handle Array\n cloned[key] = value.map(function (item) {\n return item;\n });\n } else {\n // handle generic Object\n cloned[key] = cloneProperties(value);\n }\n } else cloned[key] = value;\n });\n return cloned;\n}\n\n/**\n * Clone Feature Collection\n *\n * @private\n * @param {FeatureCollection<any>} geojson GeoJSON Feature Collection\n * @returns {FeatureCollection<any>} cloned Feature Collection\n */\nfunction cloneFeatureCollection(geojson) {\n var cloned = {type: 'FeatureCollection'};\n\n // Preserve Foreign Members\n Object.keys(geojson).forEach(function (key) {\n switch (key) {\n case 'type':\n case 'features':\n return;\n default:\n cloned[key] = geojson[key];\n }\n });\n // Add features\n cloned.features = geojson.features.map(function (feature) {\n return cloneFeature(feature);\n });\n return cloned;\n}\n\n/**\n * Clone Geometry\n *\n * @private\n * @param {Geometry<any>} geometry GeoJSON Geometry\n * @returns {Geometry<any>} cloned Geometry\n */\nfunction cloneGeometry(geometry) {\n var geom = {type: geometry.type};\n if (geometry.bbox) geom.bbox = geometry.bbox;\n\n if (geometry.type === 'GeometryCollection') {\n geom.geometries = geometry.geometries.map(function (geom) {\n return cloneGeometry(geom);\n });\n return geom;\n }\n geom.coordinates = deepSlice(geometry.coordinates);\n return geom;\n}\n\n/**\n * Deep Slice coordinates\n *\n * @private\n * @param {Coordinates} coords Coordinates\n * @returns {Coordinates} all coordinates sliced\n */\nfunction deepSlice(coords) {\n if (typeof coords[0] !== 'object') { return coords.slice(); }\n return coords.map(function (coord) {\n return deepSlice(coord);\n });\n}\n\nexport default clone;\n","import { isNumber } from '@turf/helpers';\n\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers\n * @returns {Array<number>} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nfunction getCoord(coord) {\n if (!coord) throw new Error('coord is required');\n if (coord.type === 'Feature' && coord.geometry !== null && coord.geometry.type === 'Point') return coord.geometry.coordinates;\n if (coord.type === 'Point') return coord.coordinates;\n if (Array.isArray(coord) && coord.length >= 2 && coord[0].length === undefined && coord[1].length === undefined) return coord;\n\n throw new Error('coord must be GeoJSON Point or an Array of numbers');\n}\n\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array<any>|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array<any>} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nfunction getCoords(coords) {\n if (!coords) throw new Error('coords is required');\n\n // Feature\n if (coords.type === 'Feature' && coords.geometry !== null) return coords.geometry.coordinates;\n\n // Geometry\n if (coords.coordinates) return coords.coordinates;\n\n // Array of numbers\n if (Array.isArray(coords)) return coords;\n\n throw new Error('coords must be GeoJSON Feature, Geometry Object or an Array');\n}\n\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array<any>} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nfunction containsNumber(coordinates) {\n if (coordinates.length > 1 && isNumber(coordinates[0]) && isNumber(coordinates[1])) {\n return true;\n }\n\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error('coordinates must only contain numbers');\n}\n\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction geojsonType(value, type, name) {\n if (!type || !name) throw new Error('type and name required');\n\n if (!value || value.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + value.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nfunction featureOf(feature, type, name) {\n if (!feature) throw new Error('No feature passed');\n if (!name) throw new Error('.featureOf() requires a name');\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction collectionOf(featureCollection, type, name) {\n if (!featureCollection) throw new Error('No featureCollection passed');\n if (!name) throw new Error('.collectionOf() requires a name');\n if (!featureCollection || featureCollection.type !== 'FeatureCollection') {\n throw new Error('Invalid input to ' + name + ', FeatureCollection required');\n }\n for (var i = 0; i < featureCollection.features.length; i++) {\n var feature = featureCollection.features[i];\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n }\n}\n\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nfunction getGeom(geojson) {\n if (!geojson) throw new Error('geojson is required');\n if (geojson.geometry !== undefined) return geojson.geometry;\n if (geojson.coordinates || geojson.geometries) return geojson;\n throw new Error('geojson must be a valid Feature or Geometry Object');\n}\n\n/**\n * Get Geometry Type from Feature or Geometry Object\n *\n * @throws {Error} **DEPRECATED** in v5.0.0 in favor of getType\n */\nfunction getGeomType() {\n throw new Error('invariant.getGeomType has been deprecated in v5.0 in favor of invariant.getType');\n}\n\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nfunction getType(geojson, name) {\n if (!geojson) throw new Error((name || 'geojson') + ' is required');\n // GeoJSON Feature & GeometryCollection\n if (geojson.geometry && geojson.geometry.type) return geojson.geometry.type;\n // GeoJSON Geometry & FeatureCollection\n if (geojson.type) return geojson.type;\n throw new Error((name || 'geojson') + ' is invalid');\n}\n\nexport { getCoord, getCoords, containsNumber, geojsonType, featureOf, collectionOf, getGeom, getGeomType, getType };\n","import centroid from '@turf/centroid';\nimport rhumbBearing from '@turf/rhumb-bearing';\nimport rhumbDistance from '@turf/rhumb-distance';\nimport rhumbDestination from '@turf/rhumb-destination';\nimport clone from '@turf/clone';\nimport { coordEach } from '@turf/meta';\nimport { getCoords } from '@turf/invariant';\nimport { isObject } from '@turf/helpers';\n\n/**\n * Rotates any geojson Feature or Geometry of a specified angle, around its `centroid` or a given `pivot` point;\n * all rotations follow the right-hand rule: https://en.wikipedia.org/wiki/Right-hand_rule\n *\n * @name transformRotate\n * @param {GeoJSON} geojson object to be rotated\n * @param {number} angle of rotation (along the vertical axis), from North in decimal degrees, negative clockwise\n * @param {Object} [options={}] Optional parameters\n * @param {Coord} [options.pivot='centroid'] point around which the rotation will be performed\n * @param {boolean} [options.mutate=false] allows GeoJSON input to be mutated (significant performance increase if true)\n * @returns {GeoJSON} the rotated GeoJSON feature\n * @example\n * var poly = turf.polygon([[[0,29],[3.5,29],[2.5,32],[0,29]]]);\n * var options = {pivot: [0, 25]};\n * var rotatedPoly = turf.transformRotate(poly, 10, options);\n *\n * //addToMap\n * var addToMap = [poly, rotatedPoly];\n * rotatedPoly.properties = {stroke: '#F00', 'stroke-width': 4};\n */\nfunction transformRotate(geojson, angle, options) {\n // Optional parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var pivot = options.pivot;\n var mutate = options.mutate;\n\n // Input validation\n if (!geojson) throw new Error('geojson is required');\n if (angle === undefined || angle === null || isNaN(angle)) throw new Error('angle is required');\n\n // Shortcut no-rotation\n if (angle === 0) return geojson;\n\n // Use centroid of GeoJSON if pivot is not provided\n if (!pivot) pivot = centroid(geojson);\n\n // Clone geojson to avoid side effects\n if (mutate === false || mutate === undefined) geojson = clone(geojson);\n\n // Rotate each coordinate\n coordEach(geojson, function (pointCoords) {\n var initialAngle = rhumbBearing(pivot, pointCoords);\n var finalAngle = initialAngle + angle;\n var distance = rhumbDistance(pivot, pointCoords);\n var newCoords = getCoords(rhumbDestination(pivot, distance, finalAngle));\n pointCoords[0] = newCoords[0];\n pointCoords[1] = newCoords[1];\n });\n return geojson;\n}\n\nexport default transformRotate;\n","/**\n * Earth Radius used with the Harvesine formula and approximates using a spherical (non-ellipsoid) Earth.\n */\nvar earthRadius = 6371008.8;\n\n/**\n * Unit of measurement factors using a spherical (non-ellipsoid) earth radius.\n */\nvar factors = {\n meters: earthRadius,\n metres: earthRadius,\n millimeters: earthRadius * 1000,\n millimetres: earthRadius * 1000,\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n kilometers: earthRadius / 1000,\n kilometres: earthRadius / 1000,\n miles: earthRadius / 1609.344,\n nauticalmiles: earthRadius / 1852,\n inches: earthRadius * 39.370,\n yards: earthRadius / 1.0936,\n feet: earthRadius * 3.28084,\n radians: 1,\n degrees: earthRadius / 111325,\n};\n\n/**\n * Units of measurement factors based on 1 meter.\n */\nvar unitsFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000,\n millimetres: 1000,\n centimeters: 100,\n centimetres: 100,\n kilometers: 1 / 1000,\n kilometres: 1 / 1000,\n miles: 1 / 1609.344,\n nauticalmiles: 1 / 1852,\n inches: 39.370,\n yards: 1 / 1.0936,\n feet: 3.28084,\n radians: 1 / earthRadius,\n degrees: 1 / 111325,\n};\n\n/**\n * Area of measurement factors based on 1 square meter.\n */\nvar areaFactors = {\n meters: 1,\n metres: 1,\n millimeters: 1000000,\n millimetres: 1000000,\n centimeters: 10000,\n centimetres: 10000,\n kilometers: 0.000001,\n kilometres: 0.000001,\n acres: 0.000247105,\n miles: 3.86e-7,\n yards: 1.195990046,\n feet: 10.763910417,\n inches: 1550.003100006\n};\n\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @name feature\n * @param {Geometry} geometry input geometry\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature} a GeoJSON Feature\n * @example\n * var geometry = {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 50]\n * };\n *\n * var feature = turf.feature(geometry);\n *\n * //=feature\n */\nfunction feature(geometry, properties, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (geometry === undefined) throw new Error('geometry is required');\n if (properties && properties.constructor !== Object) throw new Error('properties must be an Object');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var feat = {type: 'Feature'};\n if (id) feat.id = id;\n if (bbox) feat.bbox = bbox;\n feat.properties = properties || {};\n feat.geometry = geometry;\n return feat;\n}\n\n/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @name geometry\n * @param {string} type Geometry Type\n * @param {Array<number>} coordinates Coordinates\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Geometry\n * @returns {Geometry} a GeoJSON Geometry\n * @example\n * var type = 'Point';\n * var coordinates = [110, 50];\n *\n * var geometry = turf.geometry(type, coordinates);\n *\n * //=geometry\n */\nfunction geometry(type, coordinates, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n\n // Validation\n if (!type) throw new Error('type is required');\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (bbox) validateBBox(bbox);\n\n // Main\n var geom;\n switch (type) {\n case 'Point': geom = point(coordinates).geometry; break;\n case 'LineString': geom = lineString(coordinates).geometry; break;\n case 'Polygon': geom = polygon(coordinates).geometry; break;\n case 'MultiPoint': geom = multiPoint(coordinates).geometry; break;\n case 'MultiLineString': geom = multiLineString(coordinates).geometry; break;\n case 'MultiPolygon': geom = multiPolygon(coordinates).geometry; break;\n default: throw new Error(type + ' is invalid');\n }\n if (bbox) geom.bbox = bbox;\n return geom;\n}\n\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @name point\n * @param {Array<number>} coordinates longitude, latitude position (each in decimal degrees)\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nfunction point(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n if (coordinates.length < 2) throw new Error('coordinates must be at least 2 numbers long');\n if (!isNumber(coordinates[0]) || !isNumber(coordinates[1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'Point',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @name points\n * @param {Array<Array<number>>} coordinates an array of Points\n * @param {Object} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Point>} Point Feature\n * @example\n * var points = turf.points([\n * [-75, 39],\n * [-80, 45],\n * [-78, 50]\n * ]);\n *\n * //=points\n */\nfunction points(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return point(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @name polygon\n * @param {Array<Array<Array<number>>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon>} Polygon Feature\n * @example\n * var polygon = turf.polygon([[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]], { name: 'poly1' });\n *\n * //=polygon\n */\nfunction polygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n for (var i = 0; i < coordinates.length; i++) {\n var ring = coordinates[i];\n if (ring.length < 4) {\n throw new Error('Each LinearRing of a Polygon must have 4 or more Positions.');\n }\n for (var j = 0; j < ring[ring.length - 1].length; j++) {\n // Check if first point of Polygon contains two numbers\n if (i === 0 && j === 0 && !isNumber(ring[0][0]) || !isNumber(ring[0][1])) throw new Error('coordinates must contain numbers');\n if (ring[ring.length - 1][j] !== ring[0][j]) {\n throw new Error('First and last Position are not equivalent.');\n }\n }\n }\n\n return feature({\n type: 'Polygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @name polygons\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygon coordinates\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon>} Polygon FeatureCollection\n * @example\n * var polygons = turf.polygons([\n * [[[-5, 52], [-4, 56], [-2, 51], [-7, 54], [-5, 52]]],\n * [[[-15, 42], [-14, 46], [-12, 41], [-17, 44], [-15, 42]]],\n * ]);\n *\n * //=polygons\n */\nfunction polygons(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return polygon(coords, properties);\n }), options);\n}\n\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @name lineString\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString>} LineString Feature\n * @example\n * var linestring1 = turf.lineString([[-24, 63], [-23, 60], [-25, 65], [-20, 69]], {name: 'line 1'});\n * var linestring2 = turf.lineString([[-14, 43], [-13, 40], [-15, 45], [-10, 49]], {name: 'line 2'});\n *\n * //=linestring1\n * //=linestring2\n */\nfunction lineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (coordinates.length < 2) throw new Error('coordinates must be an array of two or more positions');\n // Check if first point of LineString contains two numbers\n if (!isNumber(coordinates[0][1]) || !isNumber(coordinates[0][1])) throw new Error('coordinates must contain numbers');\n\n return feature({\n type: 'LineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @name lineStrings\n * @param {Array<Array<number>>} coordinates an array of LinearRings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the FeatureCollection\n * @param {string|number} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString>} LineString FeatureCollection\n * @example\n * var linestrings = turf.lineStrings([\n * [[-24, 63], [-23, 60], [-25, 65], [-20, 69]],\n * [[-14, 43], [-13, 40], [-15, 45], [-10, 49]]\n * ]);\n *\n * //=linestrings\n */\nfunction lineStrings(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n if (!Array.isArray(coordinates)) throw new Error('coordinates must be an Array');\n\n return featureCollection(coordinates.map(function (coords) {\n return lineString(coords, properties);\n }), options);\n}\n\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @name featureCollection\n * @param {Feature[]} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection} FeatureCollection of Features\n * @example\n * var locationA = turf.point([-75.343, 39.984], {name: 'Location A'});\n * var locationB = turf.point([-75.833, 39.284], {name: 'Location B'});\n * var locationC = turf.point([-75.534, 39.123], {name: 'Location C'});\n *\n * var collection = turf.featureCollection([\n * locationA,\n * locationB,\n * locationC\n * ]);\n *\n * //=collection\n */\nfunction featureCollection(features, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var bbox = options.bbox;\n var id = options.id;\n\n // Validation\n if (!features) throw new Error('No features passed');\n if (!Array.isArray(features)) throw new Error('features must be an Array');\n if (bbox) validateBBox(bbox);\n if (id) validateId(id);\n\n // Main\n var fc = {type: 'FeatureCollection'};\n if (id) fc.id = id;\n if (bbox) fc.bbox = bbox;\n fc.features = features;\n return fc;\n}\n\n/**\n * Creates a {@link Feature<MultiLineString>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiLineString\n * @param {Array<Array<Array<number>>>} coordinates an array of LineStrings\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString>} a MultiLineString feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiLine = turf.multiLineString([[[0,0],[10,10]]]);\n *\n * //=multiLine\n */\nfunction multiLineString(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiLineString',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPoint>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPoint\n * @param {Array<Array<number>>} coordinates an array of Positions\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint>} a MultiPoint feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPt = turf.multiPoint([[0,0],[10,10]]);\n *\n * //=multiPt\n */\nfunction multiPoint(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPoint',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<MultiPolygon>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name multiPolygon\n * @param {Array<Array<Array<Array<number>>>>} coordinates an array of Polygons\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon>} a multipolygon feature\n * @throws {Error} if no coordinates are passed\n * @example\n * var multiPoly = turf.multiPolygon([[[[0,0],[0,10],[10,10],[10,0],[0,0]]]]);\n *\n * //=multiPoly\n *\n */\nfunction multiPolygon(coordinates, properties, options) {\n if (!coordinates) throw new Error('coordinates is required');\n\n return feature({\n type: 'MultiPolygon',\n coordinates: coordinates\n }, properties, options);\n}\n\n/**\n * Creates a {@link Feature<GeometryCollection>} based on a\n * coordinate array. Properties can be added optionally.\n *\n * @name geometryCollection\n * @param {Array<Geometry>} geometries an array of GeoJSON Geometries\n * @param {Object} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {Array<number>} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {string|number} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection>} a GeoJSON GeometryCollection Feature\n * @example\n * var pt = {\n * \"type\": \"Point\",\n * \"coordinates\": [100, 0]\n * };\n * var line = {\n * \"type\": \"LineString\",\n * \"coordinates\": [ [101, 0], [102, 1] ]\n * };\n * var collection = turf.geometryCollection([pt, line]);\n *\n * //=collection\n */\nfunction geometryCollection(geometries, properties, options) {\n if (!geometries) throw new Error('geometries is required');\n if (!Array.isArray(geometries)) throw new Error('geometries must be an Array');\n\n return feature({\n type: 'GeometryCollection',\n geometries: geometries\n }, properties, options);\n}\n\n/**\n * Round number to precision\n *\n * @param {number} num Number\n * @param {number} [precision=0] Precision\n * @returns {number} rounded number\n * @example\n * turf.round(120.4321)\n * //=120\n *\n * turf.round(120.4321, 2)\n * //=120.43\n */\nfunction round(num, precision) {\n if (num === undefined || num === null || isNaN(num)) throw new Error('num is required');\n if (precision && !(precision >= 0)) throw new Error('precision must be a positive number');\n var multiplier = Math.pow(10, precision || 0);\n return Math.round(num * multiplier) / multiplier;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from radians to a more friendly unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name radiansToLength\n * @param {number} radians in radians across the sphere\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} distance\n */\nfunction radiansToLength(radians, units) {\n if (radians === undefined || radians === null) throw new Error('radians is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return radians * factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into radians\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @name lengthToRadians\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} radians\n */\nfunction lengthToRadians(distance, units) {\n if (distance === undefined || distance === null) throw new Error('distance is required');\n\n if (units && typeof units !== 'string') throw new Error('units must be a string');\n var factor = factors[units || 'kilometers'];\n if (!factor) throw new Error(units + ' units is invalid');\n return distance / factor;\n}\n\n/**\n * Convert a distance measurement (assuming a spherical Earth) from a real-world unit into degrees\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, centimeters, kilometres, feet\n *\n * @name lengthToDegrees\n * @param {number} distance in real units\n * @param {string} [units='kilometers'] can be degrees, radians, miles, or kilometers inches, yards, metres, meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nfunction lengthToDegrees(distance, units) {\n return radiansToDegrees(lengthToRadians(distance, units));\n}\n\n/**\n * Converts any bearing angle from the north line direction (positive clockwise)\n * and returns an angle between 0-360 degrees (positive clockwise), 0 being the north line\n *\n * @name bearingToAzimuth\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nfunction bearingToAzimuth(bearing) {\n if (bearing === null || bearing === undefined) throw new Error('bearing is required');\n\n var angle = bearing % 360;\n if (angle < 0) angle += 360;\n return angle;\n}\n\n/**\n * Converts an angle in radians to degrees\n *\n * @name radiansToDegrees\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nfunction radiansToDegrees(radians) {\n if (radians === null || radians === undefined) throw new Error('radians is required');\n\n var degrees = radians % (2 * Math.PI);\n return degrees * 180 / Math.PI;\n}\n\n/**\n * Converts an angle in degrees to radians\n *\n * @name degreesToRadians\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nfunction degreesToRadians(degrees) {\n if (degrees === null || degrees === undefined) throw new Error('degrees is required');\n\n var radians = degrees % 360;\n return radians * Math.PI / 180;\n}\n\n/**\n * Converts a length to the requested unit.\n * Valid units: miles, nauticalmiles, inches, yards, meters, metres, kilometers, centimeters, feet\n *\n * @param {number} length to be converted\n * @param {string} originalUnit of the length\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted length\n */\nfunction convertLength(length, originalUnit, finalUnit) {\n if (length === null || length === undefined) throw new Error('length is required');\n if (!(length >= 0)) throw new Error('length must be a positive number');\n\n return radiansToLength(lengthToRadians(length, originalUnit), finalUnit || 'kilometers');\n}\n\n/**\n * Converts a area to the requested unit.\n * Valid units: kilometers, kilometres, meters, metres, centimetres, millimeters, acres, miles, yards, feet, inches\n * @param {number} area to be converted\n * @param {string} [originalUnit='meters'] of the distance\n * @param {string} [finalUnit='kilometers'] returned unit\n * @returns {number} the converted distance\n */\nfunction convertArea(area, originalUnit, finalUnit) {\n if (area === null || area === undefined) throw new Error('area is required');\n if (!(area >= 0)) throw new Error('area must be a positive number');\n\n var startFactor = areaFactors[originalUnit || 'meters'];\n if (!startFactor) throw new Error('invalid original units');\n\n var finalFactor = areaFactors[finalUnit || 'kilometers'];\n if (!finalFactor) throw new Error('invalid final units');\n\n return (area / startFactor) * finalFactor;\n}\n\n/**\n * isNumber\n *\n * @param {*} num Number to validate\n * @returns {boolean} true/false\n * @example\n * turf.isNumber(123)\n * //=true\n * turf.isNumber('foo')\n * //=false\n */\nfunction isNumber(num) {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n\n/**\n * isObject\n *\n * @param {*} input variable to validate\n * @returns {boolean} true/false\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nfunction isObject(input) {\n return (!!input) && (input.constructor === Object);\n}\n\n/**\n * Validate BBox\n *\n * @private\n * @param {Array<number>} bbox BBox to validate\n * @returns {void}\n * @throws Error if BBox is not valid\n * @example\n * validateBBox([-180, -40, 110, 50])\n * //=OK\n * validateBBox([-180, -40])\n * //=Error\n * validateBBox('Foo')\n * //=Error\n * validateBBox(5)\n * //=Error\n * validateBBox(null)\n * //=Error\n * validateBBox(undefined)\n * //=Error\n */\nfunction validateBBox(bbox) {\n if (!bbox) throw new Error('bbox is required');\n if (!Array.isArray(bbox)) throw new Error('bbox must be an Array');\n if (bbox.length !== 4 && bbox.length !== 6) throw new Error('bbox must be an Array of 4 or 6 numbers');\n bbox.forEach(function (num) {\n if (!isNumber(num)) throw new Error('bbox must only contain numbers');\n });\n}\n\n/**\n * Validate Id\n *\n * @private\n * @param {string|number} id Id to validate\n * @returns {void}\n * @throws Error if Id is not valid\n * @example\n * validateId([-180, -40, 110, 50])\n * //=Error\n * validateId([-180, -40])\n * //=Error\n * validateId('Foo')\n * //=OK\n * validateId(5)\n * //=OK\n * validateId(null)\n * //=Error\n * validateId(undefined)\n * //=Error\n */\nfunction validateId(id) {\n if (!id) throw new Error('id is required');\n if (['string', 'number'].indexOf(typeof id) === -1) throw new Error('id must be a number or a string');\n}\n\n// Deprecated methods\nfunction radians2degrees() {\n throw new Error('method has been renamed to `radiansToDegrees`');\n}\n\nfunction degrees2radians() {\n throw new Error('method has been renamed to `degreesToRadians`');\n}\n\nfunction distanceToDegrees() {\n throw new Error('method has been renamed to `lengthToDegrees`');\n}\n\nfunction distanceToRadians() {\n throw new Error('method has been renamed to `lengthToRadians`');\n}\n\nfunction radiansToDistance() {\n throw new Error('method has been renamed to `radiansToLength`');\n}\n\nfunction bearingToAngle() {\n throw new Error('method has been renamed to `bearingToAzimuth`');\n}\n\nfunction convertDistance() {\n throw new Error('method has been renamed to `convertLength`');\n}\n\nexport { earthRadius, factors, unitsFactors, areaFactors, feature, geometry, point, points, polygon, polygons, lineString, lineStrings, featureCollection, multiLineString, multiPoint, multiPolygon, geometryCollection, round, radiansToLength, lengthToRadians, lengthToDegrees, bearingToAzimuth, radiansToDegrees, degreesToRadians, convertLength, convertArea, isNumber, isObject, validateBBox, validateId, radians2degrees, degrees2radians, distanceToDegrees, distanceToRadians, radiansToDistance, bearingToAngle, convertDistance };\n","import { feature, isObject, lineString, point } from '@turf/helpers';\n\n/**\n * Callback for coordEach\n *\n * @callback coordEachCallback\n * @param {Array<number>} currentCoord The current coordinate being processed.\n * @param {number} coordIndex The current index of the coordinate being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n */\n\n/**\n * Iterate over coordinates in any GeoJSON object, similar to Array.forEach()\n *\n * @name coordEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentCoord, coordIndex, featureIndex, multiFeatureIndex)\n * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.coordEach(features, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=currentCoord\n * //=coordIndex\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * });\n */\nfunction coordEach(geojson, callback, excludeWrapCoord) {\n // Handles null Geometry -- Skips this GeoJSON\n if (geojson === null) return;\n var j, k, l, geometry, stopG, coords,\n geometryMaybeCollection,\n wrapShrink = 0,\n coordIndex = 0,\n isGeometryCollection,\n type = geojson.type,\n isFeatureCollection = type === 'FeatureCollection',\n isFeature = type === 'Feature',\n stop = isFeatureCollection ? geojson.features.length : 1;\n\n // This logic may look a little weird. The reason why it is that way\n // is because it's trying to be fast. GeoJSON supports multiple kinds\n // of objects at its root: FeatureCollection, Features, Geometries.\n // This function has the responsibility of handling all of them, and that\n // means that some of the `for` loops you see below actually just don't apply\n // to certain inputs. For instance, if you give this just a\n // Point geometry, then both loops are short-circuited and all we do\n // is gradually rename the input until it's called 'geometry'.\n //\n // This also aims to allocate as few resources as possible: just a\n // few numbers and booleans, rather than any temporary arrays as would\n // be required with the normalization approach.\n for (var featureIndex = 0; featureIndex < stop; featureIndex++) {\n geometryMaybeCollection = (isFeatureCollection ? geojson.features[featureIndex].geometry :\n (isFeature ? geojson.geometry : geojson));\n isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;\n stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;\n\n for (var geomIndex = 0; geomIndex < stopG; geomIndex++) {\n var multiFeatureIndex = 0;\n var geometryIndex = 0;\n geometry = isGeometryCollection ?\n geometryMaybeCollection.geometries[geomIndex] : geometryMaybeCollection;\n\n // Handles null Geometry -- Skips this geometry\n if (geometry === null) continue;\n coords = geometry.coordinates;\n var geomType = geometry.type;\n\n wrapShrink = (excludeWrapCoord && (geomType === 'Polygon' || geomType === 'MultiPolygon')) ? 1 : 0;\n\n switch (geomType) {\n case null:\n break;\n case 'Point':\n if (callback(coords, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n multiFeatureIndex++;\n break;\n case 'LineString':\n case 'MultiPoint':\n for (j = 0; j < coords.length; j++) {\n if (callback(coords[j], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n if (geomType === 'MultiPoint') multiFeatureIndex++;\n }\n if (geomType === 'LineString') multiFeatureIndex++;\n break;\n case 'Polygon':\n case 'MultiLineString':\n for (j = 0; j < coords.length; j++) {\n for (k = 0; k < coords[j].length - wrapShrink; k++) {\n if (callback(coords[j][k], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n }\n if (geomType === 'MultiLineString') multiFeatureIndex++;\n if (geomType === 'Polygon') geometryIndex++;\n }\n if (geomType === 'Polygon') multiFeatureIndex++;\n break;\n case 'MultiPolygon':\n for (j = 0; j < coords.length; j++) {\n if (geomType === 'MultiPolygon') geometryIndex = 0;\n for (k = 0; k < coords[j].length; k++) {\n for (l = 0; l < coords[j][k].length - wrapShrink; l++) {\n if (callback(coords[j][k][l], coordIndex, featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n coordIndex++;\n }\n geometryIndex++;\n }\n multiFeatureIndex++;\n }\n break;\n case 'GeometryCollection':\n for (j = 0; j < geometry.geometries.length; j++)\n if (coordEach(geometry.geometries[j], callback, excludeWrapCoord) === false) return false;\n break;\n default:\n throw new Error('Unknown Geometry Type');\n }\n }\n }\n}\n\n/**\n * Callback for coordReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback coordReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Array<number>} currentCoord The current coordinate being processed.\n * @param {number} coordIndex The current index of the coordinate being processed.\n * Starts at index 0, if an initialValue is provided, and at index 1 otherwise.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n */\n\n/**\n * Reduce coordinates in any GeoJSON object, similar to Array.reduce()\n *\n * @name coordReduce\n * @param {FeatureCollection|Geometry|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentCoord, coordIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @param {boolean} [excludeWrapCoord=false] whether or not to include the final coordinate of LinearRings that wraps the ring in its iteration.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.coordReduce(features, function (previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=previousValue\n * //=currentCoord\n * //=coordIndex\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * return currentCoord;\n * });\n */\nfunction coordReduce(geojson, callback, initialValue, excludeWrapCoord) {\n var previousValue = initialValue;\n coordEach(geojson, function (currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex) {\n if (coordIndex === 0 && initialValue === undefined) previousValue = currentCoord;\n else previousValue = callback(previousValue, currentCoord, coordIndex, featureIndex, multiFeatureIndex, geometryIndex);\n }, excludeWrapCoord);\n return previousValue;\n}\n\n/**\n * Callback for propEach\n *\n * @callback propEachCallback\n * @param {Object} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Iterate over properties in any GeoJSON object, similar to Array.forEach()\n *\n * @name propEach\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentProperties, featureIndex)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.propEach(features, function (currentProperties, featureIndex) {\n * //=currentProperties\n * //=featureIndex\n * });\n */\nfunction propEach(geojson, callback) {\n var i;\n switch (geojson.type) {\n case 'FeatureCollection':\n for (i = 0; i < geojson.features.length; i++) {\n if (callback(geojson.features[i].properties, i) === false) break;\n }\n break;\n case 'Feature':\n callback(geojson.properties, 0);\n break;\n }\n}\n\n\n/**\n * Callback for propReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback propReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {*} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Reduce properties in any GeoJSON object into a single value,\n * similar to how Array.reduce works. However, in this case we lazily run\n * the reduction, so an array of all properties is unnecessary.\n *\n * @name propReduce\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentProperties, featureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.propReduce(features, function (previousValue, currentProperties, featureIndex) {\n * //=previousValue\n * //=currentProperties\n * //=featureIndex\n * return currentProperties\n * });\n */\nfunction propReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n propEach(geojson, function (currentProperties, featureIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentProperties;\n else previousValue = callback(previousValue, currentProperties, featureIndex);\n });\n return previousValue;\n}\n\n/**\n * Callback for featureEach\n *\n * @callback featureEachCallback\n * @param {Feature<any>} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Iterate over features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @name featureEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentFeature, featureIndex)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.featureEach(features, function (currentFeature, featureIndex) {\n * //=currentFeature\n * //=featureIndex\n * });\n */\nfunction featureEach(geojson, callback) {\n if (geojson.type === 'Feature') {\n callback(geojson, 0);\n } else if (geojson.type === 'FeatureCollection') {\n for (var i = 0; i < geojson.features.length; i++) {\n if (callback(geojson.features[i], i) === false) break;\n }\n }\n}\n\n/**\n * Callback for featureReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback featureReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @name featureReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {\"foo\": \"bar\"}),\n * turf.point([36, 53], {\"hello\": \"world\"})\n * ]);\n *\n * turf.featureReduce(features, function (previousValue, currentFeature, featureIndex) {\n * //=previousValue\n * //=currentFeature\n * //=featureIndex\n * return currentFeature\n * });\n */\nfunction featureReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n featureEach(geojson, function (currentFeature, featureIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentFeature;\n else previousValue = callback(previousValue, currentFeature, featureIndex);\n });\n return previousValue;\n}\n\n/**\n * Get all coordinates from any GeoJSON object.\n *\n * @name coordAll\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @returns {Array<Array<number>>} coordinate position array\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * var coords = turf.coordAll(features);\n * //= [[26, 37], [36, 53]]\n */\nfunction coordAll(geojson) {\n var coords = [];\n coordEach(geojson, function (coord) {\n coords.push(coord);\n });\n return coords;\n}\n\n/**\n * Callback for geomEach\n *\n * @callback geomEachCallback\n * @param {Geometry} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {Object} featureProperties The current Feature Properties being processed.\n * @param {Array<number>} featureBBox The current Feature BBox being processed.\n * @param {number|string} featureId The current Feature Id being processed.\n */\n\n/**\n * Iterate over each geometry in any GeoJSON object, similar to Array.forEach()\n *\n * @name geomEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @returns {void}\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.geomEach(features, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n * //=currentGeometry\n * //=featureIndex\n * //=featureProperties\n * //=featureBBox\n * //=featureId\n * });\n */\nfunction geomEach(geojson, callback) {\n var i, j, g, geometry, stopG,\n geometryMaybeCollection,\n isGeometryCollection,\n featureProperties,\n featureBBox,\n featureId,\n featureIndex = 0,\n isFeatureCollection = geojson.type === 'FeatureCollection',\n isFeature = geojson.type === 'Feature',\n stop = isFeatureCollection ? geojson.features.length : 1;\n\n // This logic may look a little weird. The reason why it is that way\n // is because it's trying to be fast. GeoJSON supports multiple kinds\n // of objects at its root: FeatureCollection, Features, Geometries.\n // This function has the responsibility of handling all of them, and that\n // means that some of the `for` loops you see below actually just don't apply\n // to certain inputs. For instance, if you give this just a\n // Point geometry, then both loops are short-circuited and all we do\n // is gradually rename the input until it's called 'geometry'.\n //\n // This also aims to allocate as few resources as possible: just a\n // few numbers and booleans, rather than any temporary arrays as would\n // be required with the normalization approach.\n for (i = 0; i < stop; i++) {\n\n geometryMaybeCollection = (isFeatureCollection ? geojson.features[i].geometry :\n (isFeature ? geojson.geometry : geojson));\n featureProperties = (isFeatureCollection ? geojson.features[i].properties :\n (isFeature ? geojson.properties : {}));\n featureBBox = (isFeatureCollection ? geojson.features[i].bbox :\n (isFeature ? geojson.bbox : undefined));\n featureId = (isFeatureCollection ? geojson.features[i].id :\n (isFeature ? geojson.id : undefined));\n isGeometryCollection = (geometryMaybeCollection) ? geometryMaybeCollection.type === 'GeometryCollection' : false;\n stopG = isGeometryCollection ? geometryMaybeCollection.geometries.length : 1;\n\n for (g = 0; g < stopG; g++) {\n geometry = isGeometryCollection ?\n geometryMaybeCollection.geometries[g] : geometryMaybeCollection;\n\n // Handle null Geometry\n if (geometry === null) {\n if (callback(null, featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n continue;\n }\n switch (geometry.type) {\n case 'Point':\n case 'LineString':\n case 'MultiPoint':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon': {\n if (callback(geometry, featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n break;\n }\n case 'GeometryCollection': {\n for (j = 0; j < geometry.geometries.length; j++) {\n if (callback(geometry.geometries[j], featureIndex, featureProperties, featureBBox, featureId) === false) return false;\n }\n break;\n }\n default:\n throw new Error('Unknown Geometry Type');\n }\n }\n // Only increase `featureIndex` per each feature\n featureIndex++;\n }\n}\n\n/**\n * Callback for geomReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback geomReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Geometry} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {Object} featureProperties The current Feature Properties being processed.\n * @param {Array<number>} featureBBox The current Feature BBox being processed.\n * @param {number|string} featureId The current Feature Id being processed.\n */\n\n/**\n * Reduce geometry in any GeoJSON object, similar to Array.reduce().\n *\n * @name geomReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.point([36, 53], {hello: 'world'})\n * ]);\n *\n * turf.geomReduce(features, function (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n * //=previousValue\n * //=currentGeometry\n * //=featureIndex\n * //=featureProperties\n * //=featureBBox\n * //=featureId\n * return currentGeometry\n * });\n */\nfunction geomReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n geomEach(geojson, function (currentGeometry, featureIndex, featureProperties, featureBBox, featureId) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentGeometry;\n else previousValue = callback(previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId);\n });\n return previousValue;\n}\n\n/**\n * Callback for flattenEach\n *\n * @callback flattenEachCallback\n * @param {Feature} currentFeature The current flattened feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n */\n\n/**\n * Iterate over flattened features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @name flattenEach\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex)\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})\n * ]);\n *\n * turf.flattenEach(features, function (currentFeature, featureIndex, multiFeatureIndex) {\n * //=currentFeature\n * //=featureIndex\n * //=multiFeatureIndex\n * });\n */\nfunction flattenEach(geojson, callback) {\n geomEach(geojson, function (geometry, featureIndex, properties, bbox, id) {\n // Callback for single geometry\n var type = (geometry === null) ? null : geometry.type;\n switch (type) {\n case null:\n case 'Point':\n case 'LineString':\n case 'Polygon':\n if (callback(feature(geometry, properties, {bbox: bbox, id: id}), featureIndex, 0) === false) return false;\n return;\n }\n\n var geomType;\n\n // Callback for multi-geometry\n switch (type) {\n case 'MultiPoint':\n geomType = 'Point';\n break;\n case 'MultiLineString':\n geomType = 'LineString';\n break;\n case 'MultiPolygon':\n geomType = 'Polygon';\n break;\n }\n\n for (var multiFeatureIndex = 0; multiFeatureIndex < geometry.coordinates.length; multiFeatureIndex++) {\n var coordinate = geometry.coordinates[multiFeatureIndex];\n var geom = {\n type: geomType,\n coordinates: coordinate\n };\n if (callback(feature(geom, properties), featureIndex, multiFeatureIndex) === false) return false;\n }\n });\n}\n\n/**\n * Callback for flattenReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback flattenReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature} currentFeature The current Feature being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n */\n\n/**\n * Reduce flattened features in any GeoJSON object, similar to Array.reduce().\n *\n * @name flattenReduce\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {Function} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var features = turf.featureCollection([\n * turf.point([26, 37], {foo: 'bar'}),\n * turf.multiPoint([[40, 30], [36, 53]], {hello: 'world'})\n * ]);\n *\n * turf.flattenReduce(features, function (previousValue, currentFeature, featureIndex, multiFeatureIndex) {\n * //=previousValue\n * //=currentFeature\n * //=featureIndex\n * //=multiFeatureIndex\n * return currentFeature\n * });\n */\nfunction flattenReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n flattenEach(geojson, function (currentFeature, featureIndex, multiFeatureIndex) {\n if (featureIndex === 0 && multiFeatureIndex === 0 && initialValue === undefined) previousValue = currentFeature;\n else previousValue = callback(previousValue, currentFeature, featureIndex, multiFeatureIndex);\n });\n return previousValue;\n}\n\n/**\n * Callback for segmentEach\n *\n * @callback segmentEachCallback\n * @param {Feature<LineString>} currentSegment The current Segment being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n * @param {number} segmentIndex The current index of the Segment being processed.\n * @returns {void}\n */\n\n/**\n * Iterate over 2-vertex line segment in any GeoJSON object, similar to Array.forEach()\n * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON\n * @param {Function} callback a method that takes (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex)\n * @returns {void}\n * @example\n * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);\n *\n * // Iterate over GeoJSON by 2-vertex segments\n * turf.segmentEach(polygon, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n * //=currentSegment\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * //=segmentIndex\n * });\n *\n * // Calculate the total number of segments\n * var total = 0;\n * turf.segmentEach(polygon, function () {\n * total++;\n * });\n */\nfunction segmentEach(geojson, callback) {\n flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) {\n var segmentIndex = 0;\n\n // Exclude null Geometries\n if (!feature$$1.geometry) return;\n // (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n var type = feature$$1.geometry.type;\n if (type === 'Point' || type === 'MultiPoint') return;\n\n // Generate 2-vertex line segments\n var previousCoords;\n if (coordEach(feature$$1, function (currentCoord, coordIndex, featureIndexCoord, mutliPartIndexCoord, geometryIndex) {\n // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false`\n if (previousCoords === undefined) {\n previousCoords = currentCoord;\n return;\n }\n var currentSegment = lineString([previousCoords, currentCoord], feature$$1.properties);\n if (callback(currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) === false) return false;\n segmentIndex++;\n previousCoords = currentCoord;\n }) === false) return false;\n });\n}\n\n/**\n * Callback for segmentReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback segmentReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature<LineString>} currentSegment The current Segment being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed.\n * @param {number} geometryIndex The current index of the Geometry being processed.\n * @param {number} segmentIndex The current index of the Segment being processed.\n */\n\n/**\n * Reduce 2-vertex line segment in any GeoJSON object, similar to Array.reduce()\n * (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON\n * @param {Function} callback a method that takes (previousValue, currentSegment, currentIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {void}\n * @example\n * var polygon = turf.polygon([[[-50, 5], [-40, -10], [-50, -10], [-40, 5], [-50, 5]]]);\n *\n * // Iterate over GeoJSON by 2-vertex segments\n * turf.segmentReduce(polygon, function (previousSegment, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n * //= previousSegment\n * //= currentSegment\n * //= featureIndex\n * //= multiFeatureIndex\n * //= geometryIndex\n * //= segmentInex\n * return currentSegment\n * });\n *\n * // Calculate the total number of segments\n * var initialValue = 0\n * var total = turf.segmentReduce(polygon, function (previousValue) {\n * previousValue++;\n * return previousValue;\n * }, initialValue);\n */\nfunction segmentReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n var started = false;\n segmentEach(geojson, function (currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex) {\n if (started === false && initialValue === undefined) previousValue = currentSegment;\n else previousValue = callback(previousValue, currentSegment, featureIndex, multiFeatureIndex, geometryIndex, segmentIndex);\n started = true;\n });\n return previousValue;\n}\n\n/**\n * Callback for lineEach\n *\n * @callback lineEachCallback\n * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed\n * @param {number} featureIndex The current index of the Feature being processed\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed\n * @param {number} geometryIndex The current index of the Geometry being processed\n */\n\n/**\n * Iterate over line or ring coordinates in LineString, Polygon, MultiLineString, MultiPolygon Features or Geometries,\n * similar to Array.forEach.\n *\n * @name lineEach\n * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object\n * @param {Function} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @example\n * var multiLine = turf.multiLineString([\n * [[26, 37], [35, 45]],\n * [[36, 53], [38, 50], [41, 55]]\n * ]);\n *\n * turf.lineEach(multiLine, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=currentLine\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * });\n */\nfunction lineEach(geojson, callback) {\n // validation\n if (!geojson) throw new Error('geojson is required');\n\n flattenEach(geojson, function (feature$$1, featureIndex, multiFeatureIndex) {\n if (feature$$1.geometry === null) return;\n var type = feature$$1.geometry.type;\n var coords = feature$$1.geometry.coordinates;\n switch (type) {\n case 'LineString':\n if (callback(feature$$1, featureIndex, multiFeatureIndex, 0, 0) === false) return false;\n break;\n case 'Polygon':\n for (var geometryIndex = 0; geometryIndex < coords.length; geometryIndex++) {\n if (callback(lineString(coords[geometryIndex], feature$$1.properties), featureIndex, multiFeatureIndex, geometryIndex) === false) return false;\n }\n break;\n }\n });\n}\n\n/**\n * Callback for lineReduce\n *\n * The first time the callback function is called, the values provided as arguments depend\n * on whether the reduce method has an initialValue argument.\n *\n * If an initialValue is provided to the reduce method:\n * - The previousValue argument is initialValue.\n * - The currentValue argument is the value of the first element present in the array.\n *\n * If an initialValue is not provided:\n * - The previousValue argument is the value of the first element present in the array.\n * - The currentValue argument is the value of the second element present in the array.\n *\n * @callback lineReduceCallback\n * @param {*} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {Feature<LineString>} currentLine The current LineString|LinearRing being processed.\n * @param {number} featureIndex The current index of the Feature being processed\n * @param {number} multiFeatureIndex The current index of the Multi-Feature being processed\n * @param {number} geometryIndex The current index of the Geometry being processed\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @name lineReduce\n * @param {Geometry|Feature<LineString|Polygon|MultiLineString|MultiPolygon>} geojson object\n * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @param {*} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {*} The value that results from the reduction.\n * @example\n * var multiPoly = turf.multiPolygon([\n * turf.polygon([[[12,48],[2,41],[24,38],[12,48]], [[9,44],[13,41],[13,45],[9,44]]]),\n * turf.polygon([[[5, 5], [0, 0], [2, 2], [4, 4], [5, 5]]])\n * ]);\n *\n * turf.lineReduce(multiPoly, function (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n * //=previousValue\n * //=currentLine\n * //=featureIndex\n * //=multiFeatureIndex\n * //=geometryIndex\n * return currentLine\n * });\n */\nfunction lineReduce(geojson, callback, initialValue) {\n var previousValue = initialValue;\n lineEach(geojson, function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n if (featureIndex === 0 && initialValue === undefined) previousValue = currentLine;\n else previousValue = callback(previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex);\n });\n return previousValue;\n}\n\n/**\n * Finds a particular 2-vertex LineString Segment from a GeoJSON using `@turf/meta` indexes.\n *\n * Negative indexes are permitted.\n * Point & MultiPoint will always return null.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry\n * @param {Object} [options={}] Optional parameters\n * @param {number} [options.featureIndex=0] Feature Index\n * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index\n * @param {number} [options.geometryIndex=0] Geometry Index\n * @param {number} [options.segmentIndex=0] Segment Index\n * @param {Object} [options.properties={}] Translate Properties to output LineString\n * @param {BBox} [options.bbox={}] Translate BBox to output LineString\n * @param {number|string} [options.id={}] Translate Id to output LineString\n * @returns {Feature<LineString>} 2-vertex GeoJSON Feature LineString\n * @example\n * var multiLine = turf.multiLineString([\n * [[10, 10], [50, 30], [30, 40]],\n * [[-10, -10], [-50, -30], [-30, -40]]\n * ]);\n *\n * // First Segment (defaults are 0)\n * turf.findSegment(multiLine);\n * // => Feature<LineString<[[10, 10], [50, 30]]>>\n *\n * // First Segment of 2nd Multi Feature\n * turf.findSegment(multiLine, {multiFeatureIndex: 1});\n * // => Feature<LineString<[[-10, -10], [-50, -30]]>>\n *\n * // Last Segment of Last Multi Feature\n * turf.findSegment(multiLine, {multiFeatureIndex: -1, segmentIndex: -1});\n * // => Feature<LineString<[[-50, -30], [-30, -40]]>>\n */\nfunction findSegment(geojson, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var featureIndex = options.featureIndex || 0;\n var multiFeatureIndex = options.multiFeatureIndex || 0;\n var geometryIndex = options.geometryIndex || 0;\n var segmentIndex = options.segmentIndex || 0;\n\n // Find FeatureIndex\n var properties = options.properties;\n var geometry;\n\n switch (geojson.type) {\n case 'FeatureCollection':\n if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;\n properties = properties || geojson.features[featureIndex].properties;\n geometry = geojson.features[featureIndex].geometry;\n break;\n case 'Feature':\n properties = properties || geojson.properties;\n geometry = geojson.geometry;\n break;\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon':\n geometry = geojson;\n break;\n default:\n throw new Error('geojson is invalid');\n }\n\n // Find SegmentIndex\n if (geometry === null) return null;\n var coords = geometry.coordinates;\n switch (geometry.type) {\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n if (segmentIndex < 0) segmentIndex = coords.length + segmentIndex - 1;\n return lineString([coords[segmentIndex], coords[segmentIndex + 1]], properties, options);\n case 'Polygon':\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (segmentIndex < 0) segmentIndex = coords[geometryIndex].length + segmentIndex - 1;\n return lineString([coords[geometryIndex][segmentIndex], coords[geometryIndex][segmentIndex + 1]], properties, options);\n case 'MultiLineString':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1;\n return lineString([coords[multiFeatureIndex][segmentIndex], coords[multiFeatureIndex][segmentIndex + 1]], properties, options);\n case 'MultiPolygon':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (segmentIndex < 0) segmentIndex = coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1;\n return lineString([coords[multiFeatureIndex][geometryIndex][segmentIndex], coords[multiFeatureIndex][geometryIndex][segmentIndex + 1]], properties, options);\n }\n throw new Error('geojson is invalid');\n}\n\n/**\n * Finds a particular Point from a GeoJSON using `@turf/meta` indexes.\n *\n * Negative indexes are permitted.\n *\n * @param {FeatureCollection|Feature|Geometry} geojson Any GeoJSON Feature or Geometry\n * @param {Object} [options={}] Optional parameters\n * @param {number} [options.featureIndex=0] Feature Index\n * @param {number} [options.multiFeatureIndex=0] Multi-Feature Index\n * @param {number} [options.geometryIndex=0] Geometry Index\n * @param {number} [options.coordIndex=0] Coord Index\n * @param {Object} [options.properties={}] Translate Properties to output Point\n * @param {BBox} [options.bbox={}] Translate BBox to output Point\n * @param {number|string} [options.id={}] Translate Id to output Point\n * @returns {Feature<Point>} 2-vertex GeoJSON Feature Point\n * @example\n * var multiLine = turf.multiLineString([\n * [[10, 10], [50, 30], [30, 40]],\n * [[-10, -10], [-50, -30], [-30, -40]]\n * ]);\n *\n * // First Segment (defaults are 0)\n * turf.findPoint(multiLine);\n * // => Feature<Point<[10, 10]>>\n *\n * // First Segment of the 2nd Multi-Feature\n * turf.findPoint(multiLine, {multiFeatureIndex: 1});\n * // => Feature<Point<[-10, -10]>>\n *\n * // Last Segment of last Multi-Feature\n * turf.findPoint(multiLine, {multiFeatureIndex: -1, coordIndex: -1});\n * // => Feature<Point<[-30, -40]>>\n */\nfunction findPoint(geojson, options) {\n // Optional Parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var featureIndex = options.featureIndex || 0;\n var multiFeatureIndex = options.multiFeatureIndex || 0;\n var geometryIndex = options.geometryIndex || 0;\n var coordIndex = options.coordIndex || 0;\n\n // Find FeatureIndex\n var properties = options.properties;\n var geometry;\n\n switch (geojson.type) {\n case 'FeatureCollection':\n if (featureIndex < 0) featureIndex = geojson.features.length + featureIndex;\n properties = properties || geojson.features[featureIndex].properties;\n geometry = geojson.features[featureIndex].geometry;\n break;\n case 'Feature':\n properties = properties || geojson.properties;\n geometry = geojson.geometry;\n break;\n case 'Point':\n case 'MultiPoint':\n return null;\n case 'LineString':\n case 'Polygon':\n case 'MultiLineString':\n case 'MultiPolygon':\n geometry = geojson;\n break;\n default:\n throw new Error('geojson is invalid');\n }\n\n // Find Coord Index\n if (geometry === null) return null;\n var coords = geometry.coordinates;\n switch (geometry.type) {\n case 'Point':\n return point(coords, properties, options);\n case 'MultiPoint':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n return point(coords[multiFeatureIndex], properties, options);\n case 'LineString':\n if (coordIndex < 0) coordIndex = coords.length + coordIndex;\n return point(coords[coordIndex], properties, options);\n case 'Polygon':\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (coordIndex < 0) coordIndex = coords[geometryIndex].length + coordIndex;\n return point(coords[geometryIndex][coordIndex], properties, options);\n case 'MultiLineString':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (coordIndex < 0) coordIndex = coords[multiFeatureIndex].length + coordIndex;\n return point(coords[multiFeatureIndex][coordIndex], properties, options);\n case 'MultiPolygon':\n if (multiFeatureIndex < 0) multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0) geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (coordIndex < 0) coordIndex = coords[multiFeatureIndex][geometryIndex].length - coordIndex;\n return point(coords[multiFeatureIndex][geometryIndex][coordIndex], properties, options);\n }\n throw new Error('geojson is invalid');\n}\n\nexport { coordEach, coordReduce, propEach, propReduce, featureEach, featureReduce, coordAll, geomEach, geomReduce, flattenEach, flattenReduce, segmentEach, segmentReduce, lineEach, lineReduce, findSegment, findPoint };\n","import { coordEach } from '@turf/meta';\nimport { point } from '@turf/helpers';\n\n/**\n * Takes one or more features and calculates the centroid using the mean of all vertices.\n * This lessens the effect of small islands and artifacts when calculating the centroid of a set of polygons.\n *\n * @name centroid\n * @param {GeoJSON} geojson GeoJSON to be centered\n * @param {Object} [properties={}] an Object that is used as the {@link Feature}'s properties\n * @returns {Feature<Point>} the centroid of the input features\n * @example\n * var polygon = turf.polygon([[[-81, 41], [-88, 36], [-84, 31], [-80, 33], [-77, 39], [-81, 41]]]);\n *\n * var centroid = turf.centroid(polygon);\n *\n * //addToMap\n * var addToMap = [polygon, centroid]\n */\nfunction centroid(geojson, properties) {\n var xSum = 0;\n var ySum = 0;\n var len = 0;\n coordEach(geojson, function (coord) {\n xSum += coord[0];\n ySum += coord[1];\n len++;\n }, true);\n return point([xSum / len, ySum / len], properties);\n}\n\nexport default centroid;\n","import { isNumber } from '@turf/helpers';\n\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @name getCoord\n * @param {Array<number>|Geometry<Point>|Feature<Point>} coord GeoJSON Point or an Array of numbers\n * @returns {Array<number>} coordinates\n * @example\n * var pt = turf.point([10, 10]);\n *\n * var coord = turf.getCoord(pt);\n * //= [10, 10]\n */\nfunction getCoord(coord) {\n if (!coord) throw new Error('coord is required');\n if (coord.type === 'Feature' && coord.geometry !== null && coord.geometry.type === 'Point') return coord.geometry.coordinates;\n if (coord.type === 'Point') return coord.coordinates;\n if (Array.isArray(coord) && coord.length >= 2 && coord[0].length === undefined && coord[1].length === undefined) return coord;\n\n throw new Error('coord must be GeoJSON Point or an Array of numbers');\n}\n\n/**\n * Unwrap coordinates from a Feature, Geometry Object or an Array\n *\n * @name getCoords\n * @param {Array<any>|Geometry|Feature} coords Feature, Geometry Object or an Array\n * @returns {Array<any>} coordinates\n * @example\n * var poly = turf.polygon([[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]);\n *\n * var coords = turf.getCoords(poly);\n * //= [[[119.32, -8.7], [119.55, -8.69], [119.51, -8.54], [119.32, -8.7]]]\n */\nfunction getCoords(coords) {\n if (!coords) throw new Error('coords is required');\n\n // Feature\n if (coords.type === 'Feature' && coords.geometry !== null) return coords.geometry.coordinates;\n\n // Geometry\n if (coords.coordinates) return coords.coordinates;\n\n // Array of numbers\n if (Array.isArray(coords)) return coords;\n\n throw new Error('coords must be GeoJSON Feature, Geometry Object or an Array');\n}\n\n/**\n * Checks if coordinates contains a number\n *\n * @name containsNumber\n * @param {Array<any>} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nfunction containsNumber(coordinates) {\n if (coordinates.length > 1 && isNumber(coordinates[0]) && isNumber(coordinates[1])) {\n return true;\n }\n\n if (Array.isArray(coordinates[0]) && coordinates[0].length) {\n return containsNumber(coordinates[0]);\n }\n throw new Error('coordinates must only contain numbers');\n}\n\n/**\n * Enforce expectations about types of GeoJSON objects for Turf.\n *\n * @name geojsonType\n * @param {GeoJSON} value any GeoJSON object\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction geojsonType(value, type, name) {\n if (!type || !name) throw new Error('type and name required');\n\n if (!value || value.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + value.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link Feature} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name featureOf\n * @param {Feature} feature a feature with an expected geometry type\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} error if value is not the expected type.\n */\nfunction featureOf(feature, type, name) {\n if (!feature) throw new Error('No feature passed');\n if (!name) throw new Error('.featureOf() requires a name');\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n}\n\n/**\n * Enforce expectations about types of {@link FeatureCollection} inputs for Turf.\n * Internally this uses {@link geojsonType} to judge geometry types.\n *\n * @name collectionOf\n * @param {FeatureCollection} featureCollection a FeatureCollection for which features will be judged\n * @param {string} type expected GeoJSON type\n * @param {string} name name of calling function\n * @throws {Error} if value is not the expected type.\n */\nfunction collectionOf(featureCollection, type, name) {\n if (!featureCollection) throw new Error('No featureCollection passed');\n if (!name) throw new Error('.collectionOf() requires a name');\n if (!featureCollection || featureCollection.type !== 'FeatureCollection') {\n throw new Error('Invalid input to ' + name + ', FeatureCollection required');\n }\n for (var i = 0; i < featureCollection.features.length; i++) {\n var feature = featureCollection.features[i];\n if (!feature || feature.type !== 'Feature' || !feature.geometry) {\n throw new Error('Invalid input to ' + name + ', Feature with geometry required');\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error('Invalid input to ' + name + ': must be a ' + type + ', given ' + feature.geometry.type);\n }\n }\n}\n\n/**\n * Get Geometry from Feature or Geometry Object\n *\n * @param {Feature|Geometry} geojson GeoJSON Feature or Geometry Object\n * @returns {Geometry|null} GeoJSON Geometry Object\n * @throws {Error} if geojson is not a Feature or Geometry Object\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getGeom(point)\n * //={\"type\": \"Point\", \"coordinates\": [110, 40]}\n */\nfunction getGeom(geojson) {\n if (!geojson) throw new Error('geojson is required');\n if (geojson.geometry !== undefined) return geojson.geometry;\n if (geojson.coordinates || geojson.geometries) return geojson;\n throw new Error('geojson must be a valid Feature or Geometry Object');\n}\n\n/**\n * Get Geometry Type from Feature or Geometry Object\n *\n * @throws {Error} **DEPRECATED** in v5.0.0 in favor of getType\n */\nfunction getGeomType() {\n throw new Error('invariant.getGeomType has been deprecated in v5.0 in favor of invariant.getType');\n}\n\n/**\n * Get GeoJSON object's type, Geometry type is prioritize.\n *\n * @param {GeoJSON} geojson GeoJSON object\n * @param {string} [name=\"geojson\"] name of the variable to display in error message\n * @returns {string} GeoJSON type\n * @example\n * var point = {\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [110, 40]\n * }\n * }\n * var geom = turf.getType(point)\n * //=\"Point\"\n */\nfunction getType(geojson, name) {\n if (!geojson) throw new Error((name || 'geojson') + ' is required');\n // GeoJSON Feature & GeometryCollection\n if (geojson.geometry && geojson.geometry.type) return geojson.geometry.type;\n // GeoJSON Geometry & FeatureCollection\n if (geojson.type) return geojson.type;\n throw new Error((name || 'geojson') + ' is invalid');\n}\n\nexport { getCoord, getCoords, containsNumber, geojsonType, featureOf, collectionOf, getGeom, getGeomType, getType };\n","import clone from '@turf/clone';\nimport center from '@turf/center';\nimport centroid from '@turf/centroid';\nimport turfBBox from '@turf/bbox';\nimport rhumbBearing from '@turf/rhumb-bearing';\nimport rhumbDistance from '@turf/rhumb-distance';\nimport rhumbDestination from '@turf/rhumb-destination';\nimport { coordEach, featureEach } from '@turf/meta';\nimport { isObject, point } from '@turf/helpers';\nimport { getCoord, getCoords, getType } from '@turf/invariant';\n\n/**\n * Scale a GeoJSON from a given point by a factor of scaling (ex: factor=2 would make the GeoJSON 200% larger).\n * If a FeatureCollection is provided, the origin point will be calculated based on each individual Feature.\n *\n * @name transformScale\n * @param {GeoJSON} geojson GeoJSON to be scaled\n * @param {number} factor of scaling, positive or negative values greater than 0\n * @param {Object} [options={}] Optional parameters\n * @param {string|Coord} [options.origin='centroid'] Point from which the scaling will occur (string options: sw/se/nw/ne/center/centroid)\n * @param {boolean} [options.mutate=false] allows GeoJSON input to be mutated (significant performance increase if true)\n * @returns {GeoJSON} scaled GeoJSON\n * @example\n * var poly = turf.polygon([[[0,29],[3.5,29],[2.5,32],[0,29]]]);\n * var scaledPoly = turf.transformScale(poly, 3);\n *\n * //addToMap\n * var addToMap = [poly, scaledPoly];\n * scaledPoly.properties = {stroke: '#F00', 'stroke-width': 4};\n */\nfunction transformScale(geojson, factor, options) {\n // Optional parameters\n options = options || {};\n if (!isObject(options)) throw new Error('options is invalid');\n var origin = options.origin;\n var mutate = options.mutate;\n\n // Input validation\n if (!geojson) throw new Error('geojson required');\n if (typeof factor !== 'number' || factor === 0) throw new Error('invalid factor');\n var originIsPoint = Array.isArray(origin) || typeof origin === 'object';\n\n // Clone geojson to avoid side effects\n if (mutate !== true) geojson = clone(geojson);\n\n // Scale each Feature separately\n if (geojson.type === 'FeatureCollection' && !originIsPoint) {\n featureEach(geojson, function (feature, index) {\n geojson.features[index] = scale(feature, factor, origin);\n });\n return geojson;\n }\n // Scale Feature/Geometry\n return scale(geojson, factor, origin);\n}\n\n/**\n * Scale Feature/Geometry\n *\n * @private\n * @param {Feature|Geometry} feature GeoJSON Feature/Geometry\n * @param {number} factor of scaling, positive or negative values greater than 0\n * @param {string|Coord} [origin=\"centroid\"] Point from which the scaling will occur (string options: sw/se/nw/ne/center/centroid)\n * @returns {Feature|Geometry} scaled GeoJSON Feature/Geometry\n */\nfunction scale(feature, factor, origin) {\n // Default params\n var isPoint = getType(feature) === 'Point';\n origin = defineOrigin(feature, origin);\n\n // Shortcut no-scaling\n if (factor === 1 || isPoint) return feature;\n\n // Scale each coordinate\n coordEach(feature, function (coord) {\n var originalDistance = rhumbDistance(origin, coord);\n var bearing = rhumbBearing(origin, coord);\n var newDistance = originalDistance * factor;\n var newCoord = getCoords(rhumbDestination(origin, newDistance, bearing));\n coord[0] = newCoord[0];\n coord[1] = newCoord[1];\n if (coord.length === 3) coord[2] *= factor;\n });\n\n return feature;\n}\n\n/**\n * Define Origin\n *\n * @private\n * @param {GeoJSON} geojson GeoJSON\n * @param {string|Coord} origin sw/se/nw/ne/center/centroid\n * @returns {Feature<Point>} Point origin\n */\nfunction defineOrigin(geojson, origin) {\n // Default params\n if (origin === undefined || origin === null) origin = 'centroid';\n\n // Input Coord\n if (Array.isArray(origin) || typeof origin === 'object') return getCoord(origin);\n\n // Define BBox\n var bbox = (geojson.bbox) ? geojson.bbox : turfBBox(geojson);\n var west = bbox[0];\n var south = bbox[1];\n var east = bbox[2];\n var north = bbox[3];\n\n switch (origin) {\n case 'sw':\n case 'southwest':\n case 'westsouth':\n case 'bottomleft':\n return point([west, south]);\n case 'se':\n case 'southeast':\n case 'eastsouth':\n case 'bottomright':\n return point([east, south]);\n case 'nw':\n case 'northwest':\n case 'westnorth':\n case 'topleft':\n return point([west, north]);\n case 'ne':\n case 'northeast':\n case 'eastnorth':\n case 'topright':\n return point([east, north]);\n case 'center':\n return center(geojson);\n case undefined:\n case null:\n case 'centroid':\n return centroid(geojson);\n default:\n throw new Error('invalid origin');\n }\n}\n\nexport default transformScale;\n","var img = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAYAAAByDd+UAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAA1pJREFUeNrElk9IVFEUxs+89yYoDAumxUgkoYIDZfaXCqfA3GSBi8poEYWzjVrUJiqiJFoJZUEQEYYRBAaFpIsgq5F0UThYZJSLdKEtgpRSQd/M6zvXe8c743vznhs78GOGmXfPd+49551zQ47j0BKtGqyV31Pg95JWs6APO8AdMOC42wToBAlg+fkLaTuMgFMgDpLgLbgKDucEOPmdnLm/4rtRXEEULtL/HgLPwBWvDSpBFhsE0UVPwHl65CWlR7uF2CKDoBndR0ZpPRmRrerXbnAWDHsJNoPLmfF3cN5NVqyJQog+PfyU7K8PhWgQY0Fr+yUKrRJxz4Bd4LOb4Buwfy55hjK/BsgsP07OxDfxPfsgnBgl2EkENRNePX+84pkUcaD6jq2qc2RuqFeiVfpOXQVzIoKQiR1LB+6FNz1O9mBrjjDvVK7pA3uzp1DoiPhYV9S26dE+BkdBreQC6OWgwrtvChFl9uBtlfM9MmX+gsa6bWQjj3LhSvBIVmGPpEVWNQvPcGBZUeSdRaUdCCTIRZNG0aTHskcV93i0RRaIEOUaYOP0aLusFkftV3miWNZUkNZZvIyr8STosCqbyJkapxAKiNMi85jSO02z429jIBKgMz1xWZtQ/+sPsmjS5eEfoD2gmOI8eA7adLH81rYsZ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9DC9Z/H27D5NdBg5Fii+pBBKggBWE4+POV4c/1ubBqw5KYaoJQPvoAxPw/t7jD6h5UVwJLcVaLdhBzIxAHUOIjcPHPZjuFgQFRkEJcyK/KwKKZRLVqQgZWlYNS24/NbuBqAlSlI1Xlx6hVqKJY9ut4BcntBVJKb7hl5LSAyCm9i5EakL2kaAQIMAAP/aLE8VYEBwAAAABJRU5ErkJggg==\";\n export default img;","import * as Constants from '../constants';\nimport doubleClickZoom from '../lib/double_click_zoom';\nimport createSupplementaryPoints from '../lib/create_supplementary_points';\nimport * as CommonSelectors from '../lib/common_selectors';\nimport moveFeatures from '../lib/move_features';\nimport { SRCenter } from '../lib/SRCenter';\n\nimport { lineString, point } from '@turf/helpers';\nimport bearing from '@turf/bearing';\nimport center from '@turf/center';\nimport midpoint from '@turf/midpoint';\nimport distance from '@turf/distance';\nimport destination from '@turf/destination';\nimport transformRotate from '@turf/transform-rotate';\nimport transformScale from '@turf/transform-scale';\nimport rotate from \"../../src/modes/img/rotate.png\";\nimport scale from \"../../src/modes/img/scale.png\";\n// const rotate = require('./img/rotate.png');\n// const scale = require('./img/scale.png');\n\nconst SRMode = {}; //scale rotate mode\n\nfunction parseSRCenter(value, defaultSRCenter = SRCenter.Center) {\n if (value == undefined || value == null) return defaultSRCenter;\n \n if (value === SRCenter.Center || value === SRCenter.Opposite) return value;\n \n if (value == 'center') return SRCenter.Center;\n \n if (value == 'opposite') return SRCenter.Opposite;\n \n throw Error('Invalid SRCenter: ' + value);\n }\n \n /*\n opts = {\n featureId: ...,\n \n canScale: default true,\n canRotate: default true,\n \n rotatePivot: default 'center' or 'opposite',\n scaleCenter: default 'center' or 'opposite',\n \n canSelectFeatures: default true, // can exit to simple_select mode\n }\n */\n SRMode.onSetup = function (opts) {\n const featureId = this.getSelected()[0].id;\n \n const feature = this.getFeature(featureId);\n \n if (!feature) {\n throw new Error('You must provide a valid featureId to enter SRMode');\n }\n \n if (\n feature.type === Constants.geojsonTypes.POINT ||\n feature.type === Constants.geojsonTypes.MULTI_POINT\n ) {\n throw new TypeError('SRMode can not handle points');\n }\n // if (\n // feature.coordinates === undefined ||\n // feature.coordinates.length != 1 ||\n // feature.coordinates[0].length <= 2\n // ) {\n // throw new TypeError('SRMode can only handle polygons');\n // }\n \n const state = {\n featureId,\n feature,\n \n canTrash: opts.canTrash != undefined ? opts.canTrash : true,\n \n canScale: opts.canScale != undefined ? opts.canScale : true,\n canRotate: opts.canRotate != undefined ? opts.canRotate : true,\n \n singleRotationPoint:\n opts.singleRotationPoint != undefined ? opts.singleRotationPoint : false,\n rotationPointRadius:\n opts.rotationPointRadius != undefined ? opts.rotationPointRadius : 1.0,\n \n rotatePivot: parseSRCenter(opts.rotatePivot, SRCenter.Center),\n scaleCenter: parseSRCenter(opts.scaleCenter, SRCenter.Center),\n \n canSelectFeatures:\n opts.canSelectFeatures != undefined ? opts.canSelectFeatures : true,\n // selectedFeatureMode: opts.selectedFeatureMode != undefined ? opts.selectedFeatureMode : 'simple_select',\n \n dragMoveLocation: opts.startPos || null,\n dragMoving: false,\n canDragMove: false,\n selectedCoordPaths: opts.coordPath ? [opts.coordPath] : [],\n };\n \n if (!(state.canRotate || state.canScale)) {\n console.warn('Non of canScale or canRotate is true');\n }\n \n this.setSelectedCoordinates(\n this.pathsToCoordinates(featureId, state.selectedCoordPaths)\n );\n this.setSelected(featureId);\n doubleClickZoom.disable(this);\n \n this.setActionableState({\n combineFeatures: false,\n uncombineFeatures: false,\n trash: state.canTrash,\n });\n \n var _this = this;\n\n //\n // const img_rotate = new Image();\n // img_rotate.src = \"./img/rotate.png\";\n // const img_scale = new Image();\n // img_scale.src = \"./img/scale.png\";\n\n this.map.loadImage(rotate, function (error, image) {\n if (error) throw error;\n if (!_this.map.getImage('rotate')) _this.map.addImage('rotate', image);\n });\n this.map.loadImage(scale, function (error, image) {\n if (error) throw error;\n if (!_this.map.getImage('scale')) _this.map.addImage('scale', image);\n });\n \n return state;\n };\n \n SRMode.toDisplayFeatures = function (state, geojson, push) {\n if (state.featureId === geojson.properties.id) {\n geojson.properties.active = Constants.activeStates.ACTIVE;\n push(geojson);\n \n var suppPoints = createSupplementaryPoints(geojson, {\n map: this.map,\n midpoints: false,\n selectedPaths: state.selectedCoordPaths,\n });\n \n if (state.canScale) {\n this.computeBisectrix(suppPoints);\n suppPoints.forEach(push);\n }\n \n if (state.canRotate) {\n var rotPoints = this.createRotationPoints(state, geojson, suppPoints);\n rotPoints.forEach(push);\n }\n } else {\n geojson.properties.active = Constants.activeStates.INACTIVE;\n push(geojson);\n }\n \n // this.fireActionable(state);\n this.setActionableState({\n combineFeatures: false,\n uncombineFeatures: false,\n trash: state.canTrash,\n });\n \n // this.fireUpdate();\n };\n \n SRMode.onStop = function () {\n doubleClickZoom.enable(this);\n this.clearSelectedCoordinates();\n };\n \n // TODO why I need this?\n SRMode.pathsToCoordinates = function (featureId, paths) {\n return paths.map((coord_path) => {\n return { feature_id: featureId, coord_path };\n });\n };\n \n SRMode.computeBisectrix = function (points) {\n for (var i1 = 0; i1 < points.length; i1++) {\n var i0 = (i1 - 1 + points.length) % points.length;\n var i2 = (i1 + 1) % points.length;\n \n var l1 = lineString([\n points[i0].geometry.coordinates,\n points[i1].geometry.coordinates,\n ]);\n var l2 = lineString([\n points[i1].geometry.coordinates,\n points[i2].geometry.coordinates,\n ]);\n var a1 = bearing(\n points[i0].geometry.coordinates,\n points[i1].geometry.coordinates\n );\n var a2 = bearing(\n points[i2].geometry.coordinates,\n points[i1].geometry.coordinates\n );\n \n var a = (a1 + a2) / 2.0;\n \n if (a < 0.0) a += 360;\n if (a > 360) a -= 360;\n \n points[i1].properties.heading = a;\n }\n };\n \n SRMode._createRotationPoint = function (\n rotationWidgets,\n featureId,\n v1,\n v2,\n rotCenter,\n radiusScale\n ) {\n var cR0 = midpoint(v1, v2).geometry.coordinates;\n var heading = bearing(rotCenter, cR0);\n var distance0 = distance(rotCenter, cR0);\n var distance1 = radiusScale * distance0; // TODO depends on map scale\n var cR1 = destination(rotCenter, distance1, heading, {}).geometry.coordinates;\n \n rotationWidgets.push({\n type: Constants.geojsonTypes.FEATURE,\n properties: {\n meta: Constants.meta.MIDPOINT,\n icon: 'rotate',\n parent: featureId,\n lng: cR1[0],\n lat: cR1[1],\n coord_path: v1.properties.coord_path,\n heading: heading,\n },\n geometry: {\n type: Constants.geojsonTypes.POINT,\n coordinates: cR1,\n },\n });\n };\n \n SRMode.createRotationPoints = function (state, geojson, suppPoints) {\n const { type, coordinates } = geojson.geometry;\n const featureId = geojson.properties && geojson.properties.id;\n \n let rotationWidgets = [];\n if (\n type === Constants.geojsonTypes.POINT ||\n type === Constants.geojsonTypes.MULTI_POINT\n ) {\n return;\n }\n \n var corners = suppPoints.slice(0);\n corners[corners.length] = corners[0];\n \n var v1 = null;\n \n var rotCenter = this.computeRotationCenter(state, geojson);\n \n if (state.singleRotationPoint) {\n this._createRotationPoint(\n rotationWidgets,\n featureId,\n corners[0],\n corners[1],\n rotCenter,\n state.rotationPointRadius\n );\n } else {\n corners.forEach((v2) => {\n if (v1 != null) {\n this._createRotationPoint(\n rotationWidgets,\n featureId,\n v1,\n v2,\n rotCenter,\n state.rotationPointRadius\n );\n }\n \n v1 = v2;\n });\n }\n return rotationWidgets;\n };\n \n SRMode.startDragging = function (state, e) {\n this.map.dragPan.disable();\n state.canDragMove = true;\n state.dragMoveLocation = e.lngLat;\n };\n \n SRMode.stopDragging = function (state) {\n this.map.dragPan.enable();\n state.dragMoving = false;\n state.canDragMove = false;\n state.dragMoveLocation = null;\n };\n \n const isRotatePoint = CommonSelectors.isOfMetaType(Constants.meta.MIDPOINT);\n const isVertex = CommonSelectors.isOfMetaType(Constants.meta.VERTEX);\n \n SRMode.onTouchStart = SRMode.onMouseDown = function (state, e) {\n if (isVertex(e)) return this.onVertex(state, e);\n if (isRotatePoint(e)) return this.onRotatePoint(state, e);\n if (CommonSelectors.isActiveFeature(e)) return this.onFeature(state, e);\n // if (isMidpoint(e)) return this.onMidpoint(state, e);\n };\n \n const TxMode = {\n Scale: 1,\n Rotate: 2,\n };\n \n SRMode.onVertex = function (state, e) {\n // convert internal MapboxDraw feature to valid GeoJSON:\n this.computeAxes(state, state.feature.toGeoJSON());\n \n this.startDragging(state, e);\n const about = e.featureTarget.properties;\n state.selectedCoordPaths = [about.coord_path];\n state.txMode = TxMode.Scale;\n };\n \n SRMode.onRotatePoint = function (state, e) {\n // convert internal MapboxDraw feature to valid GeoJSON:\n this.computeAxes(state, state.feature.toGeoJSON());\n \n this.startDragging(state, e);\n const about = e.featureTarget.properties;\n state.selectedCoordPaths = [about.coord_path];\n state.txMode = TxMode.Rotate;\n };\n \n SRMode.onFeature = function (state, e) {\n state.selectedCoordPaths = [];\n this.startDragging(state, e);\n };\n \n SRMode.coordinateIndex = function (coordPaths) {\n if (coordPaths.length >= 1) {\n var parts = coordPaths[0].split('.');\n return parseInt(parts[parts.length - 1]);\n } else {\n return 0;\n }\n };\n \n SRMode.computeRotationCenter = function (state, polygon) {\n var center0 = center(polygon);\n return center0;\n };\n \n SRMode.computeAxes = function (state, polygon) {\n // TODO check min 3 points\n const center0 = this.computeRotationCenter(state, polygon);\n let corners;\n if (polygon.geometry.type === Constants.geojsonTypes.POLYGON)\n corners = polygon.geometry.coordinates[0].slice(0);\n else if (polygon.geometry.type === Constants.geojsonTypes.MULTI_POLYGON) {\n let temp = [];\n polygon.geometry.coordinates.forEach((c) => {\n c.forEach((c2) => {\n c2.forEach((c3) => {\n temp.push(c3);\n });\n });\n });\n corners = temp;\n } else if (polygon.geometry.type === Constants.geojsonTypes.LINE_STRING)\n corners = polygon.geometry.coordinates;\n else if (polygon.geometry.type === Constants.geojsonTypes.MULTI_LINE_STRING) {\n let temp = [];\n polygon.geometry.coordinates.forEach((c) => {\n c.forEach((c2) => {\n temp.push(c2);\n });\n });\n corners = temp;\n }\n \n const n = corners.length - 1;\n const iHalf = Math.floor(n / 2);\n \n var rotateCenters = [];\n var headings = [];\n \n for (var i1 = 0; i1 < n; i1++) {\n var i0 = i1 - 1;\n if (i0 < 0) i0 += n;\n \n const c0 = corners[i0];\n const c1 = corners[i1];\n const rotPoint = midpoint(point(c0), point(c1));\n \n var rotCenter = center0;\n if (SRCenter.Opposite === state.rotatePivot) {\n var i3 = (i1 + iHalf) % n; // opposite corner\n var i2 = i3 - 1;\n if (i2 < 0) i2 += n;\n \n const c2 = corners[i2];\n const c3 = corners[i3];\n rotCenter = midpoint(point(c2), point(c3));\n }\n \n rotateCenters[i1] = rotCenter.geometry.coordinates;\n headings[i1] = bearing(rotCenter, rotPoint);\n }\n \n state.rotation = {\n feature0: polygon, // initial feature state\n centers: rotateCenters,\n headings: headings, // rotation start heading for each point\n };\n \n // compute current distances from centers for scaling\n \n var scaleCenters = [];\n var distances = [];\n for (var i = 0; i < n; i++) {\n var c1 = corners[i];\n var c0 = center0.geometry.coordinates;\n if (SRCenter.Opposite === state.scaleCenter) {\n var i2 = (i + iHalf) % n; // opposite corner\n c0 = corners[i2];\n }\n scaleCenters[i] = c0;\n distances[i] = distance(point(c0), point(c1), { units: 'meters' });\n }\n \n state.scaling = {\n feature0: polygon, // initial feature state\n centers: scaleCenters,\n distances: distances,\n };\n };\n \n SRMode.onDrag = function (state, e) {\n if (state.canDragMove !== true) return;\n state.dragMoving = true;\n e.originalEvent.stopPropagation();\n \n const delta = {\n lng: e.lngLat.lng - state.dragMoveLocation.lng,\n lat: e.lngLat.lat - state.dragMoveLocation.lat,\n };\n if (state.selectedCoordPaths.length > 0 && state.txMode) {\n switch (state.txMode) {\n case TxMode.Rotate:\n this.dragRotatePoint(state, e, delta);\n break;\n case TxMode.Scale:\n this.dragScalePoint(state, e, delta);\n break;\n }\n } else {\n this.dragFeature(state, e, delta);\n }\n \n state.dragMoveLocation = e.lngLat;\n };\n \n SRMode.dragRotatePoint = function (state, e, delta) {\n if (state.rotation === undefined || state.rotation == null) {\n throw new Error('state.rotation required');\n }\n \n var polygon = state.feature.toGeoJSON();\n var m1 = point([e.lngLat.lng, e.lngLat.lat]);\n \n const n = state.rotation.centers.length;\n var cIdx = (this.coordinateIndex(state.selectedCoordPaths) + 1) % n;\n // TODO validate cIdx\n var cCenter = state.rotation.centers[cIdx];\n var center = point(cCenter);\n \n var heading1 = bearing(center, m1);\n \n var heading0 = state.rotation.headings[cIdx];\n var rotateAngle = heading1 - heading0; // in degrees\n if (CommonSelectors.isShiftDown(e)) {\n rotateAngle = 5.0 * Math.round(rotateAngle / 5.0);\n }\n \n var rotatedFeature = transformRotate(state.rotation.feature0, rotateAngle, {\n pivot: center,\n mutate: false,\n });\n \n state.feature.incomingCoords(rotatedFeature.geometry.coordinates);\n // TODO add option for this:\n this.fireUpdate();\n };\n \n SRMode.dragScalePoint = function (state, e, delta) {\n if (state.scaling === undefined || state.scaling == null) {\n throw new Error('state.scaling required');\n }\n \n var polygon = state.feature.toGeoJSON();\n \n var cIdx = this.coordinateIndex(state.selectedCoordPaths);\n // TODO validate cIdx\n \n var cCenter = state.scaling.centers[cIdx];\n var center = point(cCenter);\n var m1 = point([e.lngLat.lng, e.lngLat.lat]);\n \n var dist = distance(center, m1, { units: 'meters' });\n var scale = dist / state.scaling.distances[cIdx];\n \n if (CommonSelectors.isShiftDown(e)) {\n // TODO discrete scaling\n scale = 0.05 * Math.round(scale / 0.05);\n }\n \n var scaledFeature = transformScale(state.scaling.feature0, scale, {\n origin: cCenter,\n mutate: false,\n });\n \n state.feature.incomingCoords(scaledFeature.geometry.coordinates);\n // TODO add option for this:\n this.fireUpdate();\n };\n \n SRMode.dragFeature = function (state, e, delta) {\n moveFeatures(this.getSelected(), delta);\n state.dragMoveLocation = e.lngLat;\n // TODO add option for this:\n this.fireUpdate();\n };\n \n SRMode.fireUpdate = function () {\n this.map.fire(Constants.events.UPDATE, {\n action: Constants.updateActions.CHANGE_COORDINATES,\n features: this.getSelected().map((f) => f.toGeoJSON()),\n });\n };\n \n SRMode.onMouseOut = function (state) {\n // As soon as you mouse leaves the canvas, update the feature\n if (state.dragMoving) {\n this.fireUpdate();\n }\n };\n \n SRMode.onTouchEnd = SRMode.onMouseUp = function (state) {\n if (state.dragMoving) {\n this.fireUpdate();\n }\n this.stopDragging(state);\n };\n \n SRMode.clickActiveFeature = function (state) {\n state.selectedCoordPaths = [];\n this.clearSelectedCoordinates();\n state.feature.changed();\n };\n \n SRMode.onClick = function (state, e) {\n if (CommonSelectors.noTarget(e)) return this.clickNoTarget(state, e);\n if (CommonSelectors.isActiveFeature(e))\n return this.clickActiveFeature(state, e);\n if (CommonSelectors.isInactiveFeature(e)) return this.clickInactive(state, e);\n this.stopDragging(state);\n };\n \n SRMode.clickNoTarget = function (state, e) {\n if (state.canSelectFeatures){\n // activate 해제\n state.feature.ctx.ui.deactivateButtons();\n this.changeMode(Constants.modes.SIMPLE_SELECT);\n } \n };\n \n SRMode.clickInactive = function (state, e) {\n if (state.canSelectFeatures){\n // activate 해제\n state.feature.ctx.ui.deactivateButtons();\n this.changeMode(Constants.modes.SIMPLE_SELECT, {\n featureIds: [e.featureTarget.properties.id],\n });\n }\n };\n \n SRMode.onTrash = function () {\n this.deleteFeature(this.getSelectedIds());\n // this.fireActionable();\n };\n \n\n export default SRMode;","\nimport simple_select from './simple_select';\nimport direct_select from './direct_select';\nimport draw_point from './draw_point';\nimport draw_polygon from './draw_polygon';\nimport draw_line_string from './draw_line_string';\nimport SRMode from \"./SRMode\";\n\nexport default {\n simple_select,\n direct_select,\n draw_point,\n draw_polygon,\n draw_line_string,\n SRMode,\n};\n","export const SRStyle = [\n {\n id: 'gl-draw-polygon-fill-inactive',\n type: 'fill',\n filter: [\n 'all',\n ['==', 'active', 'false'],\n ['==', '$type', 'Polygon'],\n ['!=', 'user_type', 'overlay'],\n ['!=', 'mode', 'static'],\n ],\n paint: {\n 'fill-color': '#3bb2d0',\n 'fill-outline-color': '#3bb2d0',\n 'fill-opacity': 0.2,\n },\n },\n {\n id: 'gl-draw-polygon-fill-active',\n type: 'fill',\n filter: [\n 'all',\n ['==', 'active', 'true'],\n ['==', '$type', 'Polygon'],\n ['!=', 'user_type', 'overlay'],\n ],\n paint: {\n 'fill-color': '#fbb03b',\n 'fill-outline-color': '#fbb03b',\n 'fill-opacity': 0.2,\n },\n },\n \n {\n id: 'gl-draw-overlay-polygon-fill-inactive',\n type: 'fill',\n filter: [\n 'all',\n ['==', 'active', 'false'],\n ['==', '$type', 'Polygon'],\n ['==', 'user_type', 'overlay'],\n ['!=', 'mode', 'static'],\n ],\n paint: {\n 'fill-color': '#3bb2d0',\n 'fill-outline-color': '#3bb2d0',\n 'fill-opacity': 0.01,\n },\n },\n {\n id: 'gl-draw-overlay-polygon-fill-active',\n type: 'fill',\n filter: [\n 'all',\n ['==', 'active', 'true'],\n ['==', '$type', 'Polygon'],\n ['==', 'user_type', 'overlay'],\n ],\n paint: {\n 'fill-color': '#fbb03b',\n 'fill-outline-color': '#fbb03b',\n 'fill-opacity': 0.01,\n },\n },\n \n {\n id: 'gl-draw-polygon-stroke-inactive',\n type: 'line',\n filter: [\n 'all',\n ['==', 'active', 'false'],\n ['==', '$type', 'Polygon'],\n ['!=', 'user_type', 'overlay'],\n ['!=', 'mode', 'static'],\n ],\n layout: {\n 'line-cap': 'round',\n 'line-join': 'round',\n },\n paint: {\n 'line-color': '#3bb2d0',\n 'line-width': 2,\n },\n },\n \n {\n id: 'gl-draw-polygon-stroke-active',\n type: 'line',\n filter: ['all', ['==', 'active', 'true'], ['==', '$type', 'Polygon']],\n layout: {\n 'line-cap': 'round',\n 'line-join': 'round',\n },\n paint: {\n 'line-color': '#fbb03b',\n 'line-dasharray': [0.2, 2],\n 'line-width': 2,\n },\n },\n \n {\n id: 'gl-draw-polygon-midpoint',\n type: 'circle',\n filter: ['all', ['==', '$type', 'Point'], ['==', 'meta', 'midpoint']],\n paint: {\n 'circle-radius': 3,\n 'circle-color': '#fbb03b',\n },\n },\n \n {\n id: 'gl-draw-line-inactive',\n type: 'line',\n filter: [\n 'all',\n ['==', 'active', 'false'],\n ['==', '$type', 'LineString'],\n ['!=', 'mode', 'static'],\n ],\n layout: {\n 'line-cap': 'round',\n 'line-join': 'round',\n },\n paint: {\n 'line-color': '#3bb2d0',\n 'line-width': 2,\n },\n },\n {\n id: 'gl-draw-line-active',\n type: 'line',\n filter: ['all', ['==', '$type', 'LineString'], ['==', 'active', 'true']],\n layout: {\n 'line-cap': 'round',\n 'line-join': 'round',\n },\n paint: {\n 'line-color': '#fbb03b',\n 'line-dasharray': [0.2, 2],\n 'line-width': 2,\n },\n },\n {\n id: 'gl-draw-polygon-and-line-vertex-stroke-inactive',\n type: 'circle',\n filter: [\n 'all',\n ['==', 'meta', 'vertex'],\n ['==', '$type', 'Point'],\n ['!=', 'mode', 'static'],\n ],\n paint: {\n 'circle-radius': 4,\n 'circle-color': '#fff',\n },\n },\n {\n id: 'gl-draw-polygon-and-line-vertex-inactive',\n type: 'circle',\n filter: [\n 'all',\n ['==', 'meta', 'vertex'],\n ['==', '$type', 'Point'],\n ['!=', 'mode', 'static'],\n ],\n paint: {\n 'circle-radius': 2,\n 'circle-color': '#fbb03b',\n },\n },\n \n {\n id: 'gl-draw-polygon-and-line-vertex-scale-icon',\n type: 'symbol',\n filter: [\n 'all',\n ['==', 'meta', 'vertex'],\n ['==', '$type', 'Point'],\n ['!=', 'mode', 'static'],\n ['has', 'heading'],\n ],\n layout: {\n 'icon-image': 'scale',\n 'icon-allow-overlap': true,\n 'icon-ignore-placement': true,\n 'icon-rotation-alignment': 'map',\n 'icon-rotate': ['get', 'heading'],\n },\n paint: {\n 'icon-opacity': 1.0,\n 'icon-opacity-transition': {\n delay: 0,\n duration: 0,\n },\n },\n },\n \n {\n id: 'gl-draw-point-point-stroke-inactive',\n type: 'circle',\n filter: [\n 'all',\n ['==', 'active', 'false'],\n ['==', '$type', 'Point'],\n ['==', 'meta', 'feature'],\n ['!=', 'mode', 'static'],\n ],\n paint: {\n 'circle-radius': 5,\n 'circle-opacity': 1,\n 'circle-color': '#fff',\n },\n },\n {\n id: 'gl-draw-point-inactive',\n type: 'circle',\n filter: [\n 'all',\n ['==', 'active', 'false'],\n ['==', '$type', 'Point'],\n ['==', 'meta', 'feature'],\n ['!=', 'mode', 'static'],\n ],\n paint: {\n 'circle-radius': 3,\n 'circle-color': '#3bb2d0',\n },\n },\n {\n id: 'gl-draw-point-stroke-active',\n type: 'circle',\n filter: [\n 'all',\n ['==', '$type', 'Point'],\n ['==', 'active', 'true'],\n ['!=', 'meta', 'midpoint'],\n ],\n paint: {\n 'circle-radius': 4,\n 'circle-color': '#fff',\n },\n },\n {\n id: 'gl-draw-point-active',\n type: 'circle',\n filter: [\n 'all',\n ['==', '$type', 'Point'],\n ['!=', 'meta', 'midpoint'],\n ['==', 'active', 'true'],\n ],\n paint: {\n 'circle-radius': 2,\n 'circle-color': '#fbb03b',\n },\n },\n {\n id: 'gl-draw-polygon-fill-static',\n type: 'fill',\n filter: ['all', ['==', 'mode', 'static'], ['==', '$type', 'Polygon']],\n paint: {\n 'fill-color': '#404040',\n 'fill-outline-color': '#404040',\n 'fill-opacity': 0.1,\n },\n },\n {\n id: 'gl-draw-polygon-stroke-static',\n type: 'line',\n filter: ['all', ['==', 'mode', 'static'], ['==', '$type', 'Polygon']],\n layout: {\n 'line-cap': 'round',\n 'line-join': 'round',\n },\n paint: {\n 'line-color': '#404040',\n 'line-width': 2,\n },\n },\n {\n id: 'gl-draw-line-static',\n type: 'line',\n filter: ['all', ['==', 'mode', 'static'], ['==', '$type', 'LineString']],\n layout: {\n 'line-cap': 'round',\n 'line-join': 'round',\n },\n paint: {\n 'line-color': '#404040',\n 'line-width': 2,\n },\n },\n {\n id: 'gl-draw-point-static',\n type: 'circle',\n filter: ['all', ['==', 'mode', 'static'], ['==', '$type', 'Point']],\n paint: {\n 'circle-radius': 5,\n 'circle-color': '#404040',\n },\n },\n \n // {\n // 'id': 'gl-draw-polygon-rotate-point',\n // 'type': 'circle',\n // 'filter': ['all',\n // ['==', '$type', 'Point'],\n // ['==', 'meta', 'rotate_point']],\n // 'paint': {\n // 'circle-radius': 5,\n // 'circle-color': '#fbb03b'\n // }\n // },\n \n {\n id: 'gl-draw-line-rotate-point',\n type: 'line',\n filter: [\n 'all',\n ['==', 'meta', 'midpoint'],\n ['==', 'icon', 'rotate'],\n ['==', '$type', 'LineString'],\n ['!=', 'mode', 'static'],\n // ['==', 'active', 'true']\n ],\n layout: {\n 'line-cap': 'round',\n 'line-join': 'round',\n },\n paint: {\n 'line-color': '#fbb03b',\n 'line-dasharray': [0.2, 2],\n 'line-width': 2,\n },\n },\n {\n id: 'gl-draw-polygon-rotate-point-stroke',\n type: 'circle',\n filter: [\n 'all',\n ['==', 'meta', 'midpoint'],\n ['==', 'icon', 'rotate'],\n ['==', '$type', 'Point'],\n ['!=', 'mode', 'static'],\n ],\n paint: {\n 'circle-radius': 4,\n 'circle-color': '#fff',\n },\n },\n {\n id: 'gl-draw-polygon-rotate-point',\n type: 'circle',\n filter: [\n 'all',\n ['==', 'meta', 'midpoint'],\n ['==', 'icon', 'rotate'],\n ['==', '$type', 'Point'],\n ['!=', 'mode', 'static'],\n ],\n paint: {\n 'circle-radius': 2,\n 'circle-color': '#fbb03b',\n },\n },\n {\n id: 'gl-draw-polygon-rotate-point-icon',\n type: 'symbol',\n filter: [\n 'all',\n ['==', 'meta', 'midpoint'],\n ['==', 'icon', 'rotate'],\n ['==', '$type', 'Point'],\n ['!=', 'mode', 'static'],\n ],\n layout: {\n 'icon-image': 'rotate',\n 'icon-allow-overlap': true,\n 'icon-ignore-placement': true,\n 'icon-rotation-alignment': 'map',\n 'icon-rotate': ['get', 'heading'],\n },\n paint: {\n 'icon-opacity': 1.0,\n 'icon-opacity-transition': {\n delay: 0,\n duration: 0,\n },\n },\n },\n ];","import xtend from 'xtend';\nimport * as Constants from './constants';\n\nimport styles from './lib/theme';\nimport modes from './modes/index';\nimport { SRStyle } from \"./lib/SRStyle\";\n\nconst defaultOptions = {\n defaultMode: Constants.modes.SIMPLE_SELECT,\n keybindings: true,\n touchEnabled: true,\n clickBuffer: 2,\n touchBuffer: 25,\n boxSelect: true,\n displayControlsDefault: true,\n styles : SRStyle,\n modes,\n controls: {},\n userProperties: false\n};\n\nconst showControls = {\n point: true,\n line_string: true,\n polygon: true,\n trash: true,\n combine_features: true,\n uncombine_features: true,\n srmode: true\n};\n\nconst hideControls = {\n point: false,\n line_string: false,\n polygon: false,\n trash: false,\n combine_features: false,\n uncombine_features: false,\n srmode: false\n};\n\nfunction addSources(styles, sourceBucket) {\n return styles.map((style) => {\n if (style.source) return style;\n return xtend(style, {\n id: `${style.id}.${sourceBucket}`,\n source: (sourceBucket === 'hot') ? Constants.sources.HOT : Constants.sources.COLD\n });\n });\n}\n\nexport default function(options = {}) {\n let withDefaults = xtend(options);\n\n if (!options.controls) {\n withDefaults.controls = {};\n }\n\n if (options.displayControlsDefault === false) {\n withDefaults.controls = xtend(hideControls, options.controls);\n } else {\n withDefaults.controls = xtend(showControls, options.controls);\n }\n\n withDefaults = xtend(defaultOptions, withDefaults);\n\n // Layers with a shared source should be adjacent for performance reasons\n withDefaults.styles = addSources(withDefaults.styles, 'cold').concat(addSources(withDefaults.styles, 'hot'));\n\n return withDefaults;\n}\n","/**\n * Lodash (Custom Build) <https://lodash.com/>\n * Build: `lodash modularize exports=\"npm\" -o ./`\n * Copyright JS Foundation and other contributors <https://js.foundation/>\n * Released under MIT license <https://lodash.com/license>\n * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>\n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n\n/** Used as the size to enable large array optimizations. */\nvar LARGE_ARRAY_SIZE = 200;\n\n/** Used to stand-in for `undefined` hash values. */\nvar HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n/** Used to compose bitmasks for value comparisons. */\nvar COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n/** Used as references for various `Number` constants. */\nvar MAX_SAFE_INTEGER = 9007199254740991;\n\n/** `Object#toString` result references. */\nvar argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]';\n\nvar arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n/**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\nvar reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g;\n\n/** Used to detect host constructors (Safari). */\nvar reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n/** Used to detect unsigned integer values. */\nvar reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n/** Used to identify `toStringTag` values of typed arrays. */\nvar typedArrayTags = {};\ntypedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\ntypedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\ntypedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\ntypedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\ntypedArrayTags[uint32Tag] = true;\ntypedArrayTags[argsTag] = typedArrayTags[arrayTag] =\ntypedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\ntypedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\ntypedArrayTags[errorTag] = typedArrayTags[funcTag] =\ntypedArrayTags[mapTag] = typedArrayTags[numberTag] =\ntypedArrayTags[objectTag] = typedArrayTags[regexpTag] =\ntypedArrayTags[setTag] = typedArrayTags[stringTag] =\ntypedArrayTags[weakMapTag] = false;\n\n/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\n/** Detect free variable `exports`. */\nvar freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n/** Detect free variable `module`. */\nvar freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n/** Detect the popular CommonJS extension `module.exports`. */\nvar moduleExports = freeModule && freeModule.exports === freeExports;\n\n/** Detect free variable `process` from Node.js. */\nvar freeProcess = moduleExports && freeGlobal.process;\n\n/** Used to access faster Node.js helpers. */\nvar nodeUtil = (function() {\n try {\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n}());\n\n/* Node.js helper references. */\nvar nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n/**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\nfunction arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n}\n\n/**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\nfunction arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n}\n\n/**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\nfunction arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\nfunction baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n}\n\n/**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\nfunction baseUnary(func) {\n return function(value) {\n return func(value);\n };\n}\n\n/**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction cacheHas(cache, key) {\n return cache.has(key);\n}\n\n/**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\nfunction getValue(object, key) {\n return object == null ? undefined : object[key];\n}\n\n/**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\nfunction mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n}\n\n/**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\nfunction overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n}\n\n/**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\nfunction setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n}\n\n/** Used for built-in method references. */\nvar arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n/** Used to detect overreaching core-js shims. */\nvar coreJsData = root['__core-js_shared__'];\n\n/** Used to resolve the decompiled source of functions. */\nvar funcToString = funcProto.toString;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/** Used to detect methods masquerading as native. */\nvar maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n}());\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Used to detect if a method is native. */\nvar reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n);\n\n/** Built-in value references. */\nvar Buffer = moduleExports ? root.Buffer : undefined,\n Symbol = root.Symbol,\n Uint8Array = root.Uint8Array,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeKeys = overArg(Object.keys, Object);\n\n/* Built-in method references that are verified to be native. */\nvar DataView = getNative(root, 'DataView'),\n Map = getNative(root, 'Map'),\n Promise = getNative(root, 'Promise'),\n Set = getNative(root, 'Set'),\n WeakMap = getNative(root, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n/** Used to detect maps, sets, and weakmaps. */\nvar dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n/** Used to convert symbols to primitives and strings. */\nvar symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined;\n\n/**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\nfunction hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n}\n\n/**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n}\n\n/**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n}\n\n/**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\nfunction hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n}\n\n// Add methods to `Hash`.\nHash.prototype.clear = hashClear;\nHash.prototype['delete'] = hashDelete;\nHash.prototype.get = hashGet;\nHash.prototype.has = hashHas;\nHash.prototype.set = hashSet;\n\n/**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\nfunction listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n}\n\n/**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n}\n\n/**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n}\n\n/**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\nfunction listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n}\n\n// Add methods to `ListCache`.\nListCache.prototype.clear = listCacheClear;\nListCache.prototype['delete'] = listCacheDelete;\nListCache.prototype.get = listCacheGet;\nListCache.prototype.has = listCacheHas;\nListCache.prototype.set = listCacheSet;\n\n/**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n}\n\n/**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\nfunction mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n}\n\n/**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n}\n\n/**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction mapCacheGet(key) {\n return getMapData(this, key).get(key);\n}\n\n/**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction mapCacheHas(key) {\n return getMapData(this, key).has(key);\n}\n\n/**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\nfunction mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n}\n\n// Add methods to `MapCache`.\nMapCache.prototype.clear = mapCacheClear;\nMapCache.prototype['delete'] = mapCacheDelete;\nMapCache.prototype.get = mapCacheGet;\nMapCache.prototype.has = mapCacheHas;\nMapCache.prototype.set = mapCacheSet;\n\n/**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\nfunction SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n}\n\n/**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\nfunction setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n}\n\n/**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\nfunction setCacheHas(value) {\n return this.__data__.has(value);\n}\n\n// Add methods to `SetCache`.\nSetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\nSetCache.prototype.has = setCacheHas;\n\n/**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\nfunction Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n}\n\n/**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\nfunction stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n}\n\n/**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\nfunction stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n}\n\n/**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\nfunction stackGet(key) {\n return this.__data__.get(key);\n}\n\n/**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\nfunction stackHas(key) {\n return this.__data__.has(key);\n}\n\n/**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\nfunction stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n}\n\n// Add methods to `Stack`.\nStack.prototype.clear = stackClear;\nStack.prototype['delete'] = stackDelete;\nStack.prototype.get = stackGet;\nStack.prototype.has = stackHas;\nStack.prototype.set = stackSet;\n\n/**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\nfunction arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\nfunction assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n}\n\n/**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n}\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\n/**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\nfunction baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n}\n\n/**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\nfunction baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n}\n\n/**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n}\n\n/**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\nfunction baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n}\n\n/**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\nfunction baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n}\n\n/**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\nfunction baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\nfunction equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(array);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n}\n\n/**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\nfunction equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked && stack.get(other)) {\n return stacked == other;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n}\n\n/**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\nfunction getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n}\n\n/**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\nfunction getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n}\n\n/**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\nfunction getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n}\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\n/**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\nvar getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n};\n\n/**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nvar getTag = baseGetTag;\n\n// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\nif ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n}\n\n/**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\nfunction isIndex(value, length) {\n length = length == null ? MAX_SAFE_INTEGER : length;\n return !!length &&\n (typeof value == 'number' || reIsUint.test(value)) &&\n (value > -1 && value % 1 == 0 && value < length);\n}\n\n/**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\nfunction isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n}\n\n/**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\nfunction isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n}\n\n/**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\nfunction isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n}\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\n/**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\nfunction toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n}\n\n/**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\nfunction eq(value, other) {\n return value === other || (value !== value && other !== other);\n}\n\n/**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\nvar isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n};\n\n/**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\nvar isArray = Array.isArray;\n\n/**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\nfunction isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n}\n\n/**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\nvar isBuffer = nativeIsBuffer || stubFalse;\n\n/**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\nfunction isEqual(value, other) {\n return baseIsEqual(value, other);\n}\n\n/**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\nfunction isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n}\n\n/**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\nfunction isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n}\n\n/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\n/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\n/**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\nvar isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n/**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\nfunction keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n}\n\n/**\n * This method returns a new empty array.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {Array} Returns the new empty array.\n * @example\n *\n * var arrays = _.times(2, _.stubArray);\n *\n * console.log(arrays);\n * // => [[], []]\n *\n * console.log(arrays[0] === arrays[1]);\n * // => false\n */\nfunction stubArray() {\n return [];\n}\n\n/**\n * This method returns `false`.\n *\n * @static\n * @memberOf _\n * @since 4.13.0\n * @category Util\n * @returns {boolean} Returns `false`.\n * @example\n *\n * _.times(2, _.stubFalse);\n * // => [false, false]\n */\nfunction stubFalse() {\n return false;\n}\n\nmodule.exports = isEqual;\n","export default function(a, b) {\n if (a.length !== b.length) return false;\n return JSON.stringify(a.map(id => id).sort()) === JSON.stringify(b.map(id => id).sort());\n}\n","import isEqual from 'lodash.isequal';\nimport normalize from '@mapbox/geojson-normalize';\nimport hat from 'hat';\nimport featuresAt from './lib/features_at';\nimport stringSetsAreEqual from './lib/string_sets_are_equal';\nimport * as Constants from './constants';\nimport StringSet from './lib/string_set';\n\nimport Polygon from './feature_types/polygon';\nimport LineString from './feature_types/line_string';\nimport Point from './feature_types/point';\nimport MultiFeature from './feature_types/multi_feature';\n\nconst featureTypes = {\n Polygon,\n LineString,\n Point,\n MultiPolygon: MultiFeature,\n MultiLineString: MultiFeature,\n MultiPoint: MultiFeature\n};\n\nexport default function(ctx, api) {\n\n api.modes = Constants.modes;\n\n api.getFeatureIdsAt = function(point) {\n const features = featuresAt.click({ point }, null, ctx);\n return features.map(feature => feature.properties.id);\n };\n\n api.getSelectedIds = function () {\n return ctx.store.getSelectedIds();\n };\n\n api.getSelected = function () {\n return {\n type: Constants.geojsonTypes.FEATURE_COLLECTION,\n features: ctx.store.getSelectedIds().map(id => ctx.store.get(id)).map(feature => feature.toGeoJSON())\n };\n };\n\n api.getSelectedPoints = function () {\n return {\n type: Constants.geojsonTypes.FEATURE_COLLECTION,\n features: ctx.store.getSelectedCoordinates().map(coordinate => ({\n type: Constants.geojsonTypes.FEATURE,\n properties: {},\n geometry: {\n type: Constants.geojsonTypes.POINT,\n coordinates: coordinate.coordinates\n }\n }))\n };\n };\n\n api.set = function(featureCollection) {\n if (featureCollection.type === undefined || featureCollection.type !== Constants.geojsonTypes.FEATURE_COLLECTION || !Array.isArray(featureCollection.features)) {\n throw new Error('Invalid FeatureCollection');\n }\n const renderBatch = ctx.store.createRenderBatch();\n let toDelete = ctx.store.getAllIds().slice();\n const newIds = api.add(featureCollection);\n const newIdsLookup = new StringSet(newIds);\n\n toDelete = toDelete.filter(id => !newIdsLookup.has(id));\n if (toDelete.length) {\n api.delete(toDelete);\n }\n\n renderBatch();\n return newIds;\n };\n\n api.add = function (geojson) {\n const featureCollection = JSON.parse(JSON.stringify(normalize(geojson)));\n\n const ids = featureCollection.features.map((feature) => {\n feature.id = feature.id || hat();\n\n if (feature.geometry === null) {\n throw new Error('Invalid geometry: null');\n }\n\n if (ctx.store.get(feature.id) === undefined || ctx.store.get(feature.id).type !== feature.geometry.type) {\n // If the feature has not yet been created ...\n const Model = featureTypes[feature.geometry.type];\n if (Model === undefined) {\n throw new Error(`Invalid geometry type: ${feature.geometry.type}.`);\n }\n const internalFeature = new Model(ctx, feature);\n ctx.store.add(internalFeature);\n } else {\n // If a feature of that id has already been created, and we are swapping it out ...\n const internalFeature = ctx.store.get(feature.id);\n internalFeature.properties = feature.properties;\n if (!isEqual(internalFeature.getCoordinates(), feature.geometry.coordinates)) {\n internalFeature.incomingCoords(feature.geometry.coordinates);\n }\n }\n return feature.id;\n });\n\n ctx.store.render();\n return ids;\n };\n\n\n api.get = function (id) {\n const feature = ctx.store.get(id);\n if (feature) {\n return feature.toGeoJSON();\n }\n };\n\n api.getAll = function() {\n return {\n type: Constants.geojsonTypes.FEATURE_COLLECTION,\n features: ctx.store.getAll().map(feature => feature.toGeoJSON())\n };\n };\n\n api.delete = function(featureIds) {\n ctx.store.delete(featureIds, { silent: true });\n // If we were in direct select mode and our selected feature no longer exists\n // (because it was deleted), we need to get out of that mode.\n if (api.getMode() === Constants.modes.DIRECT_SELECT && !ctx.store.getSelectedIds().length) {\n ctx.events.changeMode(Constants.modes.SIMPLE_SELECT, undefined, { silent: true });\n } else {\n ctx.store.render();\n }\n\n return api;\n };\n\n api.deleteAll = function() {\n ctx.store.delete(ctx.store.getAllIds(), { silent: true });\n // If we were in direct select mode, now our selected feature no longer exists,\n // so escape that mode.\n if (api.getMode() === Constants.modes.DIRECT_SELECT) {\n ctx.events.changeMode(Constants.modes.SIMPLE_SELECT, undefined, { silent: true });\n } else {\n ctx.store.render();\n }\n\n return api;\n };\n\n api.changeMode = function(mode, modeOptions = {}) {\n // Avoid changing modes just to re-select what's already selected\n if (mode === Constants.modes.SIMPLE_SELECT && api.getMode() === Constants.modes.SIMPLE_SELECT) {\n if (stringSetsAreEqual((modeOptions.featureIds || []), ctx.store.getSelectedIds())) return api;\n // And if we are changing the selection within simple_select mode, just change the selection,\n // instead of stopping and re-starting the mode\n ctx.store.setSelected(modeOptions.featureIds, { silent: true });\n ctx.store.render();\n return api;\n }\n\n if (mode === Constants.modes.DIRECT_SELECT && api.getMode() === Constants.modes.DIRECT_SELECT &&\n modeOptions.featureId === ctx.store.getSelectedIds()[0]) {\n return api;\n }\n\n ctx.events.changeMode(mode, modeOptions, { silent: true });\n return api;\n };\n\n api.getMode = function() {\n return ctx.events.getMode();\n };\n\n api.trash = function() {\n ctx.events.trash({ silent: true });\n return api;\n };\n\n api.combineFeatures = function() {\n ctx.events.combineFeatures({ silent: true });\n return api;\n };\n\n api.uncombineFeatures = function() {\n ctx.events.uncombineFeatures({ silent: true });\n return api;\n };\n\n api.setFeatureProperty = function(featureId, property, value) {\n ctx.store.setFeatureProperty(featureId, property, value);\n return api;\n };\n\n return api;\n}\n","import runSetup from './src/setup';\nimport setupOptions from './src/options';\nimport setupAPI from './src/api';\nimport * as Constants from './src/constants';\nimport * as lib from './src/lib';\n\nconst setupDraw = function(options, api) {\n options = setupOptions(options);\n\n const ctx = {\n options\n };\n\n api = setupAPI(ctx, api);\n ctx.api = api;\n\n const setup = runSetup(ctx);\n\n api.onAdd = setup.onAdd;\n api.onRemove = setup.onRemove;\n api.types = Constants.types;\n api.options = options;\n\n return api;\n};\n\nfunction MapboxDraw(options) {\n setupDraw(options, this);\n}\n\nimport modes from './src/modes/index';\nMapboxDraw.modes = modes;\nMapboxDraw.constants = Constants;\nMapboxDraw.lib = lib;\n\nexport default MapboxDraw;\n","/**\n * @fileoverview GlobeControl component for switching between 3D globe and 2D map views.\n *\n * Provides a control button to toggle between mercator (2D flat map) and\n * globe (3D) projections in MapLibre GL 3.x+.\n *\n * @module components/globe-control\n * @see {@link https://maplibre.org/maplibre-gl-js/docs/layers/}\n */\n\nimport { useEffect, memo, useRef } from 'react'\nimport { useControl } from './use-control'\nimport { logger } from '../utils/logger'\n\nimport type { ControlPosition, IControl, Map as MapInstance } from '../types/lib'\n\n/**\n * Options for the GlobeControl\n */\nexport interface GlobeControlOptions {\n /** Custom button element */\n buttonElement?: HTMLElement\n /** Custom button class name */\n buttonClassName?: string\n /** Button title/tooltip text */\n buttonTitle?: string\n /** Custom CSS for the button */\n buttonStyle?: React.CSSProperties\n}\n\nexport type GlobeControlProps = GlobeControlOptions & {\n /** Position of the control on the map */\n position?: ControlPosition\n /** Called when projection changes */\n onProjectionChange?: (isGlobe: boolean) => void\n}\n\n/**\n * Default button SVG icons\n */\nconst GLOBE_SVG = `<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <circle cx=\"12\" cy=\"12\" r=\"10\"/>\n <line x1=\"2\" y1=\"12\" x2=\"22\" y2=\"12\"/>\n <path d=\"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z\"/>\n</svg>`\n\nconst MAP_SVG = `<svg viewBox=\"0 0 24 24\" width=\"24\" height=\"24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\">\n <polygon points=\"1 6 1 22 8 18 16 22 23 18 23 2 16 6 8 2 1 6\"/>\n <line x1=\"8\" y1=\"2\" x2=\"8\" y2=\"18\"/>\n <line x1=\"16\" y1=\"6\" x2=\"16\" y2=\"22\"/>\n</svg>`\n\n/**\n * GlobeControlImpl class implementing IControl interface\n */\nclass GlobeControlImpl implements IControl {\n private _container: HTMLDivElement\n private _button: HTMLButtonElement\n private _map: MapInstance | null = null\n private _isGlobe: boolean = false\n private _options: GlobeControlOptions\n private _onProjectionChange?: (isGlobe: boolean) => void\n\n constructor(\n options: GlobeControlOptions,\n callbacks: {\n onProjectionChange?: (isGlobe: boolean) => void\n }\n ) {\n this._options = options\n this._onProjectionChange = callbacks.onProjectionChange\n this._container = document.createElement('div')\n this._container.className = 'maplibregl-ctrl maplibregl-ctrl-group'\n this._button = this._createButton()\n this._container.appendChild(this._button)\n }\n\n private _createButton(): HTMLButtonElement {\n let button = this._options.buttonElement as HTMLButtonElement\n\n if (button) {\n const tagName = button.tagName.toLowerCase()\n const role = button.getAttribute('role')\n const isButton = tagName === 'button' || role === 'button'\n\n if (!isButton) {\n logger.warn(\n 'GlobeControl: Refusing non-button custom element. custom element must be a <button> or have role=\"button\".'\n )\n button = document.createElement('button')\n }\n } else {\n button = document.createElement('button')\n }\n\n // Unconditionally set / ensure accessibility properties\n const tagName = button.tagName.toLowerCase()\n if (tagName === 'button') {\n if (!button.getAttribute('type')) {\n button.setAttribute('type', 'button')\n }\n } else {\n if (!button.getAttribute('role')) {\n button.setAttribute('role', 'button')\n }\n if (!button.getAttribute('tabindex')) {\n button.setAttribute('tabindex', '0')\n }\n }\n\n if (!button.getAttribute('aria-label')) {\n button.setAttribute('aria-label', 'Toggle Globe View')\n }\n if (!button.getAttribute('title')) {\n button.setAttribute('title', this._options.buttonTitle || 'Toggle Globe View')\n }\n\n // For default button (or refused custom buttons), apply styles and SVG content\n if (!this._options.buttonElement || button !== this._options.buttonElement) {\n button.className = this._options.buttonClassName || 'maplibregl-ctrl-globe'\n button.innerHTML = this._isGlobe ? MAP_SVG : GLOBE_SVG\n\n // Apply custom styles\n Object.assign(button.style, {\n padding: '5px',\n border: 'none',\n background: 'white',\n cursor: 'pointer',\n borderRadius: '4px',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n ...this._options.buttonStyle,\n })\n }\n\n button.addEventListener('click', () => this._toggleGlobe())\n\n return button\n }\n\n private _toggleGlobe(): void {\n if (!this._map) return\n\n this._isGlobe = !this._isGlobe\n\n // Update button icon if it's default\n if (!this._options.buttonElement || this._button !== this._options.buttonElement) {\n this._button.innerHTML = this._isGlobe ? MAP_SVG : GLOBE_SVG\n }\n\n // Update title and aria-label unconditionally\n const labelText = this._isGlobe ? 'Switch to Map View' : 'Switch to Globe View'\n this._button.setAttribute('aria-label', labelText)\n this._button.title = labelText\n\n // Set projection\n try {\n const projection = this._isGlobe ? { type: 'globe' } : { type: 'mercator' }\n ;(this._map as any).setProjection(projection)\n this._onProjectionChange?.(this._isGlobe)\n } catch (error) {\n logger.warn('GlobeControl: setProjection not available', error)\n }\n }\n\n onAdd(map: MapInstance): HTMLElement {\n this._map = map\n\n // Check if globe projection is available\n try {\n const currentProjection = (map as any).getProjection?.()\n this._isGlobe = currentProjection?.type === 'globe'\n if (!this._options.buttonElement || this._button !== this._options.buttonElement) {\n this._button.innerHTML = this._isGlobe ? MAP_SVG : GLOBE_SVG\n }\n const labelText = this._isGlobe ? 'Switch to Map View' : 'Switch to Globe View'\n this._button.setAttribute('aria-label', labelText)\n this._button.title = labelText\n } catch {\n // Globe projection not available, default to map view\n this._isGlobe = false\n }\n\n return this._container\n }\n\n onRemove(): void {\n this._container.parentNode?.removeChild(this._container)\n this._map = null\n }\n\n /**\n * Check if currently in globe view\n */\n isGlobe(): boolean {\n return this._isGlobe\n }\n\n /**\n * Set the projection programmatically\n */\n setGlobe(isGlobe: boolean): void {\n if (this._isGlobe !== isGlobe) {\n this._toggleGlobe()\n }\n }\n}\n\n/**\n * GlobeControl component for toggling between 3D globe and 2D map views.\n *\n * This control works with MapLibre GL 3.x+ which supports globe projection.\n * Adds a button to the map that toggles between mercator (flat) and globe (3D) projections.\n *\n * @component\n * @example\n * ```tsx\n * import { Map, GlobeControl } from 'react-bkoi-gl';\n * import \"react-bkoi-gl/styles\";\n *\n * function GlobeExample() {\n * const handleProjectionChange = (isGlobe) => {\n * console.log('Globe view:', isGlobe);\n * };\n *\n * return (\n * <Map\n * mapStyle={`https://map.barikoi.com/styles/osm-liberty/style.json?key=${API_KEY}`}\n * initialViewState={{\n * longitude: 90.3938,\n * latitude: 23.8216,\n * zoom: 12\n * }}\n * >\n * <GlobeControl\n * position=\"top-right\"\n * onProjectionChange={handleProjectionChange}\n * />\n * </Map>\n * );\n * }\n * ```\n */\nfunction _GlobeControl(props: GlobeControlProps) {\n const { position, onProjectionChange, ...options } = props\n\n // Store callback in ref to avoid recreating control\n const callbacksRef = useRef({ onProjectionChange })\n\n // Update callback ref when it changes\n useEffect(() => {\n callbacksRef.current = { onProjectionChange }\n }, [onProjectionChange])\n\n useControl(\n () => {\n return new GlobeControlImpl(options, {\n onProjectionChange: isGlobe => callbacksRef.current.onProjectionChange?.(isGlobe),\n })\n },\n { position }\n )\n\n return null\n}\n\nexport const GlobeControl = memo(_GlobeControl)\n","import { memo } from 'react'\nimport {\n Map,\n type IControl,\n type GeoJSONSource,\n type ControlPosition,\n type StyleSpecification,\n} from 'maplibre-gl'\nimport { useControl } from './use-control'\nimport { logger } from '../utils/logger'\n\ntype MapLibreMap = Map\n\n/**\n * Map interaction types that can be disabled/enabled\n */\nexport type MapInteractions =\n | 'dragPan'\n | 'scrollZoom'\n | 'boxZoom'\n | 'dragRotate'\n | 'keyboard'\n | 'doubleClickZoom'\n | 'touchZoomRotate'\n\n/**\n * Configuration for minimap interactions\n */\nexport type MinimapInteractions = Record<MapInteractions, boolean>\n\n/**\n * Configuration for the parent rectangle overlay\n */\nexport interface ParentRectConfig {\n /** Layout properties for the line layer */\n lineLayout?: Record<string, unknown>\n /** Paint properties for the line layer */\n linePaint?: Record<string, unknown>\n /** Paint properties for the fill layer */\n fillPaint?: Record<string, unknown>\n}\n\n/**\n * Configuration for the toggle button\n */\nexport interface ToggleButtonConfig {\n /** Custom SVG icon */\n icon?: string\n /** Custom CSS class */\n className?: string\n /** Custom inline styles */\n style?: Record<string, string>\n /** Background color of the icon */\n iconBackgroundColor?: string\n /** Hover color */\n hoverColor?: string\n /** Enable rotation based on position */\n enableRotation?: boolean\n /** Custom rotation angle */\n rotationAngle?: number\n}\n\n/**\n * Minimap control options\n */\nexport interface MinimapControlOptions {\n /** Initial center coordinates */\n center?: [number, number]\n /** Barikoi API access token */\n accessToken?: string\n /** Map style for the minimap */\n style?: string | StyleSpecification\n /** Zoom level difference from parent */\n zoomAdjust?: number\n /** Lock to specific zoom level */\n lockZoom?: number\n /** Sync pitch with parent */\n pitchAdjust?: boolean\n /** Custom container styles */\n containerStyle?: Record<string, string>\n /** Position on map */\n position?: ControlPosition\n /** Parent rectangle configuration */\n parentRect?: ParentRectConfig\n /** Whether minimap can be toggled */\n toggleable?: boolean\n /** Toggle button configuration */\n toggleButton?: ToggleButtonConfig\n /** Start minimized */\n initialMinimized?: boolean\n /** Width when minimized */\n collapsedWidth?: string\n /** Height when minimized */\n collapsedHeight?: string\n /** Border radius */\n borderRadius?: string\n /** Interaction configuration */\n interactions?: Partial<MinimapInteractions>\n /** Toggle callback */\n onToggle?: (isMinimized: boolean) => void\n /** Hide tooltip text */\n hideText?: string\n /** Show tooltip text */\n showText?: string\n /** Enable responsive sizing */\n responsive?: boolean\n /** Responsive width */\n responsiveWidth?: string\n /** Responsive height */\n responsiveHeight?: string\n /** Minimum width */\n minWidth?: string\n /** Minimum height */\n minHeight?: string\n /** Maximum width */\n maxWidth?: string\n /** Maximum height */\n maxHeight?: string\n}\n\nexport type MinimapControlProps = MinimapControlOptions\n\n// Named constants for default values\nconst DEFAULT_ZOOM_ADJUST = -4\nconst DEFAULT_COLLAPSED_SIZE = '29px'\nconst DEFAULT_BORDER_RADIUS = '3px'\nconst TRANSITION_DURATION_MS = 600\nconst RESIZE_DEBOUNCE_MS = 100\nconst DEFAULT_WIDTH = '400px'\nconst DEFAULT_HEIGHT = '300px'\n\n/**\n * Default interactions (dragPan enabled for navigation)\n */\nconst defaultInteractions: MinimapInteractions = {\n dragPan: true,\n scrollZoom: false,\n boxZoom: false,\n dragRotate: false,\n keyboard: false,\n doubleClickZoom: false,\n touchZoomRotate: false,\n}\n\n/**\n * Default SVG icon for toggle button\n */\nconst DEFAULT_ICON = `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 24 24\"><path d=\"M17.6 18L8 8.4V17H6V5h12v2H9.4l9.6 9.6l-1.4 1.4Z\" /></svg>`\n\n/**\n * Generate a random UUID using crypto API\n */\nfunction getRandomUUID(): string {\n if (typeof crypto !== 'undefined' && crypto.randomUUID) {\n return crypto.randomUUID()\n }\n // Fallback for older environments\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n const array = new Uint8Array(1)\n crypto.getRandomValues(array)\n const r = array[0] % 16\n const v = c === 'x' ? r : (r & 0x3) | 0x8\n return v.toString(16)\n })\n}\n\nconst ALLOWED_TAGS = new Set([\n 'svg',\n 'g',\n 'path',\n 'rect',\n 'circle',\n 'ellipse',\n 'line',\n 'polyline',\n 'polygon',\n 'text',\n 'tspan',\n 'defs',\n 'linearGradient',\n 'radialGradient',\n 'stop',\n 'clipPath',\n 'mask',\n 'symbol',\n 'marker',\n 'pattern',\n 'desc',\n 'title',\n])\n\nfunction sanitizeElement(el: Element): void {\n // Sanitize attributes\n const attributes = Array.from(el.attributes)\n for (const attr of attributes) {\n const name = attr.name.toLowerCase()\n const value = attr.value\n\n // Drop all event handlers\n if (name.startsWith('on')) {\n el.removeAttribute(attr.name)\n continue\n }\n\n // Drop style attribute to prevent CSS exfiltration/injection\n if (name === 'style') {\n el.removeAttribute(attr.name)\n continue\n }\n\n // Drop dangerous values in href / xlink:href\n if (name === 'href' || name === 'xlink:href') {\n const normalizedValue = value.trim().toLowerCase()\n // Only allow local IDs (#...) or http/https URLs\n if (\n !normalizedValue.startsWith('#') &&\n !normalizedValue.startsWith('http://') &&\n !normalizedValue.startsWith('https://')\n ) {\n el.removeAttribute(attr.name)\n }\n }\n }\n\n // Sanitize child elements\n const childNodes = Array.from(el.childNodes)\n for (const child of childNodes) {\n if (child.nodeType === Node.ELEMENT_NODE) {\n const childEl = child as Element\n const tagName = childEl.tagName.toLowerCase()\n if (!ALLOWED_TAGS.has(tagName)) {\n el.removeChild(childEl)\n } else {\n sanitizeElement(childEl)\n }\n } else if (child.nodeType !== Node.TEXT_NODE && child.nodeType !== Node.CDATA_SECTION_NODE) {\n el.removeChild(child)\n }\n }\n}\n\n/**\n * Safe wrapper around CSS.supports to prevent runtime crashes in environments\n * that do not support it (e.g., Server-Side Rendering or Jest/jsdom).\n */\nfunction supportsCSS(property: string, value: string): boolean {\n if (\n value.includes(';') ||\n value.includes('{') ||\n value.includes('}') ||\n value.includes('\\\\') ||\n /url\\s*\\(/i.test(value)\n ) {\n return false\n }\n\n if (typeof CSS !== 'undefined' && typeof CSS.supports === 'function') {\n try {\n return CSS.supports(property, value)\n } catch {\n return false\n }\n }\n return true\n}\n\n/**\n * Sanitize SVG string to prevent XSS attacks\n */\nfunction sanitizeSVG(svgString: string): SVGElement {\n const parser = new DOMParser()\n let doc = parser.parseFromString(svgString, 'image/svg+xml')\n const parserError = doc.querySelector('parsererror')\n\n if (parserError || !doc.documentElement || doc.documentElement.tagName.toLowerCase() !== 'svg') {\n logger.warn('Invalid SVG format, using default icon')\n doc = parser.parseFromString(DEFAULT_ICON, 'image/svg+xml')\n }\n\n const svgElement = doc.documentElement\n sanitizeElement(svgElement)\n return svgElement as unknown as SVGElement\n}\n\n/**\n * Internal minimap options\n */\ninterface InternalMinimapOptions extends MinimapControlOptions {\n container?: HTMLElement\n zoom?: number\n minZoom?: number\n maxZoom?: number\n bearing?: number\n pitch?: number\n attributionControl: boolean\n logoPosition?: string\n}\n\n/**\n * Minimap class - wraps MapLibre Map as a control\n */\nclass Minimap implements IControl {\n private options: InternalMinimapOptions\n private map!: MapLibreMap\n private parentMap!: MapLibreMap\n private container!: HTMLElement\n private readonly id: string\n private parentRect?: GeoJSON.Feature<GeoJSON.Polygon>\n private differentStyle = false\n private desync?: () => void\n private toggleButtonCleanup?: () => void\n private isMinimized = false\n private resizeHandler?: () => void\n private resizeTimeout?: ReturnType<typeof setTimeout>\n private transitionTimeout?: ReturnType<typeof setTimeout>\n private toggleButtonStyleEl?: HTMLStyleElement\n private liveRegion?: HTMLElement\n\n constructor(options: MinimapControlOptions = {}) {\n this.id = `minimap-${getRandomUUID()}`\n\n if (options.style !== undefined) {\n this.differentStyle = true\n }\n\n const interactions = { ...defaultInteractions, ...(options.interactions ?? {}) }\n\n const containerStyle = this.validateContainerStyle(options.containerStyle)\n\n this.options = {\n zoomAdjust: DEFAULT_ZOOM_ADJUST,\n position: 'top-right',\n pitchAdjust: false,\n attributionControl: false,\n logoPosition: 'bottom-left',\n toggleable: true,\n initialMinimized: false,\n collapsedWidth: DEFAULT_COLLAPSED_SIZE,\n collapsedHeight: DEFAULT_COLLAPSED_SIZE,\n borderRadius: DEFAULT_BORDER_RADIUS,\n hideText: 'Hide minimap',\n showText: 'Show minimap',\n responsive: true,\n responsiveWidth: '20vw',\n responsiveHeight: '20vh',\n minWidth: '200px',\n minHeight: '150px',\n maxWidth: DEFAULT_WIDTH,\n maxHeight: DEFAULT_HEIGHT,\n interactions,\n ...options,\n containerStyle,\n } as InternalMinimapOptions\n\n if (options.lockZoom !== undefined) {\n this.options.minZoom = options.lockZoom\n this.options.maxZoom = options.lockZoom\n }\n\n this.isMinimized = this.options.initialMinimized ?? false\n }\n\n onAdd(parentMap: MapLibreMap): HTMLElement {\n this.parentMap = parentMap\n\n this.container = this.createContainer()\n\n this.options.container = this.container\n this.options.zoom = parentMap.getZoom() + (this.options.zoomAdjust ?? DEFAULT_ZOOM_ADJUST)\n this.options.center ??= parentMap.getCenter().toArray() as [number, number]\n this.options.bearing = parentMap.getBearing()\n this.options.pitch = this.options.pitchAdjust ? parentMap.getPitch() : 0\n\n if (!this.differentStyle) {\n this.options.style = parentMap.getStyle()\n }\n\n this.map = new Map(this.options as unknown as ConstructorParameters<typeof Map>[0])\n\n this.map.once('style.load', () => {\n this.map.resize()\n })\n\n this.map.once('load', () => {\n this.configureInteractions()\n this.addParentRect(this.options.parentRect)\n this.desync = this.syncMaps()\n this.setupToggleButton()\n this.setupResponsiveSizing()\n })\n\n return this.container\n }\n\n onRemove(): void {\n if (this.resizeHandler) {\n window.removeEventListener('resize', this.resizeHandler)\n this.resizeHandler = undefined\n }\n if (this.resizeTimeout) {\n clearTimeout(this.resizeTimeout)\n this.resizeTimeout = undefined\n }\n if (this.transitionTimeout) {\n clearTimeout(this.transitionTimeout)\n this.transitionTimeout = undefined\n }\n this.toggleButtonCleanup?.()\n this.toggleButtonStyleEl?.remove()\n this.toggleButtonStyleEl = undefined\n this.desync?.()\n this.container.remove()\n }\n\n private createContainer(): HTMLElement {\n const container = document.createElement('div')\n container.id = this.id\n container.className =\n 'maplibregl-ctrl maplibregl-ctrl-group maplibregl-ctrl-minimap custom-ctrl-minimap'\n\n if (this.isMinimized) {\n container.classList.add('minimized')\n }\n\n const styleEl = document.createElement('style')\n styleEl.textContent = this.getContainerStyles()\n container.appendChild(styleEl)\n\n if (this.options.containerStyle) {\n for (const [key, value] of Object.entries(this.options.containerStyle)) {\n container.style.setProperty(key, value)\n }\n }\n\n if (this.isMinimized) {\n container.style.width = this.options.collapsedWidth || DEFAULT_COLLAPSED_SIZE\n container.style.height = this.options.collapsedHeight || DEFAULT_COLLAPSED_SIZE\n }\n\n const preventDefault = (e: Event) => e.preventDefault()\n container.addEventListener('contextmenu', preventDefault)\n\n return container\n }\n\n private getContainerStyles(): string {\n let width = this.options.containerStyle?.width || DEFAULT_WIDTH\n if (!supportsCSS('width', width)) {\n width = DEFAULT_WIDTH\n }\n\n let height = this.options.containerStyle?.height || DEFAULT_HEIGHT\n if (!supportsCSS('height', height)) {\n height = DEFAULT_HEIGHT\n }\n\n let collapsedWidth = this.options.collapsedWidth || DEFAULT_COLLAPSED_SIZE\n if (!supportsCSS('width', collapsedWidth)) {\n collapsedWidth = DEFAULT_COLLAPSED_SIZE\n }\n\n let collapsedHeight = this.options.collapsedHeight || DEFAULT_COLLAPSED_SIZE\n if (!supportsCSS('height', collapsedHeight)) {\n collapsedHeight = DEFAULT_COLLAPSED_SIZE\n }\n\n let borderRadius = this.options.borderRadius || DEFAULT_BORDER_RADIUS\n if (!supportsCSS('border-radius', borderRadius)) {\n borderRadius = DEFAULT_BORDER_RADIUS\n }\n\n return `\n #${this.id}.custom-ctrl-minimap {\n cursor: default !important;\n box-shadow: 0 1px 5px rgba(0, 0, 0, 0.65);\n transition: width 0.6s ease-in, height 0.6s ease-in, border-color 0s ease-in;\n border-style: solid;\n border-radius: ${borderRadius};\n border-width: 4px;\n border-color: white;\n width: ${width};\n height: ${height};\n overflow: hidden;\n background: #fff;\n position: relative;\n }\n #${this.id}.minimized {\n border-radius: 3px !important;\n width: ${collapsedWidth};\n height: ${collapsedHeight};\n }\n #${this.id} canvas {\n width: 100% !important;\n height: 100% !important;\n display: block;\n }\n @media (prefers-color-scheme: dark) {\n #${this.id}.custom-ctrl-minimap {\n border-color: hsl(0, 0%, 15.2%);\n }\n }\n `\n }\n\n private validateContainerStyle(style?: Record<string, string>): Record<string, string> {\n const defaults = { border: '1px solid #000', width: DEFAULT_WIDTH, height: DEFAULT_HEIGHT }\n if (!style) return defaults\n\n const validated: Record<string, string> = {}\n if (style.width) {\n validated.width = supportsCSS('width', style.width) ? style.width : defaults.width\n } else {\n validated.width = defaults.width\n }\n if (style.height) {\n validated.height = supportsCSS('height', style.height) ? style.height : defaults.height\n } else {\n validated.height = defaults.height\n }\n for (const [key, value] of Object.entries(style)) {\n if (key !== 'width' && key !== 'height') {\n validated[key] = value\n }\n }\n return validated\n }\n\n private configureInteractions(): void {\n const interactions = this.options.interactions || defaultInteractions\n for (const [interaction, enabled] of Object.entries(interactions)) {\n if (!enabled) {\n const interactionMethod = interaction as keyof MinimapInteractions\n const interactionObj = this.map[interactionMethod] as { disable: () => void } | undefined\n interactionObj?.disable()\n }\n }\n }\n\n private setupToggleButton(): void {\n if (!this.options.toggleable) return\n\n const el = document.createElement('button')\n const elId = 'btn-' + getRandomUUID()\n\n const iconNode = sanitizeSVG(this.options.toggleButton?.icon || DEFAULT_ICON)\n el.replaceChildren(iconNode)\n el.setAttribute('id', elId)\n el.setAttribute('type', 'button')\n const initialText = this.isMinimized\n ? this.options.showText || 'Show minimap'\n : this.options.hideText || 'Hide minimap'\n el.setAttribute('aria-label', initialText)\n el.setAttribute('title', initialText)\n el.setAttribute('aria-expanded', (!this.isMinimized).toString())\n\n if (this.options.toggleButton?.className) {\n const classes = this.options.toggleButton.className.split(' ')\n classes.forEach(cls => el.classList.add(cls))\n }\n\n let iconBackgroundColor = this.options.toggleButton?.iconBackgroundColor || 'black'\n if (!supportsCSS('background-color', iconBackgroundColor)) {\n iconBackgroundColor = 'black'\n }\n\n let hoverColor = this.options.toggleButton?.hoverColor || '#e5e7e3'\n if (!supportsCSS('background-color', hoverColor)) {\n hoverColor = '#e5e7e3'\n }\n\n const styleEl = document.createElement('style')\n styleEl.textContent = `\n button#${elId} {\n border-radius: 0 !important;\n color: black;\n background-color: ${iconBackgroundColor};\n border: none;\n display: flex;\n align-items: center;\n justify-content: center;\n cursor: pointer;\n transition: all 0.2s ease-in;\n position: absolute;\n width: 24px;\n height: 24px;\n z-index: 2;\n padding: 0;\n left: 0;\n top: 0;\n }\n button#${elId}:hover {\n background-color: ${hoverColor} !important;\n }\n button#${elId} svg {\n fill: white;\n width: 16px;\n height: 16px;\n }\n .minimized > button#${elId} > * {\n transform: rotate(-180deg);\n }\n `\n\n const clickHandler = () => {\n this.toggle()\n }\n\n el.addEventListener('click', clickHandler)\n this.toggleButtonStyleEl = styleEl\n document.head.appendChild(styleEl)\n this.container.appendChild(el)\n\n // Create visually-hidden live region for status announcements\n const liveRegion = document.createElement('div')\n liveRegion.setAttribute('aria-live', 'polite')\n liveRegion.setAttribute('aria-atomic', 'true')\n // CSS to make it visually hidden but readable by screen readers\n liveRegion.style.position = 'absolute'\n liveRegion.style.width = '1px'\n liveRegion.style.height = '1px'\n liveRegion.style.padding = '0'\n liveRegion.style.margin = '-1px'\n liveRegion.style.overflow = 'hidden'\n liveRegion.style.clip = 'rect(0, 0, 0, 0)'\n liveRegion.style.border = '0'\n this.liveRegion = liveRegion\n this.container.appendChild(liveRegion)\n\n this.toggleButtonCleanup = () => {\n el.removeEventListener('click', clickHandler)\n this.toggleButtonStyleEl?.remove()\n this.toggleButtonStyleEl = undefined\n this.container.removeChild(el)\n if (this.liveRegion) {\n this.container.removeChild(this.liveRegion)\n this.liveRegion = undefined\n }\n }\n }\n\n private setupResponsiveSizing(): void {\n if (!this.options.responsive) return\n\n const updateSize = () => {\n if (this.isMinimized) return\n\n const vw = window.innerWidth / 100\n const vh = window.innerHeight / 100\n\n const responsiveWidth = this.options.responsiveWidth || '20vw'\n const responsiveHeight = this.options.responsiveHeight || '20vh'\n\n let width: number\n let height: number\n\n if (responsiveWidth.endsWith('vw')) {\n width = parseFloat(responsiveWidth) * vw\n } else if (responsiveWidth.endsWith('%')) {\n width = (parseFloat(responsiveWidth) / 100) * window.innerWidth\n } else {\n width = parseFloat(responsiveWidth)\n }\n\n if (responsiveHeight.endsWith('vh')) {\n height = parseFloat(responsiveHeight) * vh\n } else if (responsiveHeight.endsWith('%')) {\n height = (parseFloat(responsiveHeight) / 100) * window.innerHeight\n } else {\n height = parseFloat(responsiveHeight)\n }\n\n const minW = parseFloat(this.options.minWidth || '200px')\n const minH = parseFloat(this.options.minHeight || '150px')\n const maxW = parseFloat(this.options.maxWidth || DEFAULT_WIDTH)\n const maxH = parseFloat(this.options.maxHeight || DEFAULT_HEIGHT)\n\n width = Math.max(minW, Math.min(maxW, width))\n height = Math.max(minH, Math.min(maxH, height))\n\n this.container.style.width = `${width}px`\n this.container.style.height = `${height}px`\n\n this.map.resize()\n this.setParentBounds()\n }\n\n updateSize()\n\n this.resizeHandler = () => {\n if (this.resizeTimeout) {\n clearTimeout(this.resizeTimeout)\n }\n this.resizeTimeout = setTimeout(updateSize, RESIZE_DEBOUNCE_MS)\n }\n\n window.addEventListener('resize', this.resizeHandler)\n }\n\n toggle(): void {\n this.isMinimized = !this.isMinimized\n\n const collapsedWidth = this.options.collapsedWidth || DEFAULT_COLLAPSED_SIZE\n const collapsedHeight = this.options.collapsedHeight || DEFAULT_COLLAPSED_SIZE\n\n if (this.isMinimized) {\n this.container.classList.add('minimized')\n this.container.style.width = collapsedWidth\n this.container.style.height = collapsedHeight\n } else {\n this.container.classList.remove('minimized')\n if (this.options.responsive && this.resizeHandler) {\n this.resizeHandler()\n } else {\n const expandedWidth = this.options.containerStyle?.width || DEFAULT_WIDTH\n const expandedHeight = this.options.containerStyle?.height || DEFAULT_HEIGHT\n this.container.style.width = expandedWidth\n this.container.style.height = expandedHeight\n }\n }\n\n this.options.onToggle?.(this.isMinimized)\n\n const buttonEl = this.container.querySelector('button')\n if (buttonEl) {\n const text = this.isMinimized\n ? this.options.showText || 'Show minimap'\n : this.options.hideText || 'Hide minimap'\n buttonEl.setAttribute('aria-label', text)\n buttonEl.setAttribute('title', text)\n buttonEl.setAttribute('aria-expanded', (!this.isMinimized).toString())\n }\n\n if (this.liveRegion) {\n this.liveRegion.textContent = this.isMinimized ? 'Minimap collapsed' : 'Minimap expanded'\n }\n\n if (this.transitionTimeout) {\n clearTimeout(this.transitionTimeout)\n }\n this.transitionTimeout = setTimeout(() => {\n this.map.resize()\n this.setParentBounds()\n this.transitionTimeout = undefined\n }, TRANSITION_DURATION_MS)\n }\n\n isMinimizedState(): boolean {\n return this.isMinimized\n }\n\n private addParentRect(rect?: ParentRectConfig): void {\n if (rect === undefined || (rect.linePaint === undefined && rect.fillPaint === undefined)) {\n return\n }\n\n this.parentRect = {\n type: 'Feature',\n properties: { name: 'parentRect' },\n geometry: {\n type: 'Polygon',\n coordinates: [[[], [], [], [], []]],\n },\n }\n\n this.map.addSource('parentRect', {\n type: 'geojson',\n data: this.parentRect,\n })\n\n if (rect.lineLayout !== undefined || rect.linePaint !== undefined) {\n this.map.addLayer({\n id: 'parentRectOutline',\n type: 'line',\n source: 'parentRect',\n layout: { ...(rect.lineLayout || {}) },\n paint: {\n 'line-color': '#FFF',\n 'line-width': 1,\n 'line-opacity': 0.85,\n ...(rect.linePaint || {}),\n },\n })\n }\n\n if (rect.fillPaint !== undefined) {\n this.map.addLayer({\n id: 'parentRectFill',\n type: 'fill',\n source: 'parentRect',\n layout: {},\n paint: {\n 'fill-color': '#08F',\n 'fill-opacity': 0.135,\n ...(rect.fillPaint || {}),\n },\n })\n }\n\n this.setParentBounds()\n }\n\n private setParentBounds(): void {\n if (this.parentRect === undefined || this.isMinimized) return\n\n const { devicePixelRatio } = window\n const canvas = this.parentMap.getCanvas()\n const width = canvas.width / devicePixelRatio\n const height = canvas.height / devicePixelRatio\n\n const unproject = this.parentMap.unproject.bind(this.parentMap)\n const northWest = unproject([0, 0])\n const northEast = unproject([width, 0])\n const southWest = unproject([0, height])\n const southEast = unproject([width, height])\n\n this.parentRect.geometry.coordinates = [\n [\n southWest.toArray(),\n southEast.toArray(),\n northEast.toArray(),\n northWest.toArray(),\n southWest.toArray(),\n ],\n ]\n\n const source = this.map.getSource<GeoJSONSource>('parentRect')\n if (source !== undefined) {\n source.setData(this.parentRect)\n }\n }\n\n private syncMaps(): () => void {\n const { pitchAdjust } = this.options\n\n const parentCallback = () => {\n if (!this.isMinimized) {\n sync('parent')\n }\n }\n const minimapCallback = () => {\n if (!this.isMinimized) {\n sync('minimap')\n }\n }\n\n const on = () => {\n this.parentMap.on('move', parentCallback)\n this.map.on('move', minimapCallback)\n }\n\n const off = () => {\n this.parentMap.off('move', parentCallback)\n this.map.off('move', minimapCallback)\n }\n\n const sync = (which: 'parent' | 'minimap') => {\n off()\n\n const from = which === 'parent' ? this.parentMap : this.map\n const to = which === 'parent' ? this.map : this.parentMap\n\n const center = from.getCenter()\n const zoom =\n from.getZoom() +\n (this.options.zoomAdjust ?? DEFAULT_ZOOM_ADJUST) * (which === 'parent' ? 1 : -1)\n const bearing = from.getBearing()\n const pitch = from.getPitch()\n\n to.jumpTo({\n center,\n zoom,\n bearing,\n pitch: pitchAdjust ? pitch : 0,\n })\n\n this.setParentBounds()\n on()\n }\n\n on()\n\n return () => {\n off()\n }\n }\n}\n\nfunction _MinimapControl(props: MinimapControlProps) {\n const { position, ...options } = props\n\n // Create minimap control using useControl\n useControl<Minimap>(() => new Minimap(options), { position })\n\n return null\n}\n\nexport const MinimapControl = memo(_MinimapControl)\n\n// Also export the Minimap class for direct use\nexport { Minimap }\n","import { Map } from './components/map'\n\nexport { Map }\nexport default Map\n\nexport { Marker } from './components/marker'\nexport { Popup } from './components/popup'\nexport { AttributionControl } from './components/attribution-control'\nexport { FullscreenControl } from './components/fullscreen-control'\nexport { GeolocateControl } from './components/geolocate-control'\nexport { NavigationControl } from './components/navigation-control'\nexport { ScaleControl } from './components/scale-control'\nexport { TerrainControl } from './components/terrain-control'\nexport { LogoControl } from './components/logo-control'\nexport { Source } from './components/source'\nexport { CanvasSource } from './components/canvas-source'\nexport { Layer } from './components/layer'\nexport { useControl } from './components/use-control'\nexport { MapProvider, useMap } from './components/use-map'\nexport { DrawControl } from './components/draw-control'\nexport { GlobeControl } from './components/globe-control'\nexport {\n MinimapControl,\n Minimap,\n type MinimapControlOptions,\n type MinimapControlProps,\n type MinimapInteractions,\n type MapInteractions,\n type ParentRectConfig,\n type ToggleButtonConfig,\n} from './components/minimap-control'\n\nexport type { MapProps } from './components/map'\nexport type { MapRef } from './maplibre/create-ref'\nexport type { MarkerProps } from './components/marker'\nexport type { PopupProps } from './components/popup'\nexport type { AttributionControlProps } from './components/attribution-control'\nexport type { FullscreenControlProps } from './components/fullscreen-control'\nexport type { GeolocateControlProps } from './components/geolocate-control'\nexport type { NavigationControlProps } from './components/navigation-control'\nexport type { ScaleControlProps } from './components/scale-control'\nexport type { TerrainControlProps } from './components/terrain-control'\nexport type { LogoControlProps } from './components/logo-control'\nexport type { SourceProps } from './components/source'\nexport type { CanvasSourceProps, CanvasCoordinates } from './components/canvas-source'\nexport type { LayerProps } from './components/layer'\n\n// Re-export MapLayerMouseEvent for layer event typing\nexport type { MapLayerMouseEvent } from 'maplibre-gl'\nexport type { DrawControlProps, DrawControlOptions } from './components/draw-control'\nexport type { GlobeControlProps, GlobeControlOptions } from './components/globe-control'\n\nexport { logger, setLogger, type Logger } from './utils/logger'\n\n// Types\nexport * from './types/common'\nexport * from './types/events'\nexport * from './types/lib'\nex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c;AACzC,WAAK,IAAI,IAAI,QAAQ,eAAe;AAAA,IACtC;AAEA,UAAM,OAAO,CAAC,UAAgC;AAC5C,UAAI;AAEJ,YAAM,OAAO,UAAU,WAAW,KAAK,YAAY,KAAK;AACxD,YAAM,KAAK,UAAU,WAAW,KAAK,MAAM,KAAK;AAEhD,YAAMC,UAAS,KAAK,UAAU;AAC9B,YAAM,OACJ,KAAK,QAAQ,KACZ,KAAK,QAAQ,cAAc,wBAAwB,UAAU,WAAW,IAAI;AAC/E,YAAMC,WAAU,KAAK,WAAW;AAChC,YAAM,QAAQ,KAAK,SAAS;AAE5B,SAAG,OAAO;AAAA,QACR,QAAAD;AAAA,QACA;AAAA,QACA,SAAAC;AAAA,QACA,OAAO,cAAc,QAAQ;AAAA,MAC/B,CAAC;AAED,WAAK,gBAAgB;AACrB,SAAG;AAAA,IACL;AAEA,OAAG;AAEH,WAAO,MAAM;AACX,UAAI;AAAA,IACN;AAAA,EACF;AACF;AAEA,SAAS,gBAAgB,OAA4B;AACnD,QAAM,EAAE,UAAU,GAAG,QAAQ,IAAI;AAGjC,aAAoB,MAAM,IAAI,QAAQ,OAAO,GAAG,EAAE,SAAS,CAAC;AAE5D,SAAO;AACT;AAEO,IAAM,iBAAiBC,OAAK,eAAe;;;AC73BlD,IAAO,8BAAQ;","names":["React","useState","useEffect","useContext","useMemo","e","point","useEffect","useContext","useMemo","useEffect","useContext","useMemo","useEffect","useEffect","useEffect","memo","useEffect","memo","useContext","useState","useEffect","useMemo","React","useImperativeHandle","useEffect","useMemo","useRef","useContext","forwardRef","memo","memo","forwardRef","useContext","useRef","useMemo","useEffect","e","useImperativeHandle","createPortal","useImperativeHandle","useEffect","useMemo","useContext","forwardRef","memo","memo","forwardRef","useContext","useMemo","useImperativeHandle","useEffect","e","createPortal","useEffect","memo","useEffect","memo","useImperativeHandle","useRef","useEffect","forwardRef","memo","useRef","e","useImperativeHandle","useEffect","memo","forwardRef","useEffect","memo","useEffect","memo","useEffect","useRef","memo","useRef","useEffect","memo","useEffect","memo","useEffect","memo","React","useContext","useEffect","useMemo","useState","useRef","memo","useImperativeHandle","useContext","useRef","useState","useMemo","useEffect","mapInternal","useImperativeHandle","memo","React","useContext","useEffect","useMemo","useRef","memo","useContext","useRef","useMemo","useEffect","mapInternal","updateSource","memo","useContext","useEffect","useMemo","useState","useRef","memo","useId","useContext","useRef","useState","useId","useMemo","useEffect","mapInternal","e","memo","useEffect","useMemo","memo","useRef","useContext","const","render","let","wgs84","require$$0","types","modes","events","LAT_MIN","LAT_RENDERED_MIN","LAT_MAX","LAT_RENDERED_MAX","LNG_MIN","LNG_MAX","Constants.geojsonTypes","feature","area","this","Constants.meta","bbox","featuresAt","classes","Constants.cursors","Constants.activeStates","hatModule","hat","Point","MultiPoint","MultiLineString","MultiPolygon","e","getFeaturesAndSetCursor","Constants.modes","setupModeHandler","Constants.events","Constants.sources","point","hasOwnProperty","arguments","Constants.classes","Constants.types","isVertex","Constants.LAT_RENDERED_MAX","Constants.LAT_RENDERED_MIN","midpoint","geojsonNormalize","t","flatten","list","require$$2","geojsonCoords","traverse","traverseModule","clone","immutable","isNumber","isArray","extent","require$$1","geojsonExtentModule","Constants.LAT_MIN","Constants.LAT_MAX","Constants.LNG_MIN","Constants.LNG_MAX","Constants.updateActions","memo","isFeature","CommonSelectors.isFeature","CommonSelectors.noTarget","CommonSelectors.isOfMetaType","CommonSelectors.isShiftDown","CommonSelectors.isActiveFeature","CommonSelectors.isShiftMousedown","i","CommonSelectors.isEscapeKey","CommonSelectors.isEnterKey","CommonSelectors.isVertex","radiansToDegrees","degreesToRadians","isObject","getCoord","coordEach","geometry","validateBBox","validateId","earthRadius","factors","lengthToRadians","distance","bearing","radiansToLength","centroid","convertLength","destination","geom","getCoords","turfBBox","img","rotate","scale","c2","c3","temp","c0","c1","center","CommonSelectors.isInactiveFeature","simple_select","direct_select","draw_point","draw_polygon","draw_line_string","Uint8Array","Map","Promise","Set","othValue","keys","isEqual","normalize","internalFeature","useContext","useMemo","useRef","useEffect","e","memo","useEffect","memo","useRef","tagName","useRef","useEffect","memo","memo","Map","interactions","Map","e","classes","center","bearing","memo"]}