venue-js 1.4.0-next.17 → 1.4.0-next.19

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/data/index.ts","../src/data/constant.ts","../src/data/api/delivery-project.ts","../src/data/utils/geometry-validator.ts","../src/data/utils/match-filters.ts","../src/data/utils/occupant-helper.ts","../src/data/utils/lodash/compact.ts","../src/data/getDataClient.ts","../src/data/populator/index.ts","../src/data/utils/findContaining.ts","../../../node_modules/fuse.js/dist/fuse.mjs","../src/data/search/utils/sanitizeInput.ts","../src/data/search/getSearchClient.ts","../src/IndoorMap/IndoorMap.ts","../node_modules/@turf/helpers/index.ts","../src/IndoorMap/constants.ts","../src/IndoorMap/utils/createElements.js","../src/IndoorMap/object3d/Billboard.js","../src/IndoorMap/object3d/SpriteMarker.ts","../src/IndoorMap/object3d/NavigationPath.ts","../src/IndoorMap/utils/geometry.ts","../src/IndoorMap/utils/svg.ts","../src/IndoorMap/utils/math.ts","../src/IndoorMap/camera/CameraManager.ts","../../../node_modules/@turf/meta/index.js","../../../node_modules/@turf/bbox/index.ts","../src/IndoorMap/renderer/RendererManager.ts","../src/IndoorMap/renderer/3d/Element3DRenderer.ts","../src/IndoorMap/renderer/3d/objects/GroundLabel.ts","../src/IndoorMap/renderer/3d/element3DRendererOptions.ts","../src/IndoorMap/renderer/3d/utils/get3DRendererOption.ts","../src/IndoorMap/renderer/2d/Element2DRenderer.ts","../src/IndoorMap/renderer/2d/element2DRendererOptions.ts","../src/IndoorMap/renderer/2d/Marker2DRenderer.ts","../src/IndoorMap/renderer/3d/Marker3DRenderer.ts","../src/IndoorMap/renderer/3d/objects/TextSpriteMarker.ts","../src/IndoorMap/renderer/utils/interpolateStops.ts","../src/IndoorMap/renderer/utils/angleBetweenLineString.ts","../src/IndoorMap/renderer/utils/findUnitOnPoint.ts"],"sourcesContent":["export { QueryObserver } from \"@tanstack/query-core\"\n\nexport * from \"./types\"\nexport * from \"./constant\"\nexport * from \"./api/delivery-project\"\nexport * from './utils'\nexport * from \"./getDataClient\"\nexport * from './search/getSearchClient'","import { FeatureQueryOptions } from \"./types\"\nimport { FeatureType } from \"./types/feature-api\"\n\nexport const DEFAULT_BASE_URL = \"https://service.venue.in.th/api\"\n\nexport const IMDF_FEATURE_TYPES: FeatureType[] = [\n \"address\",\n \"amenity\",\n \"anchor\",\n \"building\",\n \"detail\",\n \"fixture\",\n \"footprint\",\n \"geofence\",\n \"kiosk\",\n \"level\",\n \"occupant\",\n \"opening\",\n \"relationship\",\n \"section\",\n \"unit\",\n \"venue\",\n]\n\nexport const IMDF_UNIT_CATEGORIES: string[] = [\n 'auditorium',\n 'brick',\n 'classroom',\n 'column',\n 'concrete',\n 'conferenceroom',\n 'drywall',\n 'elevator',\n 'escalator',\n 'fieldofplay',\n 'firstaid',\n 'fitnessroom',\n 'foodservice',\n 'footbridge',\n 'glass',\n 'huddleroom',\n 'kitchen',\n 'laboratory',\n 'library',\n 'lobby',\n 'lounge',\n 'mailroom',\n 'mothersroom',\n 'movietheater',\n 'movingwalkway',\n 'nonpublic',\n 'office',\n 'opentobelow',\n 'parking',\n 'phoneroom',\n 'platform',\n 'privatelounge',\n 'ramp',\n 'recreation',\n 'restroom',\n 'restroom.family',\n 'restroom.female',\n 'restroom.female.wheelchair',\n 'restroom.male',\n 'restroom.male.wheelchair',\n 'restroom.transgender',\n 'restroom.transgender.wheelchair',\n 'restroom.unisex',\n 'restroom.unisex.wheelchair',\n 'restroom.wheelchair',\n 'road',\n 'room',\n 'serverroom',\n 'shower',\n 'smokingarea',\n 'stairs',\n 'steps',\n 'storage',\n 'structure',\n 'terrace',\n 'theater',\n 'unenclosedarea',\n 'unspecified',\n 'vegetation',\n 'waitingroom',\n 'walkway',\n 'walkway.island',\n 'wood',\n];\n\nexport const NONIMDF_FEATURE_TYPES: FeatureType[] = [\n \"taxonomy\",\n \"event\",\n \"promotion\",\n \"label\",\n \"privilege\",\n]\n\nexport const GEOJSON_FEATURE_TYPES: FeatureType[] = [\n ...IMDF_FEATURE_TYPES,\n ...NONIMDF_FEATURE_TYPES,\n]\n\nexport const ALL_FEATURE_TYPES: FeatureType[] = [\n ...GEOJSON_FEATURE_TYPES,\n \"sponsored-content\",\n \"element\",\n]\n\nexport const defaultFeatureQueryOptionsMap: Record<\n FeatureType,\n FeatureQueryOptions\n> = {\n // IMDF\n address: {},\n amenity: {},\n anchor: {},\n building: {},\n detail: { enabled: false },\n fixture: {},\n footprint: {},\n geofence: { enabled: false },\n kiosk: {},\n level: {},\n occupant: {\n refetchInterval: 5 * 60 * 1000, // refresh every 5 min\n staleTime: 5 * 60 * 1000,\n },\n opening: {},\n relationship: {},\n section: {},\n unit: {},\n venue: {},\n\n // OTHERS GEOJSON\n taxonomy: {},\n privilege: {},\n event: {},\n promotion: {\n refetchInterval: 0.5 * 60 * 1000, // refresh every 5 min\n staleTime: 0.5 * 60 * 1000,\n },\n label: {},\n\n // NON GEOJSON\n \"sponsored-content\": {\n refetchInterval: 1 * 60 * 1000, // refresh every 5 min\n },\n element: {},\n page: {},\n model3d: {}\n}\n","import type {\n FeatureResponseMap,\n FeatureType,\n SponsoredContentStrapiV4ApiResponse,\n} from \"../types/feature-api\"\nimport { DEFAULT_BASE_URL } from \"../constant\"\n\nexport async function fetchDeliveryApi<T extends FeatureType = FeatureType>(\n projectId: string,\n apiKey: string,\n featureType: FeatureType,\n baseUrl: string = DEFAULT_BASE_URL,\n): Promise<FeatureResponseMap[T][]> {\n // TODO: Update Label Endpoint to match other endpoints\n switch (featureType) {\n case \"label\":\n case \"element\": {\n const pluralFeatureType = `${featureType}s`\n const res = await fetch(\n `${baseUrl}/delivery/projects/${projectId}/${pluralFeatureType}.geojson?api-key=${apiKey}`\n )\n if (res.status !== 200) return []\n const items = await res.json()\n return items\n }\n\n case \"model3d\": {\n const res = await fetch(\n `${baseUrl}/delivery/projects/${projectId}/${featureType}.geojson?api-key=${apiKey}`\n )\n if (res.status !== 200) return []\n const items = await res.json()\n return items.features\n }\n\n case \"sponsored-content\": {\n const res = await fetch(\n `${baseUrl}/delivery/projects/${projectId}/sponsored-content.json?api-key=${apiKey}`\n )\n if (res.status !== 200) return []\n const jsonRes = await res.json()\n const items = jsonRes.data as SponsoredContentStrapiV4ApiResponse[]\n return items.map((item) => ({\n id: item.id,\n ...item.attributes,\n })) as FeatureResponseMap[T][]\n }\n\n default: {\n const res = await fetch(\n `${baseUrl}/delivery/projects/${projectId}/imdf/${featureType}.geojson?api-key=${apiKey}`\n )\n if (res.status !== 200) return []\n const collections = await res.json()\n return collections.features\n }\n }\n}\n\n\nexport async function fetchPreviewApi<T extends FeatureType = FeatureType>(\n projectId: string,\n previewToken: string,\n featureType: FeatureType,\n baseUrl: string = DEFAULT_BASE_URL,\n): Promise<FeatureResponseMap[T][]> {\n // TODO: Update Label Endpoint to match other endpoints\n switch (featureType) {\n case \"label\":\n case \"element\": {\n const pluralFeatureType = `${featureType}s`\n const res = await fetch(\n `${baseUrl}/preview/projects/${projectId}/${pluralFeatureType}.geojson`, {\n headers: {\n Authorization: `Bearer ${previewToken}`\n }\n }\n )\n if (res.status !== 200) return []\n const items = await res.json()\n return items\n }\n\n case \"sponsored-content\": {\n const res = await fetch(\n `${baseUrl}/preview/projects/${projectId}/sponsored-content.json`, {\n headers: {\n Authorization: `Bearer ${previewToken}`\n }\n }\n )\n if (res.status !== 200) return []\n const jsonRes = await res.json()\n const items = jsonRes.data as SponsoredContentStrapiV4ApiResponse[]\n return items.map((item) => ({\n id: item.id,\n ...item.attributes,\n })) as FeatureResponseMap[T][]\n }\n\n default: {\n const res = await fetch(\n `${baseUrl}/preview/projects/${projectId}/imdf/${featureType}.geojson`, {\n headers: {\n Authorization: `Bearer ${previewToken}`\n }\n }\n )\n if (res.status !== 200) return []\n const collections = await res.json()\n return collections.features\n }\n }\n}\n\nexport const safeFetchFeature = async <T extends FeatureType = FeatureType>(\n featureType: FeatureType,\n params: { \n mode: 'delivery' | 'preview',\n projectId: string,\n apiKey: string,\n previewToken?: string,\n baseUrl: string\n } \n): Promise<FeatureResponseMap[T][]> => {\n const mode = params.mode ?? 'delivery'\n const projectId = params.projectId\n const apiKey = params.apiKey\n const previewToken = params.previewToken\n const baseUrl = params.baseUrl ?? DEFAULT_BASE_URL\n\n try {\n let result = []\n \n if (mode === 'delivery') {\n result = await fetchDeliveryApi<T>(\n projectId,\n apiKey,\n featureType,\n baseUrl\n )\n } else if (mode === 'preview') {\n result = await fetchPreviewApi<T>(\n projectId,\n previewToken,\n featureType,\n baseUrl\n )\n }\n return result ?? []\n } catch (e) {\n // Suppress error and return []\n return Promise.resolve([])\n }\n}\n","import { Geometry, GeometryCollection, Position } from \"geojson\"\n\n/**\n * Checks if a point is a valid coordinate pair.\n *\n * @param point - The point to be checked.\n * @return True if the point is a valid coordinate pair, false otherwise.\n */\nexport const isValidCoordinate = (point: Position): boolean => {\n return point.length === 2 && point.every((coord) => typeof coord === \"number\")\n}\n\n/**\n * Checks if a set of points forms a valid linear ring (closed and simple polygon).\n *\n * @param ring - The array of points representing a linear ring.\n * @return True if the linear ring is valid, false otherwise.\n */\nfunction isValidLinearRingCoordinates(ring: Position[]): boolean {\n if (ring.length < 4) {\n return false\n }\n\n return (\n ring.every(isValidCoordinate) &&\n ring[0][0] === ring[ring.length - 1][0] &&\n ring[0][1] === ring[ring.length - 1][1]\n )\n}\n\n/**\n * Checks if an input represents a valid polygon, which may include holes.\n * The input can be a single array of coordinates for simple polygons, or\n * an array of arrays of coordinates for polygons with holes.\n *\n * @param polygon - The input representing a polygon.\n * @return True if the polygon is valid, false otherwise.\n */\nexport const isValidPolygonCoordinates = (\n polygon: Position[] | Position[][]\n): boolean => {\n // Check if it's a simple polygon (without holes)\n if (\n Array.isArray(polygon[0]) &&\n (polygon[0].length === 0 || typeof polygon[0][0] === \"number\")\n ) {\n return isValidLinearRingCoordinates(polygon as Position[])\n }\n\n // Check if it's a polygon with holes\n if (\n Array.isArray(polygon) &&\n polygon.length > 0 &&\n Array.isArray(polygon[0])\n ) {\n // Check the outer ring\n if (!isValidLinearRingCoordinates(polygon[0] as Position[])) {\n return false\n }\n\n // Check each hole\n for (let i = 1; i < polygon.length; i++) {\n if (!isValidLinearRingCoordinates(polygon[i] as Position[])) {\n return false\n }\n }\n\n return true\n }\n\n return false\n}\n\n/**\n * Checks if an array of polygons forms a valid MultiPolygon.\n *\n * @param multipolygon - The array of polygons.\n * @return True if the multipolygon is valid, false otherwise.\n */\nexport const isValidMultiPolygonCoordinates = (\n multipolygon: Position[][][]\n): boolean => {\n return multipolygon.every(isValidPolygonCoordinates)\n}\n\n/**\n * Checks if a set of points forms a valid LineString.\n * A valid LineString must have at least two points, each point must be a valid coordinate,\n * and it should not form a closed loop.\n *\n * @param lineString - The array of points representing a LineString.\n * @return True if the LineString is valid, false otherwise.\n */\nexport const isValidLineStringCoordinates = (\n lineString: Position[]\n): boolean => {\n if (!Array.isArray(lineString) || lineString.length < 2) {\n return false\n }\n\n // Check if the first and last points are the same, which would make it a polygon\n const firstPoint = lineString[0]\n const lastPoint = lineString[lineString.length - 1]\n if (firstPoint[0] === lastPoint[0] && firstPoint[1] === lastPoint[1]) {\n return false\n }\n\n return lineString.every(isValidCoordinate)\n}\n\nexport const isValidMultiPolygon = (\n geometry: Exclude<Geometry, GeometryCollection>\n): boolean => {\n const { type, coordinates } = geometry\n return type === \"MultiPolygon\" && isValidMultiPolygonCoordinates(coordinates)\n}\n\nexport const isValidPolygon = (\n geometry: Exclude<Geometry, GeometryCollection>\n): boolean => {\n const { type, coordinates } = geometry\n return type === \"Polygon\" && isValidPolygonCoordinates(coordinates)\n}\n\nexport const isValidLineString = (\n geometry: Exclude<Geometry, GeometryCollection>\n): boolean => {\n const { type, coordinates } = geometry\n return type === \"LineString\" && isValidLineStringCoordinates(coordinates)\n}\n\nexport const isValidPoint = (\n geometry: Exclude<Geometry, GeometryCollection>\n): boolean => {\n const { type, coordinates } = geometry\n return type === \"Point\" && isValidCoordinate(coordinates)\n}\n","import type { Value, InFilter, Filter, Filters } from '../types/match-filters'\n\nfunction isInFilter(filter: Filter): filter is InFilter {\n return (\n typeof filter === \"object\" &&\n filter !== null &&\n \"$in\" in filter &&\n Array.isArray((filter as any).$in)\n );\n}\n\nconst someIntersect = (a: Value[], b: Value[]) => a.some(v => b.includes(v));\n\nexport function matchFilter(value: Value | Value[], filter: Filter) {\n\n if (Array.isArray(value)) {\n if (isInFilter(filter)) return someIntersect(value, filter.$in);\n \n // Equal\n return value.includes(filter as Value);\n \n } else {\n if (isInFilter(filter)) return filter.$in.includes(value);\n \n // Equal\n return value === filter;\n }\n}\n\nexport function matchFilters<T extends Record<string, any>>(item: T, filters: Filters): boolean {\n return Object.entries(filters).every(([key, filter]) => {\n return matchFilter(item.properties[key], filter)\n });\n}","import { compact } from \"../utils/lodash\"\nimport { KioskFeaturePopulated, OccupantFeaturePopulated, UnitFeaturePopulated } from \"../types\";\n\nexport const getOccupantMainLocation = (occupant: OccupantFeaturePopulated): UnitFeaturePopulated | KioskFeaturePopulated => {\n return occupant.properties.kiosk || occupant.properties.unit\n}\n\nexport const getOccupantCorrelatedLocations = (occupant: OccupantFeaturePopulated): Array<UnitFeaturePopulated | KioskFeaturePopulated> => {\n\n const allCorrelatedLocations = [\n ...occupant.properties.units,\n ...occupant.properties.kiosks,\n ]\n\n return compact(allCorrelatedLocations)\n}\n\nexport type OccupantMarkerPlacementType = 'ONCE_PER_LEVEL' | 'ALL_LOCATIONS'\n\nexport const getOccupantMarkerLocations = (occupant: OccupantFeaturePopulated, options?: { type: OccupantMarkerPlacementType }): Array<UnitFeaturePopulated | KioskFeaturePopulated> => {\n\n /**\n * Use optiosn.type first\n * THEN occupant.show_name_on_all_units \n */\n const placementType = options?.type ? options.type : occupant.properties.show_name_on_all_units ? 'ALL_LOCATIONS' : 'ONCE_PER_LEVEL'\n\n const mainLocation = getOccupantMainLocation(occupant)\n\n const mainLocationLevel = mainLocation?.properties?.level_id\n const allCorrelatedLocations = getOccupantCorrelatedLocations(occupant)\n\n // IF showNameonAllLocations = true, Show All \n if (placementType === 'ALL_LOCATIONS') {\n return compact([mainLocation, ...allCorrelatedLocations])\n }\n \n // ELSE Show Once per level\n const otherLevelLocations = allCorrelatedLocations.filter((f) => f.properties.level_id !== mainLocationLevel)\n const onePerLevelLocations = [...new Map(otherLevelLocations.map(loc => [loc.properties.level_id, loc])).values()]\n return compact([mainLocation, ...onePerLevelLocations])\n}\n","export const compact = <T extends unknown = unknown>(arr: T[]): T[] => arr.filter(item => Boolean(item));\n","import { safeFetchFeature } from \"./api/delivery-project\"\nimport { FeatureResponseMap, FeatureType, ImdfFeature } from \"./types/feature-api\"\nimport {\n EnsureQueryDataOptions,\n QueryClient,\n QueryObserver,\n} from \"@tanstack/query-core\"\nimport {\n FeatureQueryOptions,\n FilterParams,\n FindParams,\n InternalFilterByType,\n InternalFindById,\n PopulatedParams,\n SearchClient,\n VenueClientOptions,\n VenueDataClient,\n} from \"./types/VenueDataClient\"\nimport { createPopulator } from \"./populator\"\nimport { FeaturePopulatedResponseMap } from \"./types\"\nimport { matchFilters } from \"./utils/match-filters\"\nimport { FuseResult } from \"fuse.js\"\nimport { getSearchClient } from \"./search/getSearchClient\"\n\nexport const getDataClient = (options: VenueClientOptions): VenueDataClient => {\n let searchClient: SearchClient;\n\n const observers = new Map<\n FeatureType,\n { observer: QueryObserver<any, any>, unsubscribe: () => void }\n >()\n\n const queryClient = options.queryClient ?? new QueryClient()\n const { mode = 'delivery', projectId, apiKey, baseUrl, previewToken } = options\n\n if (!projectId)\n throw new Error(\n \"Cannot create VenueDataClient. Reason: `projectId` is missing\"\n )\n \n if (mode === 'delivery' && !apiKey)\n throw new Error(\n \"Cannot create VenueDataClient. Reason: `apiKey` is missing\"\n )\n\n if (mode === 'preview' && !previewToken)\n throw new Error(\n \"Cannot create VenueDataClient. Reason: `previewToken` is missing\"\n )\n\n const createDeliveryApiQueryOptions = <T extends FeatureType = FeatureType>(\n featureType: T\n ) => ({\n queryKey: [\"_deliveryapi\", featureType] as const,\n queryFn: () => safeFetchFeature<T>(featureType, { mode, projectId, apiKey, previewToken, baseUrl }),\n })\n\n /**\n * Internal Functions\n * ***********************************/\n const internalFilterByType: InternalFilterByType = async <T extends FeatureType = FeatureType>(\n featureType: T\n ) => {\n\n try {\n const features = await queryClient.ensureQueryData<\n FeatureResponseMap[T][],\n unknown,\n FeatureResponseMap[T][]\n >(createDeliveryApiQueryOptions(featureType))\n return features\n } catch (error) {\n throw error\n }\n }\n\n const internalFindById: InternalFindById = async <T extends FeatureType = FeatureType>(\n id: string\n ) => {\n if (id === null || id === undefined) return null\n const featureType = id.slice(0, id.lastIndexOf(\"-\")) as FeatureType\n const feature = await queryClient.ensureQueryData<FeatureResponseMap[T]>({\n queryKey: [\"_deliveryapi\", featureType, id],\n queryFn: async () => {\n const features = await internalFilterByType(featureType)\n const feature = features.find(\n (f) => f.id === id\n ) as FeatureResponseMap[T]\n return feature ?? null\n },\n })\n return feature\n }\n\n // Create `Feature Populator` with internal functions\n const populator = createPopulator({ internalFindById, internalFilterByType })\n\n /**\n * Public Functions\n * ***********************************/\n const registerObserver = (\n featureType: FeatureType,\n refetchInterval: number\n ) => {\n if (observers.has(featureType)) {\n console.warn(`Observer for ${featureType} already exists`)\n const record = observers.get(featureType)\n return record.observer\n }\n const options = createDeliveryApiQueryOptions(featureType)\n const observer = new QueryObserver(queryClient, {\n ...options,\n refetchInterval,\n })\n const unsubscribe = observer.subscribe(() => {\n console.log(`[venue-js] Listening to ${featureType} changes (interval = ${refetchInterval}ms)`)\n // TODO: add logs or what to do after subscribe\n })\n observers.set(featureType, { observer, unsubscribe })\n\n return observer\n }\n\n const destroyObserver = (featureType: FeatureType) => {\n const record = observers.get(featureType)\n if (!record) return\n\n record.unsubscribe()\n observers.delete(featureType)\n }\n\n const destroyObservers = () => {\n observers.forEach(({ observer, unsubscribe }) => {\n unsubscribe()\n observer.destroy()\n })\n observers.clear()\n }\n\n const createFilterByTypeQueryOptions = <T extends FeatureType = FeatureType>(\n featureType: T,\n params: FilterParams = {},\n options: FeatureQueryOptions = {}\n ): EnsureQueryDataOptions<FeatureResponseMap[T][] | FeaturePopulatedResponseMap[T][]> => ({\n queryKey: [featureType, \"list\", params] as const,\n queryFn: async () => {\n const features = await internalFilterByType<T>(featureType)\n \n // Filter \n const filters = params.filters ?? {}\n let result = features\n if (params.filters) {\n result = features.filter(f => matchFilters(f, filters))\n }\n\n // Populate\n return params.populate === true\n ? await Promise.all(result.map((f) => populator[featureType](f)))\n : result\n },\n ...(options ?? {}),\n })\n\n const createFindByIdQueryOptions = <T extends FeatureType = FeatureType>(\n featureType: T,\n id: string,\n params: FindParams = {},\n options: FeatureQueryOptions = {}\n ): EnsureQueryDataOptions<FeatureResponseMap[T] | FeaturePopulatedResponseMap[T]> => ({\n queryKey: [featureType, \"detail\", id, params] as const,\n queryFn: async () => {\n const feature = await internalFindById<T>(id)\n return params.populate === true\n ? await populator[featureType](feature)\n : Promise.resolve(feature)\n },\n ...(options ?? {}),\n })\n\n async function filterByType<T extends FeatureType>(featureType: T, params: FilterParams & PopulatedParams): Promise<FeaturePopulatedResponseMap[T][]>\n async function filterByType<T extends FeatureType>(featureType: T, params?: FilterParams): Promise<FeatureResponseMap[T][]>\n async function filterByType<T extends FeatureType>(featureType: T, params?: FilterParams) {\n const filterQueryOptions = createFilterByTypeQueryOptions<T>(\n featureType,\n params\n )\n const features = await queryClient.ensureQueryData(filterQueryOptions)\n return (params?.populate === true) ? features as FeaturePopulatedResponseMap[T][] : features as FeatureResponseMap[T][]\n }\n\n async function findById<T extends FeatureType>(featureType: T, id: string, params: FindParams & PopulatedParams): Promise<FeaturePopulatedResponseMap[T]>\n async function findById<T extends FeatureType>(featureType: T, id: string, params?: FindParams): Promise<FeatureResponseMap[T]>\n async function findById<T extends FeatureType>( featureType: T, id: string, params?: FindParams) {\n const findQueryOptions = createFindByIdQueryOptions<T>(\n featureType,\n id,\n params\n )\n const feature = await queryClient.ensureQueryData(findQueryOptions)\n return feature\n }\n\n const searchFn = async (txt: string): Promise<FuseResult<ImdfFeature>[]> => {\n if (!searchClient) {\n const [occupants, amenities] = await Promise.all([\n filterByType(\"occupant\"),\n filterByType(\"amenity\")\n ])\n const haystack = { occupants, amenities }\n searchClient = getSearchClient(haystack)\n }\n return searchClient.search(txt)\n }\n\n return {\n projectId,\n queryClient,\n registerObserver,\n destroyObserver,\n destroyObservers,\n createFilterByTypeQueryOptions,\n createFindByIdQueryOptions,\n _internalFindById: internalFindById,\n filterByType,\n findById,\n search: searchFn,\n }\n}\n","import {\n FeatureResponseMap,\n FeaturePopulatedResponseMap,\n InternalFindById,\n InternalFilterByType,\n SectionFeature,\n} from \"../types\"\nimport { compact } from '../utils/lodash'\n\nimport { center } from '@turf/center'\nimport { booleanPointInPolygon } from \"@turf/boolean-point-in-polygon\";\nimport { findContainingUnit } from \"../utils/findContaining\";\n\ntype CreatePopulatorOptions = {\n internalFindById: InternalFindById\n internalFilterByType: InternalFilterByType\n}\n\ntype PopulatableFeatureType = Extract<\n keyof FeatureResponseMap,\n keyof FeaturePopulatedResponseMap\n>\ntype PopulatorFn<T extends PopulatableFeatureType> = (\n f: FeatureResponseMap[T]\n) => Promise<FeaturePopulatedResponseMap[T]>\n\nexport type Populator = {\n [K in PopulatableFeatureType]?: PopulatorFn<K>\n}\n\nexport const createPopulator = ({\n internalFindById,\n internalFilterByType,\n}: CreatePopulatorOptions): Populator => {\n const populateAddress: PopulatorFn<\"address\"> = (address) =>\n Promise.resolve(address)\n const populateBuilding: PopulatorFn<\"building\"> = (building) =>\n Promise.resolve(building)\n const populateDetail: PopulatorFn<\"detail\"> = (detail) =>\n Promise.resolve(detail)\n const populateFootprint: PopulatorFn<\"footprint\"> = (footprint) =>\n Promise.resolve(footprint)\n const populateGeofence: PopulatorFn<\"geofence\"> = (geofence) =>\n Promise.resolve(geofence)\n\n const populatePrivilege: PopulatorFn<\"privilege\"> = (privilege) =>\n Promise.resolve(privilege)\n const populateEvent: PopulatorFn<\"event\"> = (event) => Promise.resolve(event)\n\n const populatePromotion: PopulatorFn<\"promotion\"> = async (promotion) => {\n const venue = await internalFindById<\"venue\">(promotion.properties.venue_id)\n return {\n ...promotion,\n properties: {\n ...promotion.properties,\n venue,\n },\n }\n }\n\n const populateAmenity: PopulatorFn<\"amenity\"> = async (amenity) => {\n const units = await Promise.all(\n amenity.properties.unit_ids.map(internalFindById<\"unit\">)\n )\n\n const populatedUnits = await Promise.all(units.map(populateUnit))\n\n const venue = await internalFindById<\"venue\">(amenity.properties.venue_id)\n\n const defaultLevel = populatedUnits[0].properties.level\n\n const kiosks = await internalFilterByType<\"kiosk\">(\"kiosk\")\n const ordinalKiosks = kiosks.filter(\n (kiosk) => kiosk.properties.level_id === defaultLevel.id\n )\n const kiosk = ordinalKiosks.find((kiosk) => booleanPointInPolygon(amenity, kiosk))\n return {\n ...amenity,\n properties: {\n ...amenity.properties,\n ordinal: defaultLevel.properties.ordinal,\n level_name: defaultLevel.properties.name.en,\n level: defaultLevel,\n units: populatedUnits,\n venue,\n _experimental_kiosk: kiosk ? await populateKiosk(kiosk) : null,\n },\n }\n }\n\n const populateAnchor: PopulatorFn<\"anchor\"> = async (anchor) => {\n const unit = await internalFindById<\"unit\">(anchor.properties.unit_id)\n const venue = await internalFindById<\"venue\">(unit.properties.venue_id)\n const level = await internalFindById<\"level\">(unit.properties.level_id)\n\n const sections = await internalFilterByType<\"section\">(\"section\")\n const section = sections.find((section) => booleanPointInPolygon(anchor, section))\n\n return {\n ...anchor,\n properties: {\n ...anchor.properties,\n level: await populateLevel(level),\n unit: await populateUnit(unit),\n section: section ? await populateSection(section) : null,\n venue: await populateVenue(venue),\n ordinal: level.properties.ordinal,\n },\n }\n }\n\n const populateFixture: PopulatorFn<\"fixture\"> = async (fixture) => {\n const level = await internalFindById<\"level\">(fixture.properties.level_id)\n const venue = await internalFindById<\"venue\">(fixture.properties.venue_id)\n const anchor = await internalFindById<\"anchor\">(fixture.properties.anchor_id)\n\n return {\n ...fixture,\n properties: {\n ...fixture.properties,\n anchor: anchor ? await populateAnchor(anchor) : null,\n level: await populateLevel(level),\n venue: await populateVenue(venue),\n ordinal: level.properties.ordinal,\n }\n }\n }\n\n const populateKiosk: PopulatorFn<\"kiosk\"> = async (kiosk) => {\n const level = await internalFindById<\"level\">(kiosk.properties.level_id)\n const venue = await internalFindById<\"venue\">(kiosk.properties.venue_id)\n const anchor = await internalFindById<\"anchor\">(kiosk.properties.anchor_id)\n\n // Find Kiosk's Unit\n const units = await internalFilterByType<\"unit\">(\"unit\")\n const unit = findContainingUnit(kiosk, units.filter(unit => unit.properties.category === \"walkway\"))\n\n let section: SectionFeature | null = null\n\n if (anchor) {\n const sections = await internalFilterByType<\"section\">(\"section\")\n section = sections.find((section) => booleanPointInPolygon(anchor, section))\n }\n\n return {\n ...kiosk,\n properties: {\n ...kiosk.properties,\n anchor: anchor ? await populateAnchor(anchor) : null,\n level: await populateLevel(level),\n venue: await populateVenue(venue),\n ordinal: level.properties.ordinal,\n\n unit: unit ? await populateUnit(unit) : null,\n section: section ? await populateSection(section) : null,\n },\n }\n }\n\n const populateLevel: PopulatorFn<\"level\"> = async (level) => {\n const venue = await internalFindById<\"venue\">(level.properties.venue_id)\n return {\n ...level,\n properties: {\n ...level.properties,\n venue,\n },\n }\n }\n\n const populateOccupant: PopulatorFn<\"occupant\"> = async (occupant) => {\n const {\n anchor_id,\n venue_id,\n local_category_ids,\n promotion_ids = [],\n privilege_ids = [],\n kiosk_id,\n unit_id,\n kiosk_ids = [],\n unit_ids = [],\n } = occupant.properties\n const anchor = await internalFindById<\"anchor\">(anchor_id)\n const venue = await internalFindById<\"venue\">(venue_id)\n\n const localCategories = await Promise.all(\n local_category_ids.map(internalFindById<\"taxonomy\">)\n )\n const promotions = await Promise.all(\n promotion_ids.map(internalFindById<\"promotion\">)\n )\n const privileges = await Promise.all(\n privilege_ids.map(internalFindById<\"privilege\">)\n )\n const kiosk = await internalFindById<\"kiosk\">(kiosk_id)\n const unit = await internalFindById<\"unit\">(unit_id)\n\n const kiosks = await Promise.all(kiosk_ids.map(internalFindById<\"kiosk\">))\n const units = await Promise.all(unit_ids.map(internalFindById<\"unit\">))\n return {\n ...occupant,\n properties: {\n ...occupant.properties,\n anchor: anchor ? await populateAnchor(anchor) : null,\n local_categories: await Promise.all(\n compact(localCategories).map(populateTaxonomy)\n ),\n venue,\n promotions,\n privileges,\n\n kiosk: kiosk ? await populateKiosk(kiosk) : null,\n unit: unit ? await populateUnit(unit) : null,\n kiosks: await Promise.all(kiosks.map(populateKiosk)),\n units: await Promise.all(units.map(populateUnit)),\n },\n }\n }\n\n const populateOpening: PopulatorFn<\"opening\"> = async (opening) => {\n const venue = await internalFindById<\"venue\">(opening.properties.venue_id)\n const level = await internalFindById<\"level\">(opening.properties.level_id)\n return {\n ...opening,\n properties: {\n venue,\n level: await populateLevel(level),\n ordinal: level.properties.ordinal,\n }\n }\n }\n\n const populateRelationship: PopulatorFn<\"relationship\"> = async (relationship) => {\n const originId = relationship.properties.origin?.id\n const destinationId = relationship.properties.destination?.id\n const origin = originId ? await internalFindById<\"opening\" | \"unit\">(originId) : null\n const destination = destinationId ? await internalFindById<\"opening\" | \"unit\">(destinationId) : null\n const intermediary_ids = (relationship.properties.intermediary || []).map(({ id }) => id)\n const intermediary = await Promise.all(intermediary_ids.map(internalFindById<\"opening\" | \"unit\">))\n\n return {\n ...relationship,\n properties: {\n ...relationship.properties,\n origin,\n destination,\n intermediary,\n }\n }\n }\n\n const populateSection: PopulatorFn<\"section\"> = async (section) => {\n const venue = await internalFindById<\"venue\">(section.properties.venue_id)\n const level = await internalFindById<\"level\">(section.properties.level_id)\n return {\n ...section,\n properties: {\n ...section.properties,\n venue,\n level: await populateLevel(level),\n ordinal: level.properties.ordinal,\n },\n }\n }\n\n const populateUnit: PopulatorFn<\"unit\"> = async (unit) => {\n const venue = await internalFindById<\"venue\">(unit.properties.venue_id)\n const level = await internalFindById<\"level\">(unit.properties.level_id)\n\n const sections = await internalFilterByType<\"section\">(\"section\")\n try {\n const section = unit.geometry.type !== 'MultiPolygon' ? sections.find((section) => booleanPointInPolygon(center(unit), section)) : null\n return {\n ...unit,\n properties: {\n ...unit.properties,\n venue,\n ordinal: level.properties.ordinal,\n level: await populateLevel(level),\n section: section ? await populateSection(section) : null,\n },\n }\n } catch (err) {\n console.log(`error finding section `, { unit, sections })\n }\n }\n\n const populateVenue: PopulatorFn<\"venue\"> = (venue) => {\n return Promise.resolve(venue)\n }\n\n const populateTaxonomy: PopulatorFn<\"taxonomy\"> = async (taxonomy) => {\n const venue = await internalFindById<\"venue\">(taxonomy.properties.venue_id)\n return {\n ...taxonomy,\n properties: {\n ...taxonomy.properties,\n venue: venue ? await populateVenue(venue) : null,\n },\n }\n }\n\n const populateModel3D: PopulatorFn<\"model3d\"> = async (model3d) => {\n const level = await internalFindById<\"level\">(model3d.properties.level_id)\n try {\n return {\n ...model3d,\n properties: {\n ...model3d.properties,\n level: await populateLevel(level),\n },\n }\n } catch (err) {\n console.log(`error finding level`, { model3d, level })\n }\n }\n\n const populateFeature = (feature) => Promise.resolve(feature)\n\n return {\n address: populateAddress,\n building: populateBuilding,\n detail: populateDetail,\n fixture: populateFixture,\n footprint: populateFootprint,\n geofence: populateGeofence,\n opening: populateOpening,\n relationship: populateRelationship,\n privilege: populatePrivilege,\n promotion: populatePromotion,\n event: populateEvent,\n label: populateFeature,\n element: populateFeature,\n page: populateFeature,\n\n amenity: populateAmenity,\n anchor: populateAnchor,\n kiosk: populateKiosk,\n level: populateLevel,\n occupant: populateOccupant,\n section: populateSection,\n unit: populateUnit,\n venue: populateVenue,\n taxonomy: populateTaxonomy,\n\n model3d: populateModel3D,\n }\n}\n","import { center } from '@turf/center'\nimport { booleanPointInPolygon } from \"@turf/boolean-point-in-polygon\";\nimport { AmenityFeature, KioskFeature, UnitFeature } from \"../types\"\n\nexport const findContainingUnit = (poi: KioskFeature | AmenityFeature, units: UnitFeature[]): UnitFeature | null => {\n const unit = units.find(\n (unit) => {\n try {\n return unit.properties.level_id === poi.properties.level_id\n && booleanPointInPolygon(center(poi), unit)\n } catch (e) {\n console.log(`Cannot find containing unit of (${poi.id}):`, e.message)\n return false\n }\n }\n )\n return unit\n}\n","/**\n * Fuse.js v7.1.0 - Lightweight fuzzy-search (http://fusejs.io)\n *\n * Copyright (c) 2025 Kiro Risk (http://kiro.me)\n * All Rights Reserved. Apache Software License 2.0\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n */\n\nfunction isArray(value) {\n return !Array.isArray\n ? getTag(value) === '[object Array]'\n : Array.isArray(value)\n}\n\n// Adapted from: https://github.com/lodash/lodash/blob/master/.internal/baseToString.js\nconst INFINITY = 1 / 0;\nfunction baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value\n }\n let result = value + '';\n return result == '0' && 1 / value == -INFINITY ? '-0' : result\n}\n\nfunction toString(value) {\n return value == null ? '' : baseToString(value)\n}\n\nfunction isString(value) {\n return typeof value === 'string'\n}\n\nfunction isNumber(value) {\n return typeof value === 'number'\n}\n\n// Adapted from: https://github.com/lodash/lodash/blob/master/isBoolean.js\nfunction isBoolean(value) {\n return (\n value === true ||\n value === false ||\n (isObjectLike(value) && getTag(value) == '[object Boolean]')\n )\n}\n\nfunction isObject(value) {\n return typeof value === 'object'\n}\n\n// Checks if `value` is object-like.\nfunction isObjectLike(value) {\n return isObject(value) && value !== null\n}\n\nfunction isDefined(value) {\n return value !== undefined && value !== null\n}\n\nfunction isBlank(value) {\n return !value.trim().length\n}\n\n// Gets the `toStringTag` of `value`.\n// Adapted from: https://github.com/lodash/lodash/blob/master/.internal/getTag.js\nfunction getTag(value) {\n return value == null\n ? value === undefined\n ? '[object Undefined]'\n : '[object Null]'\n : Object.prototype.toString.call(value)\n}\n\nconst EXTENDED_SEARCH_UNAVAILABLE = 'Extended search is not available';\n\nconst INCORRECT_INDEX_TYPE = \"Incorrect 'index' type\";\n\nconst LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = (key) =>\n `Invalid value for key ${key}`;\n\nconst PATTERN_LENGTH_TOO_LARGE = (max) =>\n `Pattern length exceeds max of ${max}.`;\n\nconst MISSING_KEY_PROPERTY = (name) => `Missing ${name} property in key`;\n\nconst INVALID_KEY_WEIGHT_VALUE = (key) =>\n `Property 'weight' in key '${key}' must be a positive integer`;\n\nconst hasOwn = Object.prototype.hasOwnProperty;\n\nclass KeyStore {\n constructor(keys) {\n this._keys = [];\n this._keyMap = {};\n\n let totalWeight = 0;\n\n keys.forEach((key) => {\n let obj = createKey(key);\n\n this._keys.push(obj);\n this._keyMap[obj.id] = obj;\n\n totalWeight += obj.weight;\n });\n\n // Normalize weights so that their sum is equal to 1\n this._keys.forEach((key) => {\n key.weight /= totalWeight;\n });\n }\n get(keyId) {\n return this._keyMap[keyId]\n }\n keys() {\n return this._keys\n }\n toJSON() {\n return JSON.stringify(this._keys)\n }\n}\n\nfunction createKey(key) {\n let path = null;\n let id = null;\n let src = null;\n let weight = 1;\n let getFn = null;\n\n if (isString(key) || isArray(key)) {\n src = key;\n path = createKeyPath(key);\n id = createKeyId(key);\n } else {\n if (!hasOwn.call(key, 'name')) {\n throw new Error(MISSING_KEY_PROPERTY('name'))\n }\n\n const name = key.name;\n src = name;\n\n if (hasOwn.call(key, 'weight')) {\n weight = key.weight;\n\n if (weight <= 0) {\n throw new Error(INVALID_KEY_WEIGHT_VALUE(name))\n }\n }\n\n path = createKeyPath(name);\n id = createKeyId(name);\n getFn = key.getFn;\n }\n\n return { path, id, weight, src, getFn }\n}\n\nfunction createKeyPath(key) {\n return isArray(key) ? key : key.split('.')\n}\n\nfunction createKeyId(key) {\n return isArray(key) ? key.join('.') : key\n}\n\nfunction get(obj, path) {\n let list = [];\n let arr = false;\n\n const deepGet = (obj, path, index) => {\n if (!isDefined(obj)) {\n return\n }\n if (!path[index]) {\n // If there's no path left, we've arrived at the object we care about.\n list.push(obj);\n } else {\n let key = path[index];\n\n const value = obj[key];\n\n if (!isDefined(value)) {\n return\n }\n\n // If we're at the last value in the path, and if it's a string/number/bool,\n // add it to the list\n if (\n index === path.length - 1 &&\n (isString(value) || isNumber(value) || isBoolean(value))\n ) {\n list.push(toString(value));\n } else if (isArray(value)) {\n arr = true;\n // Search each item in the array.\n for (let i = 0, len = value.length; i < len; i += 1) {\n deepGet(value[i], path, index + 1);\n }\n } else if (path.length) {\n // An object. Recurse further.\n deepGet(value, path, index + 1);\n }\n }\n };\n\n // Backwards compatibility (since path used to be a string)\n deepGet(obj, isString(path) ? path.split('.') : path, 0);\n\n return arr ? list : list[0]\n}\n\nconst MatchOptions = {\n // Whether the matches should be included in the result set. When `true`, each record in the result\n // set will include the indices of the matched characters.\n // These can consequently be used for highlighting purposes.\n includeMatches: false,\n // When `true`, the matching function will continue to the end of a search pattern even if\n // a perfect match has already been located in the string.\n findAllMatches: false,\n // Minimum number of characters that must be matched before a result is considered a match\n minMatchCharLength: 1\n};\n\nconst BasicOptions = {\n // When `true`, the algorithm continues searching to the end of the input even if a perfect\n // match is found before the end of the same input.\n isCaseSensitive: false,\n // When `true`, the algorithm will ignore diacritics (accents) in comparisons\n ignoreDiacritics: false,\n // When true, the matching function will continue to the end of a search pattern even if\n includeScore: false,\n // List of properties that will be searched. This also supports nested properties.\n keys: [],\n // Whether to sort the result list, by score\n shouldSort: true,\n // Default sort function: sort by ascending score, ascending index\n sortFn: (a, b) =>\n a.score === b.score ? (a.idx < b.idx ? -1 : 1) : a.score < b.score ? -1 : 1\n};\n\nconst FuzzyOptions = {\n // Approximately where in the text is the pattern expected to be found?\n location: 0,\n // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match\n // (of both letters and location), a threshold of '1.0' would match anything.\n threshold: 0.6,\n // Determines how close the match must be to the fuzzy location (specified above).\n // An exact letter match which is 'distance' characters away from the fuzzy location\n // would score as a complete mismatch. A distance of '0' requires the match be at\n // the exact location specified, a threshold of '1000' would require a perfect match\n // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold.\n distance: 100\n};\n\nconst AdvancedOptions = {\n // When `true`, it enables the use of unix-like search commands\n useExtendedSearch: false,\n // The get function to use when fetching an object's properties.\n // The default will search nested paths *ie foo.bar.baz*\n getFn: get,\n // When `true`, search will ignore `location` and `distance`, so it won't matter\n // where in the string the pattern appears.\n // More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score\n ignoreLocation: false,\n // When `true`, the calculation for the relevance score (used for sorting) will\n // ignore the field-length norm.\n // More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm\n ignoreFieldNorm: false,\n // The weight to determine how much field length norm effects scoring.\n fieldNormWeight: 1\n};\n\nvar Config = {\n ...BasicOptions,\n ...MatchOptions,\n ...FuzzyOptions,\n ...AdvancedOptions\n};\n\nconst SPACE = /[^ ]+/g;\n\n// Field-length norm: the shorter the field, the higher the weight.\n// Set to 3 decimals to reduce index size.\nfunction norm(weight = 1, mantissa = 3) {\n const cache = new Map();\n const m = Math.pow(10, mantissa);\n\n return {\n get(value) {\n const numTokens = value.match(SPACE).length;\n\n if (cache.has(numTokens)) {\n return cache.get(numTokens)\n }\n\n // Default function is 1/sqrt(x), weight makes that variable\n const norm = 1 / Math.pow(numTokens, 0.5 * weight);\n\n // In place of `toFixed(mantissa)`, for faster computation\n const n = parseFloat(Math.round(norm * m) / m);\n\n cache.set(numTokens, n);\n\n return n\n },\n clear() {\n cache.clear();\n }\n }\n}\n\nclass FuseIndex {\n constructor({\n getFn = Config.getFn,\n fieldNormWeight = Config.fieldNormWeight\n } = {}) {\n this.norm = norm(fieldNormWeight, 3);\n this.getFn = getFn;\n this.isCreated = false;\n\n this.setIndexRecords();\n }\n setSources(docs = []) {\n this.docs = docs;\n }\n setIndexRecords(records = []) {\n this.records = records;\n }\n setKeys(keys = []) {\n this.keys = keys;\n this._keysMap = {};\n keys.forEach((key, idx) => {\n this._keysMap[key.id] = idx;\n });\n }\n create() {\n if (this.isCreated || !this.docs.length) {\n return\n }\n\n this.isCreated = true;\n\n // List is Array<String>\n if (isString(this.docs[0])) {\n this.docs.forEach((doc, docIndex) => {\n this._addString(doc, docIndex);\n });\n } else {\n // List is Array<Object>\n this.docs.forEach((doc, docIndex) => {\n this._addObject(doc, docIndex);\n });\n }\n\n this.norm.clear();\n }\n // Adds a doc to the end of the index\n add(doc) {\n const idx = this.size();\n\n if (isString(doc)) {\n this._addString(doc, idx);\n } else {\n this._addObject(doc, idx);\n }\n }\n // Removes the doc at the specified index of the index\n removeAt(idx) {\n this.records.splice(idx, 1);\n\n // Change ref index of every subsquent doc\n for (let i = idx, len = this.size(); i < len; i += 1) {\n this.records[i].i -= 1;\n }\n }\n getValueForItemAtKeyId(item, keyId) {\n return item[this._keysMap[keyId]]\n }\n size() {\n return this.records.length\n }\n _addString(doc, docIndex) {\n if (!isDefined(doc) || isBlank(doc)) {\n return\n }\n\n let record = {\n v: doc,\n i: docIndex,\n n: this.norm.get(doc)\n };\n\n this.records.push(record);\n }\n _addObject(doc, docIndex) {\n let record = { i: docIndex, $: {} };\n\n // Iterate over every key (i.e, path), and fetch the value at that key\n this.keys.forEach((key, keyIndex) => {\n let value = key.getFn ? key.getFn(doc) : this.getFn(doc, key.path);\n\n if (!isDefined(value)) {\n return\n }\n\n if (isArray(value)) {\n let subRecords = [];\n const stack = [{ nestedArrIndex: -1, value }];\n\n while (stack.length) {\n const { nestedArrIndex, value } = stack.pop();\n\n if (!isDefined(value)) {\n continue\n }\n\n if (isString(value) && !isBlank(value)) {\n let subRecord = {\n v: value,\n i: nestedArrIndex,\n n: this.norm.get(value)\n };\n\n subRecords.push(subRecord);\n } else if (isArray(value)) {\n value.forEach((item, k) => {\n stack.push({\n nestedArrIndex: k,\n value: item\n });\n });\n } else ;\n }\n record.$[keyIndex] = subRecords;\n } else if (isString(value) && !isBlank(value)) {\n let subRecord = {\n v: value,\n n: this.norm.get(value)\n };\n\n record.$[keyIndex] = subRecord;\n }\n });\n\n this.records.push(record);\n }\n toJSON() {\n return {\n keys: this.keys,\n records: this.records\n }\n }\n}\n\nfunction createIndex(\n keys,\n docs,\n { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}\n) {\n const myIndex = new FuseIndex({ getFn, fieldNormWeight });\n myIndex.setKeys(keys.map(createKey));\n myIndex.setSources(docs);\n myIndex.create();\n return myIndex\n}\n\nfunction parseIndex(\n data,\n { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {}\n) {\n const { keys, records } = data;\n const myIndex = new FuseIndex({ getFn, fieldNormWeight });\n myIndex.setKeys(keys);\n myIndex.setIndexRecords(records);\n return myIndex\n}\n\nfunction computeScore$1(\n pattern,\n {\n errors = 0,\n currentLocation = 0,\n expectedLocation = 0,\n distance = Config.distance,\n ignoreLocation = Config.ignoreLocation\n } = {}\n) {\n const accuracy = errors / pattern.length;\n\n if (ignoreLocation) {\n return accuracy\n }\n\n const proximity = Math.abs(expectedLocation - currentLocation);\n\n if (!distance) {\n // Dodge divide by zero error.\n return proximity ? 1.0 : accuracy\n }\n\n return accuracy + proximity / distance\n}\n\nfunction convertMaskToIndices(\n matchmask = [],\n minMatchCharLength = Config.minMatchCharLength\n) {\n let indices = [];\n let start = -1;\n let end = -1;\n let i = 0;\n\n for (let len = matchmask.length; i < len; i += 1) {\n let match = matchmask[i];\n if (match && start === -1) {\n start = i;\n } else if (!match && start !== -1) {\n end = i - 1;\n if (end - start + 1 >= minMatchCharLength) {\n indices.push([start, end]);\n }\n start = -1;\n }\n }\n\n // (i-1 - start) + 1 => i - start\n if (matchmask[i - 1] && i - start >= minMatchCharLength) {\n indices.push([start, i - 1]);\n }\n\n return indices\n}\n\n// Machine word size\nconst MAX_BITS = 32;\n\nfunction search(\n text,\n pattern,\n patternAlphabet,\n {\n location = Config.location,\n distance = Config.distance,\n threshold = Config.threshold,\n findAllMatches = Config.findAllMatches,\n minMatchCharLength = Config.minMatchCharLength,\n includeMatches = Config.includeMatches,\n ignoreLocation = Config.ignoreLocation\n } = {}\n) {\n if (pattern.length > MAX_BITS) {\n throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS))\n }\n\n const patternLen = pattern.length;\n // Set starting location at beginning text and initialize the alphabet.\n const textLen = text.length;\n // Handle the case when location > text.length\n const expectedLocation = Math.max(0, Math.min(location, textLen));\n // Highest score beyond which we give up.\n let currentThreshold = threshold;\n // Is there a nearby exact match? (speedup)\n let bestLocation = expectedLocation;\n\n // Performance: only computer matches when the minMatchCharLength > 1\n // OR if `includeMatches` is true.\n const computeMatches = minMatchCharLength > 1 || includeMatches;\n // A mask of the matches, used for building the indices\n const matchMask = computeMatches ? Array(textLen) : [];\n\n let index;\n\n // Get all exact matches, here for speed up\n while ((index = text.indexOf(pattern, bestLocation)) > -1) {\n let score = computeScore$1(pattern, {\n currentLocation: index,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n currentThreshold = Math.min(score, currentThreshold);\n bestLocation = index + patternLen;\n\n if (computeMatches) {\n let i = 0;\n while (i < patternLen) {\n matchMask[index + i] = 1;\n i += 1;\n }\n }\n }\n\n // Reset the best location\n bestLocation = -1;\n\n let lastBitArr = [];\n let finalScore = 1;\n let binMax = patternLen + textLen;\n\n const mask = 1 << (patternLen - 1);\n\n for (let i = 0; i < patternLen; i += 1) {\n // Scan for the best match; each iteration allows for one more error.\n // Run a binary search to determine how far from the match location we can stray\n // at this error level.\n let binMin = 0;\n let binMid = binMax;\n\n while (binMin < binMid) {\n const score = computeScore$1(pattern, {\n errors: i,\n currentLocation: expectedLocation + binMid,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n if (score <= currentThreshold) {\n binMin = binMid;\n } else {\n binMax = binMid;\n }\n\n binMid = Math.floor((binMax - binMin) / 2 + binMin);\n }\n\n // Use the result from this iteration as the maximum for the next.\n binMax = binMid;\n\n let start = Math.max(1, expectedLocation - binMid + 1);\n let finish = findAllMatches\n ? textLen\n : Math.min(expectedLocation + binMid, textLen) + patternLen;\n\n // Initialize the bit array\n let bitArr = Array(finish + 2);\n\n bitArr[finish + 1] = (1 << i) - 1;\n\n for (let j = finish; j >= start; j -= 1) {\n let currentLocation = j - 1;\n let charMatch = patternAlphabet[text.charAt(currentLocation)];\n\n if (computeMatches) {\n // Speed up: quick bool to int conversion (i.e, `charMatch ? 1 : 0`)\n matchMask[currentLocation] = +!!charMatch;\n }\n\n // First pass: exact match\n bitArr[j] = ((bitArr[j + 1] << 1) | 1) & charMatch;\n\n // Subsequent passes: fuzzy match\n if (i) {\n bitArr[j] |=\n ((lastBitArr[j + 1] | lastBitArr[j]) << 1) | 1 | lastBitArr[j + 1];\n }\n\n if (bitArr[j] & mask) {\n finalScore = computeScore$1(pattern, {\n errors: i,\n currentLocation,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n // This match will almost certainly be better than any existing match.\n // But check anyway.\n if (finalScore <= currentThreshold) {\n // Indeed it is\n currentThreshold = finalScore;\n bestLocation = currentLocation;\n\n // Already passed `loc`, downhill from here on in.\n if (bestLocation <= expectedLocation) {\n break\n }\n\n // When passing `bestLocation`, don't exceed our current distance from `expectedLocation`.\n start = Math.max(1, 2 * expectedLocation - bestLocation);\n }\n }\n }\n\n // No hope for a (better) match at greater error levels.\n const score = computeScore$1(pattern, {\n errors: i + 1,\n currentLocation: expectedLocation,\n expectedLocation,\n distance,\n ignoreLocation\n });\n\n if (score > currentThreshold) {\n break\n }\n\n lastBitArr = bitArr;\n }\n\n const result = {\n isMatch: bestLocation >= 0,\n // Count exact matches (those with a score of 0) to be \"almost\" exact\n score: Math.max(0.001, finalScore)\n };\n\n if (computeMatches) {\n const indices = convertMaskToIndices(matchMask, minMatchCharLength);\n if (!indices.length) {\n result.isMatch = false;\n } else if (includeMatches) {\n result.indices = indices;\n }\n }\n\n return result\n}\n\nfunction createPatternAlphabet(pattern) {\n let mask = {};\n\n for (let i = 0, len = pattern.length; i < len; i += 1) {\n const char = pattern.charAt(i);\n mask[char] = (mask[char] || 0) | (1 << (len - i - 1));\n }\n\n return mask\n}\n\nconst stripDiacritics = String.prototype.normalize\n ? ((str) => str.normalize('NFD').replace(/[\\u0300-\\u036F\\u0483-\\u0489\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u07FD\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u08D3-\\u08E1\\u08E3-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u09FE\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0AFA-\\u0AFF\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B62\\u0B63\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C00-\\u0C04\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C81-\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0D00-\\u0D03\\u0D3B\\u0D3C\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D82\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F\\u109A-\\u109D\\u135D-\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u180B-\\u180D\\u1885\\u1886\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F\\u1AB0-\\u1ABE\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF2-\\u1CF4\\u1CF7-\\u1CF9\\u1DC0-\\u1DF9\\u1DFB-\\u1DFF\\u20D0-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F-\\uA672\\uA674-\\uA67D\\uA69E\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA880\\uA881\\uA8B4-\\uA8C5\\uA8E0-\\uA8F1\\uA8FF\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uA9E5\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA7B-\\uAA7D\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE2F]/g, ''))\n : ((str) => str);\n\nclass BitapSearch {\n constructor(\n pattern,\n {\n location = Config.location,\n threshold = Config.threshold,\n distance = Config.distance,\n includeMatches = Config.includeMatches,\n findAllMatches = Config.findAllMatches,\n minMatchCharLength = Config.minMatchCharLength,\n isCaseSensitive = Config.isCaseSensitive,\n ignoreDiacritics = Config.ignoreDiacritics,\n ignoreLocation = Config.ignoreLocation\n } = {}\n ) {\n this.options = {\n location,\n threshold,\n distance,\n includeMatches,\n findAllMatches,\n minMatchCharLength,\n isCaseSensitive,\n ignoreDiacritics,\n ignoreLocation\n };\n\n pattern = isCaseSensitive ? pattern : pattern.toLowerCase();\n pattern = ignoreDiacritics ? stripDiacritics(pattern) : pattern;\n this.pattern = pattern;\n\n this.chunks = [];\n\n if (!this.pattern.length) {\n return\n }\n\n const addChunk = (pattern, startIndex) => {\n this.chunks.push({\n pattern,\n alphabet: createPatternAlphabet(pattern),\n startIndex\n });\n };\n\n const len = this.pattern.length;\n\n if (len > MAX_BITS) {\n let i = 0;\n const remainder = len % MAX_BITS;\n const end = len - remainder;\n\n while (i < end) {\n addChunk(this.pattern.substr(i, MAX_BITS), i);\n i += MAX_BITS;\n }\n\n if (remainder) {\n const startIndex = len - MAX_BITS;\n addChunk(this.pattern.substr(startIndex), startIndex);\n }\n } else {\n addChunk(this.pattern, 0);\n }\n }\n\n searchIn(text) {\n const { isCaseSensitive, ignoreDiacritics, includeMatches } = this.options;\n\n text = isCaseSensitive ? text : text.toLowerCase();\n text = ignoreDiacritics ? stripDiacritics(text) : text;\n\n // Exact match\n if (this.pattern === text) {\n let result = {\n isMatch: true,\n score: 0\n };\n\n if (includeMatches) {\n result.indices = [[0, text.length - 1]];\n }\n\n return result\n }\n\n // Otherwise, use Bitap algorithm\n const {\n location,\n distance,\n threshold,\n findAllMatches,\n minMatchCharLength,\n ignoreLocation\n } = this.options;\n\n let allIndices = [];\n let totalScore = 0;\n let hasMatches = false;\n\n this.chunks.forEach(({ pattern, alphabet, startIndex }) => {\n const { isMatch, score, indices } = search(text, pattern, alphabet, {\n location: location + startIndex,\n distance,\n threshold,\n findAllMatches,\n minMatchCharLength,\n includeMatches,\n ignoreLocation\n });\n\n if (isMatch) {\n hasMatches = true;\n }\n\n totalScore += score;\n\n if (isMatch && indices) {\n allIndices = [...allIndices, ...indices];\n }\n });\n\n let result = {\n isMatch: hasMatches,\n score: hasMatches ? totalScore / this.chunks.length : 1\n };\n\n if (hasMatches && includeMatches) {\n result.indices = allIndices;\n }\n\n return result\n }\n}\n\nclass BaseMatch {\n constructor(pattern) {\n this.pattern = pattern;\n }\n static isMultiMatch(pattern) {\n return getMatch(pattern, this.multiRegex)\n }\n static isSingleMatch(pattern) {\n return getMatch(pattern, this.singleRegex)\n }\n search(/*text*/) {}\n}\n\nfunction getMatch(pattern, exp) {\n const matches = pattern.match(exp);\n return matches ? matches[1] : null\n}\n\n// Token: 'file\n\nclass ExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'exact'\n }\n static get multiRegex() {\n return /^=\"(.*)\"$/\n }\n static get singleRegex() {\n return /^=(.*)$/\n }\n search(text) {\n const isMatch = text === this.pattern;\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, this.pattern.length - 1]\n }\n }\n}\n\n// Token: !fire\n\nclass InverseExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'inverse-exact'\n }\n static get multiRegex() {\n return /^!\"(.*)\"$/\n }\n static get singleRegex() {\n return /^!(.*)$/\n }\n search(text) {\n const index = text.indexOf(this.pattern);\n const isMatch = index === -1;\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, text.length - 1]\n }\n }\n}\n\n// Token: ^file\n\nclass PrefixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'prefix-exact'\n }\n static get multiRegex() {\n return /^\\^\"(.*)\"$/\n }\n static get singleRegex() {\n return /^\\^(.*)$/\n }\n search(text) {\n const isMatch = text.startsWith(this.pattern);\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, this.pattern.length - 1]\n }\n }\n}\n\n// Token: !^fire\n\nclass InversePrefixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'inverse-prefix-exact'\n }\n static get multiRegex() {\n return /^!\\^\"(.*)\"$/\n }\n static get singleRegex() {\n return /^!\\^(.*)$/\n }\n search(text) {\n const isMatch = !text.startsWith(this.pattern);\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, text.length - 1]\n }\n }\n}\n\n// Token: .file$\n\nclass SuffixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'suffix-exact'\n }\n static get multiRegex() {\n return /^\"(.*)\"\\$$/\n }\n static get singleRegex() {\n return /^(.*)\\$$/\n }\n search(text) {\n const isMatch = text.endsWith(this.pattern);\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [text.length - this.pattern.length, text.length - 1]\n }\n }\n}\n\n// Token: !.file$\n\nclass InverseSuffixExactMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'inverse-suffix-exact'\n }\n static get multiRegex() {\n return /^!\"(.*)\"\\$$/\n }\n static get singleRegex() {\n return /^!(.*)\\$$/\n }\n search(text) {\n const isMatch = !text.endsWith(this.pattern);\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices: [0, text.length - 1]\n }\n }\n}\n\nclass FuzzyMatch extends BaseMatch {\n constructor(\n pattern,\n {\n location = Config.location,\n threshold = Config.threshold,\n distance = Config.distance,\n includeMatches = Config.includeMatches,\n findAllMatches = Config.findAllMatches,\n minMatchCharLength = Config.minMatchCharLength,\n isCaseSensitive = Config.isCaseSensitive,\n ignoreDiacritics = Config.ignoreDiacritics,\n ignoreLocation = Config.ignoreLocation\n } = {}\n ) {\n super(pattern);\n this._bitapSearch = new BitapSearch(pattern, {\n location,\n threshold,\n distance,\n includeMatches,\n findAllMatches,\n minMatchCharLength,\n isCaseSensitive,\n ignoreDiacritics,\n ignoreLocation\n });\n }\n static get type() {\n return 'fuzzy'\n }\n static get multiRegex() {\n return /^\"(.*)\"$/\n }\n static get singleRegex() {\n return /^(.*)$/\n }\n search(text) {\n return this._bitapSearch.searchIn(text)\n }\n}\n\n// Token: 'file\n\nclass IncludeMatch extends BaseMatch {\n constructor(pattern) {\n super(pattern);\n }\n static get type() {\n return 'include'\n }\n static get multiRegex() {\n return /^'\"(.*)\"$/\n }\n static get singleRegex() {\n return /^'(.*)$/\n }\n search(text) {\n let location = 0;\n let index;\n\n const indices = [];\n const patternLen = this.pattern.length;\n\n // Get all exact matches\n while ((index = text.indexOf(this.pattern, location)) > -1) {\n location = index + patternLen;\n indices.push([index, location - 1]);\n }\n\n const isMatch = !!indices.length;\n\n return {\n isMatch,\n score: isMatch ? 0 : 1,\n indices\n }\n }\n}\n\n// ❗Order is important. DO NOT CHANGE.\nconst searchers = [\n ExactMatch,\n IncludeMatch,\n PrefixExactMatch,\n InversePrefixExactMatch,\n InverseSuffixExactMatch,\n SuffixExactMatch,\n InverseExactMatch,\n FuzzyMatch\n];\n\nconst searchersLen = searchers.length;\n\n// Regex to split by spaces, but keep anything in quotes together\nconst SPACE_RE = / +(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)/;\nconst OR_TOKEN = '|';\n\n// Return a 2D array representation of the query, for simpler parsing.\n// Example:\n// \"^core go$ | rb$ | py$ xy$\" => [[\"^core\", \"go$\"], [\"rb$\"], [\"py$\", \"xy$\"]]\nfunction parseQuery(pattern, options = {}) {\n return pattern.split(OR_TOKEN).map((item) => {\n let query = item\n .trim()\n .split(SPACE_RE)\n .filter((item) => item && !!item.trim());\n\n let results = [];\n for (let i = 0, len = query.length; i < len; i += 1) {\n const queryItem = query[i];\n\n // 1. Handle multiple query match (i.e, once that are quoted, like `\"hello world\"`)\n let found = false;\n let idx = -1;\n while (!found && ++idx < searchersLen) {\n const searcher = searchers[idx];\n let token = searcher.isMultiMatch(queryItem);\n if (token) {\n results.push(new searcher(token, options));\n found = true;\n }\n }\n\n if (found) {\n continue\n }\n\n // 2. Handle single query matches (i.e, once that are *not* quoted)\n idx = -1;\n while (++idx < searchersLen) {\n const searcher = searchers[idx];\n let token = searcher.isSingleMatch(queryItem);\n if (token) {\n results.push(new searcher(token, options));\n break\n }\n }\n }\n\n return results\n })\n}\n\n// These extended matchers can return an array of matches, as opposed\n// to a singl match\nconst MultiMatchSet = new Set([FuzzyMatch.type, IncludeMatch.type]);\n\n/**\n * Command-like searching\n * ======================\n *\n * Given multiple search terms delimited by spaces.e.g. `^jscript .python$ ruby !java`,\n * search in a given text.\n *\n * Search syntax:\n *\n * | Token | Match type | Description |\n * | ----------- | -------------------------- | -------------------------------------- |\n * | `jscript` | fuzzy-match | Items that fuzzy match `jscript` |\n * | `=scheme` | exact-match | Items that are `scheme` |\n * | `'python` | include-match | Items that include `python` |\n * | `!ruby` | inverse-exact-match | Items that do not include `ruby` |\n * | `^java` | prefix-exact-match | Items that start with `java` |\n * | `!^earlang` | inverse-prefix-exact-match | Items that do not start with `earlang` |\n * | `.js$` | suffix-exact-match | Items that end with `.js` |\n * | `!.go$` | inverse-suffix-exact-match | Items that do not end with `.go` |\n *\n * A single pipe character acts as an OR operator. For example, the following\n * query matches entries that start with `core` and end with either`go`, `rb`,\n * or`py`.\n *\n * ```\n * ^core go$ | rb$ | py$\n * ```\n */\nclass ExtendedSearch {\n constructor(\n pattern,\n {\n isCaseSensitive = Config.isCaseSensitive,\n ignoreDiacritics = Config.ignoreDiacritics,\n includeMatches = Config.includeMatches,\n minMatchCharLength = Config.minMatchCharLength,\n ignoreLocation = Config.ignoreLocation,\n findAllMatches = Config.findAllMatches,\n location = Config.location,\n threshold = Config.threshold,\n distance = Config.distance\n } = {}\n ) {\n this.query = null;\n this.options = {\n isCaseSensitive,\n ignoreDiacritics,\n includeMatches,\n minMatchCharLength,\n findAllMatches,\n ignoreLocation,\n location,\n threshold,\n distance\n };\n\n pattern = isCaseSensitive ? pattern : pattern.toLowerCase();\n pattern = ignoreDiacritics ? stripDiacritics(pattern) : pattern;\n this.pattern = pattern;\n this.query = parseQuery(this.pattern, this.options);\n }\n\n static condition(_, options) {\n return options.useExtendedSearch\n }\n\n searchIn(text) {\n const query = this.query;\n\n if (!query) {\n return {\n isMatch: false,\n score: 1\n }\n }\n\n const { includeMatches, isCaseSensitive, ignoreDiacritics } = this.options;\n\n text = isCaseSensitive ? text : text.toLowerCase();\n text = ignoreDiacritics ? stripDiacritics(text) : text;\n\n let numMatches = 0;\n let allIndices = [];\n let totalScore = 0;\n\n // ORs\n for (let i = 0, qLen = query.length; i < qLen; i += 1) {\n const searchers = query[i];\n\n // Reset indices\n allIndices.length = 0;\n numMatches = 0;\n\n // ANDs\n for (let j = 0, pLen = searchers.length; j < pLen; j += 1) {\n const searcher = searchers[j];\n const { isMatch, indices, score } = searcher.search(text);\n\n if (isMatch) {\n numMatches += 1;\n totalScore += score;\n if (includeMatches) {\n const type = searcher.constructor.type;\n if (MultiMatchSet.has(type)) {\n allIndices = [...allIndices, ...indices];\n } else {\n allIndices.push(indices);\n }\n }\n } else {\n totalScore = 0;\n numMatches = 0;\n allIndices.length = 0;\n break\n }\n }\n\n // OR condition, so if TRUE, return\n if (numMatches) {\n let result = {\n isMatch: true,\n score: totalScore / numMatches\n };\n\n if (includeMatches) {\n result.indices = allIndices;\n }\n\n return result\n }\n }\n\n // Nothing was matched\n return {\n isMatch: false,\n score: 1\n }\n }\n}\n\nconst registeredSearchers = [];\n\nfunction register(...args) {\n registeredSearchers.push(...args);\n}\n\nfunction createSearcher(pattern, options) {\n for (let i = 0, len = registeredSearchers.length; i < len; i += 1) {\n let searcherClass = registeredSearchers[i];\n if (searcherClass.condition(pattern, options)) {\n return new searcherClass(pattern, options)\n }\n }\n\n return new BitapSearch(pattern, options)\n}\n\nconst LogicalOperator = {\n AND: '$and',\n OR: '$or'\n};\n\nconst KeyType = {\n PATH: '$path',\n PATTERN: '$val'\n};\n\nconst isExpression = (query) =>\n !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]);\n\nconst isPath = (query) => !!query[KeyType.PATH];\n\nconst isLeaf = (query) =>\n !isArray(query) && isObject(query) && !isExpression(query);\n\nconst convertToExplicit = (query) => ({\n [LogicalOperator.AND]: Object.keys(query).map((key) => ({\n [key]: query[key]\n }))\n});\n\n// When `auto` is `true`, the parse function will infer and initialize and add\n// the appropriate `Searcher` instance\nfunction parse(query, options, { auto = true } = {}) {\n const next = (query) => {\n let keys = Object.keys(query);\n\n const isQueryPath = isPath(query);\n\n if (!isQueryPath && keys.length > 1 && !isExpression(query)) {\n return next(convertToExplicit(query))\n }\n\n if (isLeaf(query)) {\n const key = isQueryPath ? query[KeyType.PATH] : keys[0];\n\n const pattern = isQueryPath ? query[KeyType.PATTERN] : query[key];\n\n if (!isString(pattern)) {\n throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key))\n }\n\n const obj = {\n keyId: createKeyId(key),\n pattern\n };\n\n if (auto) {\n obj.searcher = createSearcher(pattern, options);\n }\n\n return obj\n }\n\n let node = {\n children: [],\n operator: keys[0]\n };\n\n keys.forEach((key) => {\n const value = query[key];\n\n if (isArray(value)) {\n value.forEach((item) => {\n node.children.push(next(item));\n });\n }\n });\n\n return node\n };\n\n if (!isExpression(query)) {\n query = convertToExplicit(query);\n }\n\n return next(query)\n}\n\n// Practical scoring function\nfunction computeScore(\n results,\n { ignoreFieldNorm = Config.ignoreFieldNorm }\n) {\n results.forEach((result) => {\n let totalScore = 1;\n\n result.matches.forEach(({ key, norm, score }) => {\n const weight = key ? key.weight : null;\n\n totalScore *= Math.pow(\n score === 0 && weight ? Number.EPSILON : score,\n (weight || 1) * (ignoreFieldNorm ? 1 : norm)\n );\n });\n\n result.score = totalScore;\n });\n}\n\nfunction transformMatches(result, data) {\n const matches = result.matches;\n data.matches = [];\n\n if (!isDefined(matches)) {\n return\n }\n\n matches.forEach((match) => {\n if (!isDefined(match.indices) || !match.indices.length) {\n return\n }\n\n const { indices, value } = match;\n\n let obj = {\n indices,\n value\n };\n\n if (match.key) {\n obj.key = match.key.src;\n }\n\n if (match.idx > -1) {\n obj.refIndex = match.idx;\n }\n\n data.matches.push(obj);\n });\n}\n\nfunction transformScore(result, data) {\n data.score = result.score;\n}\n\nfunction format(\n results,\n docs,\n {\n includeMatches = Config.includeMatches,\n includeScore = Config.includeScore\n } = {}\n) {\n const transformers = [];\n\n if (includeMatches) transformers.push(transformMatches);\n if (includeScore) transformers.push(transformScore);\n\n return results.map((result) => {\n const { idx } = result;\n\n const data = {\n item: docs[idx],\n refIndex: idx\n };\n\n if (transformers.length) {\n transformers.forEach((transformer) => {\n transformer(result, data);\n });\n }\n\n return data\n })\n}\n\nclass Fuse {\n constructor(docs, options = {}, index) {\n this.options = { ...Config, ...options };\n\n if (\n this.options.useExtendedSearch &&\n !true\n ) {\n throw new Error(EXTENDED_SEARCH_UNAVAILABLE)\n }\n\n this._keyStore = new KeyStore(this.options.keys);\n\n this.setCollection(docs, index);\n }\n\n setCollection(docs, index) {\n this._docs = docs;\n\n if (index && !(index instanceof FuseIndex)) {\n throw new Error(INCORRECT_INDEX_TYPE)\n }\n\n this._myIndex =\n index ||\n createIndex(this.options.keys, this._docs, {\n getFn: this.options.getFn,\n fieldNormWeight: this.options.fieldNormWeight\n });\n }\n\n add(doc) {\n if (!isDefined(doc)) {\n return\n }\n\n this._docs.push(doc);\n this._myIndex.add(doc);\n }\n\n remove(predicate = (/* doc, idx */) => false) {\n const results = [];\n\n for (let i = 0, len = this._docs.length; i < len; i += 1) {\n const doc = this._docs[i];\n if (predicate(doc, i)) {\n this.removeAt(i);\n i -= 1;\n len -= 1;\n\n results.push(doc);\n }\n }\n\n return results\n }\n\n removeAt(idx) {\n this._docs.splice(idx, 1);\n this._myIndex.removeAt(idx);\n }\n\n getIndex() {\n return this._myIndex\n }\n\n search(query, { limit = -1 } = {}) {\n const {\n includeMatches,\n includeScore,\n shouldSort,\n sortFn,\n ignoreFieldNorm\n } = this.options;\n\n let results = isString(query)\n ? isString(this._docs[0])\n ? this._searchStringList(query)\n : this._searchObjectList(query)\n : this._searchLogical(query);\n\n computeScore(results, { ignoreFieldNorm });\n\n if (shouldSort) {\n results.sort(sortFn);\n }\n\n if (isNumber(limit) && limit > -1) {\n results = results.slice(0, limit);\n }\n\n return format(results, this._docs, {\n includeMatches,\n includeScore\n })\n }\n\n _searchStringList(query) {\n const searcher = createSearcher(query, this.options);\n const { records } = this._myIndex;\n const results = [];\n\n // Iterate over every string in the index\n records.forEach(({ v: text, i: idx, n: norm }) => {\n if (!isDefined(text)) {\n return\n }\n\n const { isMatch, score, indices } = searcher.searchIn(text);\n\n if (isMatch) {\n results.push({\n item: text,\n idx,\n matches: [{ score, value: text, norm, indices }]\n });\n }\n });\n\n return results\n }\n\n _searchLogical(query) {\n\n const expression = parse(query, this.options);\n\n const evaluate = (node, item, idx) => {\n if (!node.children) {\n const { keyId, searcher } = node;\n\n const matches = this._findMatches({\n key: this._keyStore.get(keyId),\n value: this._myIndex.getValueForItemAtKeyId(item, keyId),\n searcher\n });\n\n if (matches && matches.length) {\n return [\n {\n idx,\n item,\n matches\n }\n ]\n }\n\n return []\n }\n\n const res = [];\n for (let i = 0, len = node.children.length; i < len; i += 1) {\n const child = node.children[i];\n const result = evaluate(child, item, idx);\n if (result.length) {\n res.push(...result);\n } else if (node.operator === LogicalOperator.AND) {\n return []\n }\n }\n return res\n };\n\n const records = this._myIndex.records;\n const resultMap = {};\n const results = [];\n\n records.forEach(({ $: item, i: idx }) => {\n if (isDefined(item)) {\n let expResults = evaluate(expression, item, idx);\n\n if (expResults.length) {\n // Dedupe when adding\n if (!resultMap[idx]) {\n resultMap[idx] = { idx, item, matches: [] };\n results.push(resultMap[idx]);\n }\n expResults.forEach(({ matches }) => {\n resultMap[idx].matches.push(...matches);\n });\n }\n }\n });\n\n return results\n }\n\n _searchObjectList(query) {\n const searcher = createSearcher(query, this.options);\n const { keys, records } = this._myIndex;\n const results = [];\n\n // List is Array<Object>\n records.forEach(({ $: item, i: idx }) => {\n if (!isDefined(item)) {\n return\n }\n\n let matches = [];\n\n // Iterate over every key (i.e, path), and fetch the value at that key\n keys.forEach((key, keyIndex) => {\n matches.push(\n ...this._findMatches({\n key,\n value: item[keyIndex],\n searcher\n })\n );\n });\n\n if (matches.length) {\n results.push({\n idx,\n item,\n matches\n });\n }\n });\n\n return results\n }\n _findMatches({ key, value, searcher }) {\n if (!isDefined(value)) {\n return []\n }\n\n let matches = [];\n\n if (isArray(value)) {\n value.forEach(({ v: text, i: idx, n: norm }) => {\n if (!isDefined(text)) {\n return\n }\n\n const { isMatch, score, indices } = searcher.searchIn(text);\n\n if (isMatch) {\n matches.push({\n score,\n key,\n value: text,\n idx,\n norm,\n indices\n });\n }\n });\n } else {\n const { v: text, n: norm } = value;\n\n const { isMatch, score, indices } = searcher.searchIn(text);\n\n if (isMatch) {\n matches.push({ score, key, value: text, norm, indices });\n }\n }\n\n return matches\n }\n}\n\nFuse.version = '7.1.0';\nFuse.createIndex = createIndex;\nFuse.parseIndex = parseIndex;\nFuse.config = Config;\n\n{\n Fuse.parseQuery = parse;\n}\n\n{\n register(ExtendedSearch);\n}\n\nexport { Fuse as default };\n","// Switching languages might inject invisible characters like Zero Width Non-Joiners (\\u200C) or directionality marks (\\u200E, \\u200F)\nexport const sanitizeInput = (str: string) =>\n str\n .replace(/[\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u2069]/g, \"\")\n .replace(/[\\-–—_./()]+/g, '') // remove separators only // remove hyphens, spaces, symbols\n .normalize(\"NFC\")\n .trim()","import Fuse, { FuseResult } from \"fuse.js\"\nimport { AmenityFeature, ImdfFeature, OccupantFeature, SearchClient } from \"../types\"\nimport { sanitizeInput } from \"./utils/sanitizeInput\"\n\nexport const getSearchClient = ({ occupants, amenities }: { occupants: OccupantFeature[], amenities: AmenityFeature[] }): SearchClient => {\n \n //** Create fuse instances once on init */\n const fuseAmenities = new Fuse(amenities, {\n threshold: 0.2,\n keys: [\n { name: \"properties.name\", \"weight\": 1, getFn: (obj) => Object.values(obj.properties.name || {}) },\n { name: \"properties.category\", \"weight\": 1 },\n ]\n })\n const fuseOccupants = new Fuse(occupants, {\n threshold: 0.25, // 0.2 is too strict (can't find Mo-Mo Paradise with \"momo\" search string)\n includeScore: true,\n shouldSort: true,\n keys: [\n { name: \"properties.name\", \"weight\": 4, getFn: (obj) => Object.values(obj.properties.name || {}) },\n { name: \"properties.keywords\", \"weight\": 0.5 },\n { name: \"properties.category\", \"weight\": 0.25 },\n { name: \"properties.local_category_names\", \"weight\": 0.25 },\n { name: \"properties.description\", \"weight\": 0.25, getFn: occ => Object.values(occ.properties.description || {}) },\n { name: \"properties.unit_name\", \"weight\": 0.25 },\n { name: \"properties.kiosk_name\", \"weight\": 0.25 }\n ]\n })\n\n const search = (value: string): FuseResult<ImdfFeature>[] => {\n\n const sanitizedValue = sanitizeInput(value)\n \n // 01. Search amenities\n const matchedAmenities = fuseAmenities.search(sanitizedValue)\n\n // 02. Search Occupants\n const matchedOccupants = fuseOccupants.search(sanitizedValue)\n\n return [...matchedAmenities, ...matchedOccupants]\n }\n\n return {\n search\n }\n}","import {\n ui,\n Map,\n TileLayer,\n VectorLayer,\n LineString,\n Geometry,\n Coordinate,\n OverlayLayer,\n GroupGLLayer,\n GLTFLayer,\n} from \"maptalks-gl\"\nimport '@maptalks/transcoders.draco';\n\nimport { GeoJsonProperties, LineString as LineStringType, Feature } from \"geojson\"\nimport TWEEN from \"@tweenjs/tween.js\"\nimport _ from \"lodash\"\nimport {\n feature as turfFeature,\n lineString,\n point,\n} from \"@turf/helpers\"\nimport turfDistance from \"@turf/distance\"\nimport turfCenter from \"@turf/center\"\nimport { featureCollection } from '@turf/helpers';\n\nimport { PerspectiveCamera } from \"three\"\nimport { ThreeLayer } from \"maptalks.three\"\n\nimport {\n LAYERS,\n LAYER_OPTIONS,\n LAYER_FEATURE_TYPE_OBJ,\n HIGHLIGHT_LAYER_NAME,\n USER_LOCATION_LAYER_NAME,\n ORIGIN_MARKER_ID,\n DESTINATION_MARKER_ID,\n USER_LOCATION_ELEMENT_ID,\n LAST_USER_LOCATION_ELEMENT_ID_PREFIX,\n LOCALE_SYMBOL_KEY,\n DEFAULT_LOCALE,\n VENUE_EVENTS,\n} from \"./constants\"\n\nimport {\n styledFeatureGenerator,\n getExtrudeConfigByFeature,\n} from \"./utils/createElements\"\n\nimport { getBearingBetweenPoints } from \"./utils/math\"\n\nimport {\n NavigationPath,\n} from \"./object3d\"\nimport {\n IMapConfig,\n IndoorMapOptions,\n} from \"./types\"\n\nimport { CameraManager } from \"./camera/CameraManager\"\nimport { RendererManager } from \"./renderer\"\nimport { VenueDataClient } from \"../data\"\n\nconst INITIAL_CENTER = [100.5017051, 13.7572619] // just placeholder\nconst INITIAL_ZOOM = 18.5\nconst CLICK_TOLERANCE = 20\n\nconst defaultOptions: Partial<IndoorMapOptions> = {\n pixelRatio: 1,\n interactions: true,\n locale: DEFAULT_LOCALE,\n}\n\nconst parseMaptalksOptions = (options: IndoorMapOptions) => {\n return {\n centerCross: (options.centerCross ?? false),\n ...(options.interactions === false ? ({\n draggable: false,\n dragPan: false,\n dragRotate: false,\n dragPitch: false,\n scrollWheelZoom: false,\n touchZoom: false,\n doubleClickZoom: false\n }) : {}),\n }\n}\n\nexport class IndoorMap extends EventTarget {\n options: IndoorMapOptions\n //TODO: refac functions; let them do only 1 thing in a function\n\n /** Note: \"#\" means private variables */\n #styler = null\n #featuresInitted = false\n #elementsLoaded = false\n #elements: Record<string, any> = {}\n #features = []\n #markers = []\n #venues = []\n #venueInView: string | null = null\n #ordinals = []\n #mapTheme = {}\n #billboards = []\n #billboardObjects = []\n #spriteMarkerObjects = []\n #mapDecorations = []\n #groundObjects = []\n #navigationGeometries: Record<string, NavigationPath> = {}\n #venueObjects = []\n #glbObjects = []\n #objects = []\n #object3ds = []\n #isClicked = false\n #highlightElementIds = []\n #highlightObjectIds = []\n #highlightObjectControllers = []\n #userLocationGeometry = null\n #userLocationElement = null\n #mapConfig: IMapConfig = {}\n #locale: string = defaultOptions.locale\n #lastUserLocationGeometries = []\n #lastUserLocationElements = []\n\n #isLayersFadingOnZoom = false\n\n #touchStartTarget = null\n #touchStartPoint = null\n\n #onClickElement = (e) => {}\n #animationsToRun = []\n\n map: Map | null = null\n #dataClient: VenueDataClient\n camera: CameraManager\n rendererManager: RendererManager\n\n showVenueObject = false\n threeLayer: ThreeLayer | null = null\n\n onMapReady = () => {}\n onMapLoading = () => {}\n\n constructor(elementId, options: IndoorMapOptions) {\n super()\n const combinedOptions = _.merge({}, defaultOptions, options)\n this.options = combinedOptions\n const {\n onMapReady,\n onMapLoading,\n pixelRatio,\n locale,\n } = combinedOptions\n\n const maptalksOptions = parseMaptalksOptions(combinedOptions)\n\n this.map = new Map(elementId, {\n attribution: false,\n // Temporart set, not really default view\n // Default view is set in camera manager\n center: INITIAL_CENTER,\n zoom: INITIAL_ZOOM,\n clickTimeThreshold: 600,\n ...maptalksOptions,\n baseLayer: new TileLayer(\"base\", {\n urlTemplate:\n \"https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png\",\n subdomains: [\"a\", \"b\", \"c\", \"d\"],\n opacity: 1.0,\n attribution: \"\",\n hitDetect: false,\n decodeImageInWorker: true,\n errorUrl: \"/assets/img/tile-placeholder.png\",\n }),\n layers: [],\n })\n\n const groupLayer = new GroupGLLayer('group', [], {}).addTo(this.map);\n\n const threeLayer = new ThreeLayer(\"three\", {\n forceRenderOnMoving: true,\n forceRenderOnRotating: true,\n })\n groupLayer.addLayer(threeLayer)\n\n const gltfLayer = new GLTFLayer('gltf');\n groupLayer.addLayer(gltfLayer);\n\n /** Manage create elements from imdf features */\n this.rendererManager = new RendererManager(this.map, options.dataClient, options.renderer)\n\n /** Manage zoom, bearing, pitch, flyTo, moveCamera to position */\n this.camera = new CameraManager(this.map, options.camera)\n \n this.locale = locale\n this.pixelRatio = pixelRatio\n\n this.onMapReady = onMapReady\n this.onMapLoading = onMapLoading\n this.showVenueObject = false\n\n // Bind events\n // @ts-expect-error\n this.map.on(\"click\", this.handleMapClick)\n\n this.dataClient = options.dataClient\n }\n\n setOptions(options) {\n const combinedOptions = _.merge({}, defaultOptions, options)\n this.options = combinedOptions\n\n const maptalksOptions = parseMaptalksOptions(combinedOptions)\n this.map.setOptions(maptalksOptions)\n }\n\n set dataClient(value) {\n this.#dataClient = value\n \n // If no defaultView is set, get center from dataClient and move map to center\n if (!this.options.camera?.defaultView?.center) {\n this.#dataClient.filterByType(\"venue\")\n .then(venues => {\n\n /** Store for later use */\n this.#venues = venues;\n\n /** Find Venue's center */\n const venueCenters = turfCenter(featureCollection(venues));\n const [x, y] = venueCenters.geometry.coordinates\n const center = new Coordinate(x, y)\n\n /** Move Map to center */\n this.camera.setView({ center, pitch: 60, zoom: 19 })\n })\n }\n }\n\n \n\n /**\n * Events\n */\n on(eventName: string, handler) {\n this.map.on(eventName, handler)\n }\n\n handleMapClick = ({ coordinate }) => {\n const { x, y } = coordinate\n console.log(\n `[Coordinates]: x: ${_.round(x, 8)} y: ${_.round(\n y,\n 8\n )}, [Bearing]: ${this.map.getBearing()}, [Pitch]: ${this.map.getPitch()}`\n )\n }\n\n handleMapTouchEnd = ({ containerPoint }) => {\n const { x, y } = containerPoint\n const { x: touchStartX, y: touchStartY } = this.#touchStartPoint\n\n const dis = Math.hypot(x - touchStartX, y - touchStartY)\n // @ts-expect-error \n this.map.off(\"touchend\", this.handleMapTouchEnd)\n\n if (dis > 0 && dis < CLICK_TOLERANCE) {\n console.log(\"Forgiving click\", this.#touchStartTarget.properties.id)\n this.handleClickElement({ target: this.#touchStartTarget })\n }\n\n this.#touchStartTarget = null\n this.#touchStartPoint = null\n }\n\n /**\n * Getters & Setters\n */\n get elementsLoaded() {\n return this.#elementsLoaded\n }\n\n get pixelRatio() {\n return this.map.getDevicePixelRatio()\n }\n\n get locale() {\n return this.#locale\n }\n\n set mapTheme(value) {\n this.#mapTheme = value\n this.#styler = styledFeatureGenerator(this.#mapTheme)\n }\n\n get venues() {\n return this.#venues || []\n }\n\n #findAndSetVenueInView = () => {\n const venueInViewWithDistance = this.findVenueInView()\n if (\n venueInViewWithDistance &&\n (!this.#venueInView ||\n venueInViewWithDistance.venueId !== this.#venueInView)\n ) {\n this.#venueInView = venueInViewWithDistance.venueId\n this.map.fire(VENUE_EVENTS.VENUE_MOVEINTOVIEW, venueInViewWithDistance)\n }\n }\n\n set detectVenueInView(value) {\n if (value) {\n // Set initial venueInView\n this.#findAndSetVenueInView()\n this.map.on(\"moveend\", this.#findAndSetVenueInView)\n } else {\n this.map.off(\"moveend\", this.#findAndSetVenueInView)\n }\n }\n\n set billboards(value) {\n this.#billboards = value\n }\n\n set mapDecorations(value) {\n this.#mapDecorations = value\n }\n\n set pixelRatio(value: number) {\n this.map.setDevicePixelRatio(value)\n }\n\n set onClickElement(func) {\n this.rendererManager.onClickElement = func\n }\n\n set locale(value: string) {\n this.#locale = value || defaultOptions.locale\n\n // Update elements affected by locale changes.\n this.updateUserLocationSymbolByLocale(this.#locale)\n }\n\n /**\n * Private internal methods\n */\n\n #clearElements() {\n LAYERS.forEach((layerKey) => {\n this.#clearAllElementOnLayerByName(layerKey)\n })\n const scene = this.threeLayer.getScene()\n if (scene) {\n scene.children = scene.children.filter(\n (children) => children instanceof PerspectiveCamera\n )\n }\n }\n\n handleClickElement = (e) => {\n if (this.#isClicked) return\n this.#isClicked = true\n const onClickElement = this.#onClickElement\n if (!_.isFunction(onClickElement)) return\n this.#onClickElement(e)\n this.#isClicked = false\n }\n\n async #legacy_createElements() {\n const {\n // 2D\n createOpening,\n createSection,\n createDecoration,\n // 3D\n create3DBillboard,\n create3DAmenityMarker,\n create3DOpeningMarker,\n } = this.#styler\n\n let elements = {}\n let object3ds = []\n\n for (const feature of this.#features) {\n try {\n const { feature_type: featureType, properties, id } = feature\n const layerName = _.get(\n LAYER_FEATURE_TYPE_OBJ,\n featureType,\n featureType\n )\n const layer = this.map.getLayer(layerName)\n let geometry\n const category = _.get(feature, \"properties.category\")\n\n const extrudeConfig = _.get(this.#mapConfig, \"extrude\")\n const textMarkerType = _.get(\n this.#mapConfig,\n \"text_marker_type\",\n \"ui-marker\"\n )\n const featureExtrudeConfig = getExtrudeConfigByFeature(\n extrudeConfig,\n feature\n )\n\n switch (featureType) {\n \n case \"amenity\": {\n if (feature.properties.is_featured) {\n const billboardObj = create3DBillboard(feature, this.threeLayer)\n billboardObj?.on(\"click\", this.handleClickElement)\n this.#billboardObjects.push(billboardObj)\n this.#spriteMarkerObjects.push(billboardObj)\n object3ds.push(billboardObj)\n break\n }\n const marker3d = create3DAmenityMarker(\n feature,\n this.threeLayer,\n extrudeConfig\n )\n marker3d?.on(\"click\", this.handleClickElement)\n this.#spriteMarkerObjects.push(marker3d)\n object3ds.push(marker3d)\n break\n }\n case \"opening\": {\n switch (category) {\n case \"emergencyexit\":\n const { geometry } = turfCenter(feature)\n const markerFeature = {\n ...feature,\n geometry,\n }\n const marker3d = create3DOpeningMarker(\n markerFeature,\n this.threeLayer,\n extrudeConfig\n )?.on(\"click\", this.handleClickElement)\n object3ds.push(marker3d)\n break\n default:\n }\n geometry = createOpening(feature)\n ?.on(\"click\", this.handleClickElement)\n .addTo(layer)\n break\n }\n case \"section\": {\n geometry = createSection(feature)?.addTo(layer)\n break\n }\n \n default:\n break\n }\n if (!id) throw new Error(`Property is missing ID, ${id}`)\n elements[id] = { geometry, properties, featureType, feature }\n } catch (err) {\n console.warn(`Cannot create ${feature.id}: ${err.message}`)\n }\n }\n\n this.#mapDecorations.forEach((decoration) => {\n const { id, geometry, properties } = decoration\n const geometryType = decoration?.geometry?.type\n try {\n switch (geometryType) {\n case \"Point\":\n const createdBillboard = create3DBillboard(\n decoration,\n this.threeLayer\n )\n this.#billboardObjects.push(createdBillboard)\n object3ds.push(createdBillboard)\n break\n default:\n const decorationLayer = this.map.getLayer(`base`)\n const createdDecoration = createDecoration(geometry, {\n id,\n ...properties,\n }).addTo(decorationLayer)\n elements[id] = {\n geometry: createdDecoration,\n properties,\n featureType: \"decoration\",\n }\n break\n }\n } catch (error) {\n console.log(\n \"error creating decoration for \",\n decoration.properties.name\n )\n }\n })\n\n // Initiate Canvas render\n this.#elements = elements\n this.#elementsLoaded = true\n this.#featuresInitted = true\n this.#object3ds = object3ds\n if (typeof this.onMapReady === \"function\") this.onMapReady()\n }\n\n #clearAllElementOnLayerByName = (layerName: string) => {\n const layer = this.map.getLayer(layerName) as VectorLayer\n if (layer) layer.clear()\n }\n\n /**\n * Change Level & animate to path / geometry / view / etc.\n * ================================== */\n changeLevelByOrdinal(ordinal: null | number | number[]): void {\n this.rendererManager.changeLevelByOrdinal(ordinal)\n }\n\n findVenueInView = (): { venueId: string; distance: number } => {\n const mapCenter = this.map.getCenter()\n const result = this.#venues.reduce<{\n venueId: string\n distance: number\n } | null>((closest, venue) => {\n const { display_point: displayPoint } = venue.properties\n const distance = turfDistance(displayPoint, [mapCenter.x, mapCenter.y])\n if (!closest || distance < closest.distance) {\n return { venueId: venue.id, distance }\n }\n return closest\n }, null)\n return result\n }\n\n getLineStringBearing = (feature) => {\n const { geometry } = feature\n const path = new LineString(geometry.coordinates)\n return getBearingBetweenPoints(\n path.getFirstCoordinate(),\n path.getLastCoordinate()\n )\n }\n\n //map animation\n addAnimations(animation: { id: string; callback: () => void }) {\n this.#animationsToRun.push(animation)\n }\n\n removeAnimationById(id: string) {\n this.#animationsToRun = this.#animationsToRun.filter(\n (animation) => animation.id !== id\n )\n }\n\n clearAnimations() {\n this.#animationsToRun = []\n }\n\n /**\n * User Location\n ****************************/\n // TODO: To consider if we should use setter `set userLocation` instead?\n\n addUserLocation(value) {\n const { createUserLocationMarker } = this.#styler\n\n this.#userLocationGeometry = value\n\n const { properties, feature_type } = value\n\n // If UserLocationGeometry not exists, create one.\n\n const markerLayer = this.map.getLayer(USER_LOCATION_LAYER_NAME)\n\n if (!this.#userLocationElement?.geometry && markerLayer) {\n const geometry = createUserLocationMarker(value)\n geometry.addTo(markerLayer)\n\n // Add marker to this.#elements\n const element = {\n geometry,\n properties,\n featureType: feature_type,\n feature: value,\n }\n this.#elements[USER_LOCATION_ELEMENT_ID] = element\n this.#userLocationElement = element\n\n this.updateUserLocationSymbolByLocale(this.locale)\n }\n }\n\n updateUserLocationSymbolByLocale(locale: string) {\n const userLocationGeometry = _.get(\n this.#elements,\n `${USER_LOCATION_ELEMENT_ID}.geometry`\n )\n\n if (!userLocationGeometry) return\n\n const currentSymbol = userLocationGeometry.getSymbol()\n\n /**\n * Localized user location marker example.\n * Supports locale-based marker files.\n *\n * Example:\n * {\n * \"markerFile\": \"logo_url\", // Default marker\n * \"locale_symbol\": { \"th\": { \"markerFile\": \"logo_url\" }, \"default\": { \"markerFile\": \"logo_url\" } }\n * }\n */\n const localeSymbolToUpdate = currentSymbol.map((symbol) => {\n const localeSymbol =\n _.get(symbol, `${LOCALE_SYMBOL_KEY}.${locale}`) ||\n _.get(symbol, `${LOCALE_SYMBOL_KEY}.default`)\n if (!_.isPlainObject(localeSymbol)) return symbol\n\n return {\n ...symbol,\n ...localeSymbol,\n }\n })\n userLocationGeometry?.updateSymbol(localeSymbolToUpdate)\n }\n\n removeUserLocation() {\n this.#userLocationGeometry = null\n if (this.#userLocationElement) {\n const { geometry } = this.#userLocationElement\n if (geometry) geometry.remove()\n\n this.#userLocationElement = null\n this.#elements[USER_LOCATION_ELEMENT_ID] = null\n }\n }\n\n showUserLocationMarker() {\n this.#userLocationElement?.geometry.show()\n }\n\n hideUserLocationMarker() {\n this.#userLocationElement?.geometry.hide()\n }\n\n addLastUserLocation(value) {\n const newLastLocationId = value?.id\n // If the last location ID is undefined or exists, no new marker will be added.\n const isExists =\n this.#lastUserLocationGeometries.findIndex(\n ({ feature }) => feature?.id === newLastLocationId\n ) >= 0\n\n if (!newLastLocationId || isExists) return\n\n const { createLastUserLocationMarker } = this.#styler\n\n this.#lastUserLocationGeometries = [\n ...this.#lastUserLocationGeometries,\n value,\n ]\n\n const { properties, feature_type, id } = value\n\n const markerLayer = this.map.getLayer(USER_LOCATION_LAYER_NAME)\n\n const geometry = createLastUserLocationMarker(value)\n if (!geometry) return\n geometry.addTo(markerLayer)\n\n // Add marker to this.#elements\n const element = {\n geometry,\n properties,\n featureType: feature_type,\n feature: value,\n }\n this.#elements[`${LAST_USER_LOCATION_ELEMENT_ID_PREFIX}${id}`] = element\n this.#lastUserLocationElements = [\n ...this.#lastUserLocationElements,\n element,\n ]\n }\n\n removeLastUserLocation() {\n this.#lastUserLocationGeometries = []\n if (\n this.#lastUserLocationElements &&\n this.#lastUserLocationElements.length > 0\n ) {\n for (const lastUserLocationElem of this.#lastUserLocationElements) {\n const { geometry, properties = {} } = lastUserLocationElem\n if (geometry) {\n geometry.remove()\n delete this.#elements[`last_user_location-${properties?.id}`]\n }\n }\n this.#lastUserLocationElements = []\n }\n }\n\n hideLastUserLocationMarker() {\n for (const lastUserLocationElem of this.#lastUserLocationElements) {\n const { geometry } = lastUserLocationElem\n if (geometry) geometry.hide()\n }\n }\n\n /**\n * END of User Location\n ****************************/\n\n showGeometryByElementId = (elementId): void => {\n const geometry: Geometry | undefined = _.get(\n this.#elements,\n `${elementId}.geometry`\n )\n if (geometry) geometry.show()\n }\n\n hideGeometryByElementId = (elementId): void => {\n const geometry: Geometry = _.get(this.#elements, `${elementId}.geometry`)\n if (geometry) geometry.hide()\n }\n\n setSpriteMarkersOpacity = (opacity: number = 1): void => {\n const spriteMarkerObjects = this.#spriteMarkerObjects\n spriteMarkerObjects?.forEach((baseObject) => {\n baseObject.getObject3d().traverse((child) => {\n if (child.isLine || child.isSprite) {\n child.material.opacity = opacity\n }\n })\n })\n }\n\n setFeatureObject3DsOpacity = (opacity: number = 1): void => {\n const objects = this.#object3ds\n objects?.forEach((baseObject) => {\n if (baseObject instanceof NavigationPath) return\n baseObject.getObject3d().traverse((child) => {\n if (child.isMesh === true) {\n child.material.opacity = opacity\n }\n })\n })\n }\n\n /*\n * Enable or disable the fading effect based on the zoom level for all layers except the Venue Model.\n * This function applies when extruded units exceed the edges of the Venue Model while zooming out.\n * It can be enabled only when the Venue Model is present.\n */\n disableLayersFadingOnZoom = (): void => {\n this.#isLayersFadingOnZoom = false\n }\n\n enableLayersFadingOnZoom = (): void => {\n this.#isLayersFadingOnZoom = this.#venueObjects.length !== 0\n }\n\n /**\n * Navigation\n ****************************/\n combineNearbyLineStrings(\n lineStrings: Feature<LineStringType, GeoJsonProperties>[],\n options: {\n properties?: GeoJsonProperties\n distance?: number\n } = { properties: {}, distance: 0.0003 }\n // 0.0003 = 30cm\n ) {\n const { properties = {}, distance = 0.0003 } = options || {}\n const combinedLineStrings = []\n const accLine = []\n if (lineStrings.length === 1) return lineStrings\n\n for (let i = 0; i < lineStrings.length; i++) {\n const line = lineStrings[i]\n const coords = line.geometry.coordinates\n const prevLine = lineStrings[i - 1]\n const firstCoord = _.first(coords)\n const isFirstLine = i === 0\n\n if (isFirstLine) {\n accLine.push(...coords)\n continue\n }\n\n const prevLastCoord = _.last(prevLine.geometry.coordinates)\n const isNearby =\n turfDistance(point(firstCoord), point(prevLastCoord)) < distance\n\n if (!isNearby) {\n const remainingLines = lineStrings.slice(i)\n const res = this.combineNearbyLineStrings(remainingLines, properties)\n combinedLineStrings.push(...res)\n break\n }\n accLine.push(...coords)\n }\n combinedLineStrings.push(lineString(accLine, properties))\n return combinedLineStrings\n }\n\n createNavigationGeometries = (stepGeometries, destinationFeature) => {\n const {\n createOriginMarker,\n createDestinationPinMarker,\n createDestinationLogoMarker,\n create3DStepPath,\n } = this.#styler\n const routeMarkerLayer = this.map.getLayer(HIGHLIGHT_LAYER_NAME)\n\n const linesByOrdinal = _(stepGeometries)\n .filter(({ geometry }) => geometry.type === \"LineString\")\n .groupBy(\"properties.ordinal\")\n .value()\n\n const joinedLines = _(linesByOrdinal).reduce((acc, lines, key) => {\n const joined = this.combineNearbyLineStrings(lines, {\n properties: { ordinal: +key },\n })\n return [...acc, ...joined]\n }, [])\n\n joinedLines.forEach((line, index) => {\n try {\n const navPath: NavigationPath = create3DStepPath(line, this.threeLayer)\n this.threeLayer.addMesh([navPath])\n this.#navigationGeometries[`line-${index}`] = navPath\n this.#object3ds.push(navPath)\n } catch (err) {\n console.log(err)\n }\n })\n\n stepGeometries.forEach((stepGeometry) => {\n const { geometry, properties, feature_type = null } = stepGeometry\n let stepElement\n try {\n switch (geometry.type) {\n // Create a destination marker and route path\n case \"Point\":\n switch (feature_type) {\n case \"origin-marker\":\n stepElement =\n createOriginMarker(stepGeometry).addTo(routeMarkerLayer)\n break\n case \"destination-marker\":\n const extrudeConfig = _.get(this.#mapConfig, \"extrude\")\n if (destinationFeature.feature_type === \"occupant\") {\n const stepId = _.get(stepGeometry, \"id\")\n // !Update step ID to occupant destination feature ID to prevent unexpected clearing of occupant element from map\n const normalizedDestinationFeature = {\n ...destinationFeature,\n id: stepId,\n }\n const logoUrl = _.get(\n normalizedDestinationFeature,\n \"properties.logo.url\"\n )\n const createOccupantDestinationMarkerFn = logoUrl\n ? createDestinationLogoMarker\n : createDestinationPinMarker\n stepElement = createOccupantDestinationMarkerFn(\n normalizedDestinationFeature,\n { extrudeConfig }\n ).addTo(routeMarkerLayer)\n break\n }\n stepElement = createDestinationPinMarker(destinationFeature, {\n extrudeConfig,\n }).addTo(routeMarkerLayer)\n break\n default:\n this.#navigationGeometries[stepGeometry.id] = stepElement\n break\n }\n break\n default:\n break\n }\n if (stepElement) {\n const { id, feature_type: featureType } = stepGeometry\n // Add tot Elements object\n this.#elements[id] = {\n geometry: stepElement,\n featureType,\n properties: { ...stepGeometry, ...properties },\n }\n //\n }\n } catch (err) {\n // console.log(err, {\n // index: index,\n // stepGeometries,\n // })\n // throw err;\n console.log(err)\n }\n })\n }\n\n createOverviewStepPathByOrdinal = (stepGeometries, viewingOrdinal) => {\n const { createLineStringFromGeometries } = this.#styler\n const initialStepGeometries = stepGeometries\n .filter(({ properties }) => properties.ordinal === viewingOrdinal)\n .map(({ geometry }) => geometry)\n return createLineStringFromGeometries(initialStepGeometries)\n }\n\n clearNavigationGeometries(): void {\n // Remove origin and destination markers from the highlight layer\n const routeMarkerLayer = this.map.getLayer(\n HIGHLIGHT_LAYER_NAME\n ) as OverlayLayer\n const originMarkerGeometry = _.get(\n this.#elements,\n `${ORIGIN_MARKER_ID}.geometry`\n )\n const destinationMarkerGeometry = _.get(\n this.#elements,\n `${DESTINATION_MARKER_ID}.geometry`\n )\n const geometriesToRemove = _.compact([\n originMarkerGeometry,\n destinationMarkerGeometry,\n ])\n\n routeMarkerLayer.removeGeometry(geometriesToRemove)\n\n this.#elements[ORIGIN_MARKER_ID] = null\n this.#elements[DESTINATION_MARKER_ID] = null\n\n // Filter out NavigationPath objects from the global this.#object3ds list\n this.#object3ds = this.#object3ds.filter(\n (obj) => !(obj instanceof NavigationPath)\n )\n\n // Remove related navigation geometry objects\n const objects = this.#navigationGeometries || {}\n _.forEach(objects, (obj) => {\n if (!obj) return\n this.#navigationGeometries[obj.properties.id] = null\n obj.remove()\n })\n }\n /**\n * END of Navigation\n ****************************/\n\n /**\n * hide/show venue 3dmodel\n **/\n\n hideVenueObjects = () => {\n this.showVenueObject = false\n }\n showVenueObjects = () => {\n this.showVenueObject = true\n }\n\n /**\n * Other functions\n */\n\n enableClick = () => this.map.config({ geometryEvents: true })\n disableClick = () => this.map.config({ geometryEvents: false })\n\n freeze = () => this.map.config({ zoomable: false, draggable: false })\n unfreeze = () => this.map.config({ zoomable: true, draggable: true })\n\n /**\n * render (frame)\n */\n \n render() {\n // TODO: Update User Location marker position\n const view = this.map.getView()\n const currBearing = view.bearing\n this.threeLayer._needsUpdate = !this.threeLayer._needsUpdate\n if (this.threeLayer._needsUpdate) {\n // @ts-ignore\n this.threeLayer.redraw()\n }\n\n if (this.threeLayer) {\n const currentView = this.camera.getView()\n const objectOpacity = _.clamp(38 - 2 * currentView.zoom, 0, 1)\n\n this.#objects.forEach((object) => {\n object.getObject3d().traverse((child) => {\n if (child.isMesh) child.material.opacity = objectOpacity\n //TODO: recheck this line if it actually works\n /** set Mesh visible = false when opacity is 0\n * and true when opacity > 0\n */\n child.visible = !!objectOpacity\n })\n object.getObject3d().visible = !!objectOpacity\n })\n\n if (this.#billboardObjects) {\n this.#billboardObjects.forEach((object) => {\n const objectScale = _.clamp(\n 20 - 1 * currentView.zoom,\n 1,\n 1.05\n )\n object.getObject3d().scale.set(objectScale, objectScale, 1)\n })\n }\n\n /*\n * The layer appears while zooming in and disappears when zooming out,\n * fully vanishing when the Venue Model is visible (opacity: 1).\n */\n if (this.#isLayersFadingOnZoom) {\n const layerOpacity = _.clamp(1 - objectOpacity, 0, 1)\n // Fading 2D layers.\n LAYERS.forEach((layerKey) => {\n const layer = this.map.getLayer(layerKey)\n if (layer) layer.setOpacity(layerOpacity)\n })\n\n // Fading 3D units, such as extruded units.\n this.setFeatureObject3DsOpacity(layerOpacity)\n\n // Fading sprite markers, such as billboards and amenity markers.\n this.setSpriteMarkersOpacity(layerOpacity)\n }\n\n this.#venueObjects.forEach((object) => {\n object.getObject3d().traverse((child) => {\n if (child.isMesh) child.material.opacity = objectOpacity\n /** set Mesh visible = false when opacity is 0\n * and true when opacity > 0\n */\n child.visible = this.showVenueObject && objectOpacity > 0.4\n })\n })\n\n // // Update bearing to each GroundLabel to determine if text should flip or not\n // this.#groundObjects.forEach((gLabel) => {\n // gLabel.bearing = currBearing\n // })\n }\n\n this.#animationsToRun.forEach(({ callback }) => callback(this))\n\n //update TWEEN.js animaton\n TWEEN.update()\n\n requestAnimationFrame(this.render.bind(this))\n }\n}\n","import {\n BBox,\n Feature,\n FeatureCollection,\n Geometry,\n GeometryCollection,\n GeometryObject,\n LineString,\n MultiLineString,\n MultiPoint,\n MultiPolygon,\n Point,\n Polygon,\n Position,\n GeoJsonProperties,\n} from \"geojson\";\n\nimport { Id } from \"./lib/geojson.js\";\nexport * from \"./lib/geojson.js\";\n\n/**\n * @module helpers\n */\n\n// TurfJS Combined Types\nexport type Coord = Feature<Point> | Point | Position;\n\n/**\n * Linear measurement units.\n *\n * ⚠️ Warning. Be aware of the implications of using radian or degree units to\n * measure distance. The distance represented by a degree of longitude *varies*\n * depending on latitude.\n *\n * See https://www.thoughtco.com/degree-of-latitude-and-longitude-distance-4070616\n * for an illustration of this behaviour.\n *\n * @typedef\n */\nexport type Units =\n | \"meters\"\n | \"metres\"\n | \"millimeters\"\n | \"millimetres\"\n | \"centimeters\"\n | \"centimetres\"\n | \"kilometers\"\n | \"kilometres\"\n | \"miles\"\n | \"nauticalmiles\"\n | \"inches\"\n | \"yards\"\n | \"feet\"\n | \"radians\"\n | \"degrees\";\n\n/**\n * Area measurement units.\n *\n * @typedef\n */\nexport type AreaUnits =\n | Exclude<Units, \"radians\" | \"degrees\">\n | \"acres\"\n | \"hectares\";\n\n/**\n * Grid types.\n *\n * @typedef\n */\nexport type Grid = \"point\" | \"square\" | \"hex\" | \"triangle\";\n\n/**\n * Shorthand corner identifiers.\n *\n * @typedef\n */\nexport type Corners = \"sw\" | \"se\" | \"nw\" | \"ne\" | \"center\" | \"centroid\";\n\n/**\n * Geometries made up of lines i.e. lines and polygons.\n *\n * @typedef\n */\nexport type Lines = LineString | MultiLineString | Polygon | MultiPolygon;\n\n/**\n * Convenience type for all possible GeoJSON.\n *\n * @typedef\n */\nexport type AllGeoJSON =\n | Feature\n | FeatureCollection\n | Geometry\n | GeometryCollection;\n\n/**\n * The Earth radius in meters. Used by Turf modules that model the Earth as a sphere. The {@link https://en.wikipedia.org/wiki/Earth_radius#Arithmetic_mean_radius mean radius} was selected because it is {@link https://rosettacode.org/wiki/Haversine_formula#:~:text=This%20value%20is%20recommended recommended } by the Haversine formula (used by turf/distance) to reduce error.\n *\n * @constant\n */\nexport const earthRadius = 6371008.8;\n\n/**\n * Unit of measurement factors based on earthRadius.\n *\n * Keys are the name of the unit, values are the number of that unit in a single radian\n *\n * @constant\n */\nexport const factors: Record<Units, number> = {\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n degrees: 360 / (2 * Math.PI),\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/**\n\n * Area of measurement factors based on 1 square meter.\n *\n * @constant\n */\nexport const areaFactors: Record<AreaUnits, number> = {\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 nauticalmiles: 2.9155334959812285e-7,\n millimeters: 1000000,\n millimetres: 1000000,\n yards: 1.195990046,\n};\n\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @function\n * @param {GeometryObject} geometry input geometry\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryObject, GeoJsonProperties>} 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<\n G extends GeometryObject = Geometry,\n P extends GeoJsonProperties = GeoJsonProperties,\n>(\n geom: G | null,\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<G, P> {\n const feat: any = { 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/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @function\n * @param {(\"Point\" | \"LineString\" | \"Polygon\" | \"MultiPoint\" | \"MultiLineString\" | \"MultiPolygon\")} 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<\n T extends\n | \"Point\"\n | \"LineString\"\n | \"Polygon\"\n | \"MultiPoint\"\n | \"MultiLineString\"\n | \"MultiPolygon\",\n>(\n type: T,\n coordinates: any[],\n _options: Record<string, never> = {}\n): Extract<Geometry, { type: T }> {\n switch (type) {\n case \"Point\":\n return point(coordinates).geometry as Extract<Geometry, { type: T }>;\n case \"LineString\":\n return lineString(coordinates).geometry as Extract<Geometry, { type: T }>;\n case \"Polygon\":\n return polygon(coordinates).geometry as Extract<Geometry, { type: T }>;\n case \"MultiPoint\":\n return multiPoint(coordinates).geometry as Extract<Geometry, { type: T }>;\n case \"MultiLineString\":\n return multiLineString(coordinates).geometry as Extract<\n Geometry,\n { type: T }\n >;\n case \"MultiPolygon\":\n return multiPolygon(coordinates).geometry as Extract<\n Geometry,\n { type: T }\n >;\n default:\n throw new Error(type + \" is invalid\");\n }\n}\n\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @function\n * @param {Position} coordinates longitude, latitude position (each in decimal degrees)\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point, GeoJsonProperties>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nexport function point<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position,\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<Point, P> {\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\n const geom: Point = {\n type: \"Point\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @function\n * @param {Position[]} coordinates an array of Points\n * @param {GeoJsonProperties} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {Id} [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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): FeatureCollection<Point, P> {\n return featureCollection(\n coordinates.map((coords) => {\n return point(coords, properties);\n }),\n options\n );\n}\n\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @function\n * @param {Position[][]} coordinates an array of LinearRings\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[][],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<Polygon, P> {\n for (const ring of coordinates) {\n if (ring.length < 4) {\n throw new Error(\n \"Each LinearRing of a Polygon must have 4 or more Positions.\"\n );\n }\n\n if (ring[ring.length - 1].length !== ring[0].length) {\n throw new Error(\"First and last Position are not equivalent.\");\n }\n\n for (let 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 const geom: Polygon = {\n type: \"Polygon\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @function\n * @param {Position[][][]} coordinates an array of Polygon coordinates\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[][][],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): FeatureCollection<Polygon, P> {\n return featureCollection(\n coordinates.map((coords) => {\n return polygon(coords, properties);\n }),\n options\n );\n}\n\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @function\n * @param {Position[]} coordinates an array of Positions\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<LineString, P> {\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be an array of two or more positions\");\n }\n const geom: LineString = {\n type: \"LineString\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @function\n * @param {Position[][]} coordinates an array of LinearRings\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {Id} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[][],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): FeatureCollection<LineString, P> {\n return featureCollection(\n coordinates.map((coords) => {\n return lineString(coords, properties);\n }),\n options\n );\n}\n\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @function\n * @param {Array<Feature<GeometryObject, GeoJsonProperties>>} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection<GeometryObject, GeoJsonProperties>} 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<\n G extends GeometryObject = Geometry,\n P extends GeoJsonProperties = GeoJsonProperties,\n>(\n features: Array<Feature<G, P>>,\n options: { bbox?: BBox; id?: Id } = {}\n): FeatureCollection<G, P> {\n const fc: any = { 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/**\n * Creates a {@link Feature}<{@link MultiLineString}> based on a\n * coordinate array. Properties can be added optionally.\n *\n * @function\n * @param {Position[][]} coordinates an array of LineStrings\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString, GeoJsonProperties>} 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<\n P extends GeoJsonProperties = GeoJsonProperties,\n>(\n coordinates: Position[][],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<MultiLineString, P> {\n const geom: MultiLineString = {\n type: \"MultiLineString\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a {@link Feature}<{@link MultiPoint}> based on a\n * coordinate array. Properties can be added optionally.\n *\n * @function\n * @param {Position[]} coordinates an array of Positions\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<MultiPoint, P> {\n const geom: MultiPoint = {\n type: \"MultiPoint\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a {@link Feature}<{@link MultiPolygon}> based on a\n * coordinate array. Properties can be added optionally.\n *\n * @function\n * @param {Position[][][]} coordinates an array of Polygons\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[][][],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<MultiPolygon, P> {\n const geom: MultiPolygon = {\n type: \"MultiPolygon\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a Feature<GeometryCollection> based on a\n * coordinate array. Properties can be added optionally.\n *\n * @function\n * @param {Array<Point | LineString | Polygon | MultiPoint | MultiLineString | MultiPolygon>} geometries an array of GeoJSON Geometries\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection, GeoJsonProperties>} 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<\n G extends\n | Point\n | LineString\n | Polygon\n | MultiPoint\n | MultiLineString\n | MultiPolygon,\n P extends GeoJsonProperties = GeoJsonProperties,\n>(\n geometries: Array<G>,\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<GeometryCollection<G>, P> {\n const geom: GeometryCollection<G> = {\n type: \"GeometryCollection\",\n geometries,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Round number to precision\n *\n * @function\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: number, precision = 0): number {\n if (precision && !(precision >= 0)) {\n throw new Error(\"precision must be a positive number\");\n }\n const 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 * @function\n * @param {number} radians in radians across the sphere\n * @param {Units} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} distance\n */\nexport function radiansToLength(\n radians: number,\n units: Units = \"kilometers\"\n): number {\n const factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\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 * @function\n * @param {number} distance in real units\n * @param {Units} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} radians\n */\nexport function lengthToRadians(\n distance: number,\n units: Units = \"kilometers\"\n): number {\n const factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\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 * @function\n * @param {number} distance in real units\n * @param {Units} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nexport function lengthToDegrees(distance: number, units?: Units): number {\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 * @function\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nexport function bearingToAzimuth(bearing: number): number {\n let angle = bearing % 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n}\n\n/**\n * Converts any azimuth angle from the north line direction (positive clockwise)\n * and returns an angle between -180 and +180 degrees (positive clockwise), 0 being the north line\n *\n * @function\n * @param {number} angle between 0 and 360 degrees\n * @returns {number} bearing between -180 and +180 degrees\n */\nexport function azimuthToBearing(angle: number): number {\n // Ignore full revolutions (multiples of 360)\n angle = angle % 360;\n\n if (angle > 180) {\n return angle - 360;\n } else if (angle < -180) {\n return angle + 360;\n }\n\n return angle;\n}\n\n/**\n * Converts an angle in radians to degrees\n *\n * @function\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nexport function radiansToDegrees(radians: number): number {\n // % (2 * Math.PI) radians in case someone passes value > 2π\n const normalisedRadians = radians % (2 * Math.PI);\n return (normalisedRadians * 180) / Math.PI;\n}\n\n/**\n * Converts an angle in degrees to radians\n *\n * @function\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nexport function degreesToRadians(degrees: number): number {\n // % 360 degrees in case someone passes value > 360\n const normalisedDegrees = degrees % 360;\n return (normalisedDegrees * Math.PI) / 180;\n}\n\n/**\n * Converts a length from one unit to another.\n *\n * @function\n * @param {number} length Length to be converted\n * @param {Units} [originalUnit=\"kilometers\"] Input length unit\n * @param {Units} [finalUnit=\"kilometers\"] Returned length unit\n * @returns {number} The converted length\n */\nexport function convertLength(\n length: number,\n originalUnit: Units = \"kilometers\",\n finalUnit: Units = \"kilometers\"\n): number {\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/**\n * Converts an area from one unit to another.\n *\n * @function\n * @param {number} area Area to be converted\n * @param {AreaUnits} [originalUnit=\"meters\"] Input area unit\n * @param {AreaUnits} [finalUnit=\"kilometers\"] Returned area unit\n * @returns {number} The converted length\n */\nexport function convertArea(\n area: number,\n originalUnit: AreaUnits = \"meters\",\n finalUnit: AreaUnits = \"kilometers\"\n): number {\n if (!(area >= 0)) {\n throw new Error(\"area must be a positive number\");\n }\n\n const startFactor = areaFactors[originalUnit];\n if (!startFactor) {\n throw new Error(\"invalid original units\");\n }\n\n const finalFactor = areaFactors[finalUnit];\n if (!finalFactor) {\n throw new Error(\"invalid final units\");\n }\n\n return (area / startFactor) * finalFactor;\n}\n\n/**\n * isNumber\n *\n * @function\n * @param {any} 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: any): boolean {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n\n/**\n * isObject\n *\n * @function\n * @param {any} input variable to validate\n * @returns {boolean} true/false, including false for Arrays and Functions\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nexport function isObject(input: any): boolean {\n return input !== null && typeof input === \"object\" && !Array.isArray(input);\n}\n\n/**\n * Validate BBox\n *\n * @private\n * @param {any} 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: any): void {\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((num) => {\n if (!isNumber(num)) {\n throw new Error(\"bbox must only contain numbers\");\n }\n });\n}\n\n/**\n * Validate Id\n *\n * @private\n * @param {any} 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: any): void {\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","import { IHighlightOptions, ISetHighlight2DElementIdsOptions } from \"./types\"\n\nconst defaultLayerOption = { enableAltitude: true }\n\nconst VENUE = \"venue\"\nconst LEVEL = \"level\"\nconst UNIT = \"unit\"\nconst FIXTURE = \"fixture\"\nconst KIOSK = \"kiosk\"\nconst OPENING = \"opening\"\nconst SECTION = \"section\"\nconst FOOTPRINT = \"footprint\"\n\nconst AMENITY = \"amenity\"\nconst OCCUPANT = \"occupant\"\n\nconst GEOLOCATION = \"geolocation\"\nconst ORIGIN_MARKER = \"origin-marker\"\nconst DESTINATION_MARKER = \"destination-marker\"\n\nconst DECORATION = \"decoration\"\n\nexport const BASE_LAYER_NAME = \"base\"\nexport const POI_MARKER_LAYER_NAME = \"poi\"\nexport const MARKER_LAYER_NAME = \"marker\"\nexport const HIGHLIGHT_LAYER_NAME = \"highlight\"\nexport const USER_LOCATION_LAYER_NAME = \"user_location\"\n\nexport const ORIGIN_MARKER_ID = \"master-origin-marker\"\nexport const DESTINATION_MARKER_ID = \"master-destination-marker\"\nexport const USER_LOCATION_ELEMENT_ID = \"user_location\"\nexport const LAST_USER_LOCATION_ELEMENT_ID_PREFIX = \"last_user_location-\"\n\nexport const LOCALE_SYMBOL_KEY = \"locale_symbol\"\nexport const DEFAULT_LOCALE = \"en\"\n\nexport const LAYERS = [\n BASE_LAYER_NAME,\n POI_MARKER_LAYER_NAME,\n HIGHLIGHT_LAYER_NAME,\n USER_LOCATION_LAYER_NAME,\n]\n\nexport const LAYER_OPTIONS = {\n [BASE_LAYER_NAME]: {\n ...defaultLayerOption,\n forceRenderOnMoving: true,\n forceRenderOnRotating: true,\n forceRenderOnZooming: true,\n },\n [POI_MARKER_LAYER_NAME]: {\n ...defaultLayerOption,\n forceRenderOnMoving: true,\n forceRenderOnRotating: true,\n forceRenderOnZooming: true,\n zIndex: 10,\n collision: true,\n collisionDelay: 1200,\n },\n [MARKER_LAYER_NAME]: { ...defaultLayerOption },\n [HIGHLIGHT_LAYER_NAME]: { ...defaultLayerOption, zIndex: 98 },\n [USER_LOCATION_LAYER_NAME]: { ...defaultLayerOption, zIndex: 99 },\n}\n\nexport const LAYER_FEATURE_TYPE_OBJ = {\n [VENUE]: BASE_LAYER_NAME,\n [LEVEL]: BASE_LAYER_NAME,\n [UNIT]: BASE_LAYER_NAME,\n [FIXTURE]: BASE_LAYER_NAME,\n [KIOSK]: BASE_LAYER_NAME,\n [OPENING]: BASE_LAYER_NAME,\n [SECTION]: BASE_LAYER_NAME,\n [FOOTPRINT]: BASE_LAYER_NAME,\n [AMENITY]: MARKER_LAYER_NAME,\n [OCCUPANT]: POI_MARKER_LAYER_NAME,\n [GEOLOCATION]: USER_LOCATION_LAYER_NAME,\n [ORIGIN_MARKER]: HIGHLIGHT_LAYER_NAME,\n [DESTINATION_MARKER]: HIGHLIGHT_LAYER_NAME,\n [DECORATION]: BASE_LAYER_NAME,\n}\n\n/** Custom Venue Platform Events. Prefix with \"venue:\" to avoid collision */\nexport const VENUE_EVENTS = {\n VENUE_MOVEINTOVIEW: \"venue:venuemoveintoview\", // When a map is moved and a venue moved into a viewport\n}\n","import _ from \"lodash\"\nimport {\n Polygon,\n MultiPolygon,\n LineString,\n Marker,\n Coordinate,\n MultiLineString,\n ui,\n} from \"maptalks\"\nimport turfCenter from \"@turf/center\"\nimport turfBuffer from \"@turf/buffer\"\n\nimport {\n TextureLoader,\n SpriteMaterial,\n MeshLambertMaterial,\n} from \"three\"\n\nimport {\n SpriteMarker,\n Billboard,\n NavigationPath,\n} from \"../object3d\"\nimport { getCenterFromGeometry, createPolygonFromLineString } from \"./geometry\"\nimport { createSVGPathFromMarkerSymbol, svgToPng } from \"./svg\"\n\nconst GeometryType = {\n Polygon,\n MultiPolygon,\n}\n\nconst ORDINAL_HEIGHT = 0 // in version 3D change ORDINAL_HEIGHT for set altitude of geometry\n\nconst VENUE_Z_INDEX = 0\n\nconst LEVEL_Z_INDEX = 2\nconst UNIT_Z_INDEX = 3\nconst FIXTURE_Z_INDEX = 4\nconst DECORATION_Z_INDEX = 4\nconst KIOSK_Z_INDEX = 5\nconst OPENING_Z_INDEX = 3\nconst SECTION_Z_INDEX = 6\nconst USER_LOCATION_Z_INDEX = 99\nconst LAST_LOCATION_Z_INDEX = USER_LOCATION_Z_INDEX - 1\n\nconst PREFIX_HIGHLIGHTED_SYMBOL_KEY = \"highlighted\"\nconst SPRITE_MARKER_FEATURE = [\n \"amenity-atm\",\n \"amenity-babychanging\",\n \"amenity-strollerrental\",\n \"amenity-boardinggate.ferry\",\n \"amenity-elevator\",\n \"amenity-escalator\",\n \"amenity-stairs\",\n \"amenity-information\",\n \"amenity-information.transit\",\n \"amenity-wheelchair\",\n \"amenity-restroom\",\n \"amenity-restroom.male\",\n \"amenity-restroom.female\",\n \"amenity-restroom.wheelchair\",\n \"amenity-restroom.family\",\n \"amenity-restroom.unisex\",\n \"amenity-taxi\",\n \"amenity-groundtransportation\",\n \"amenity-bus\",\n \"amenity-bus.muni\",\n \"amenity-shuttle\",\n \"amenity-parking\",\n \"amenity-parking.shortterm\",\n \"amenity-parking.longterm\",\n \"amenity-parking.waitingarea\",\n \"amenity-parking.compact\",\n \"amenity-parking.ev\",\n \"amenity-parking.bicycle\",\n \"amenity-parking.motorcycle\",\n \"amenity-privatelounge\",\n \"amenity-rideshare\",\n \"amenity-valet\",\n \"amenity-landmark\",\n \"amenity-rail.muni\",\n \"amenity-service\",\n \"amenity-smokingarea\",\n \"amenity-ticketing\",\n \"amenity-meetingpoint\",\n \"amenity-prayerroom\",\n \"amenity-firstaid\",\n \"amenity-ticketing.rail\",\n \"amenity-exhibit\",\n \"amenity-mothersroom\",\n \"amenity-checkin.desk\",\n \"amenity-baggagestorage\",\n \"amenity-baggagecarts\",\n \"amenity-library\",\n \"amenity-coinlocker\",\n \"amenity-powerchargingstation\",\n \"amenity-wheelchairassit\",\n \"amenity-lostandfound\",\n \"amenity-foodservice\",\n \"amenity-businesscenter\",\n \"amenity-guestservices\",\n \"amenity-emergencyshelter\",\n \"amenity-prayerroom.buddhism\",\n \"amenity-defibrillator\",\n \"amenity-drinkingfountain\",\n \"amenity-handsanitizerstation\",\n \"amenity-unspecified\",\n \"amenity-entry\",\n \"amenity-fireextinguisher\",\n \"amenity-security\",\n \"amenity-seating\",\n \"amenity-copymachine\",\n \"amenity-fieldofplay\",\n \"amenity-fieldofplay.soccer\",\n \"amenity-amphitheater\",\n \"amenity-hoteling\",\n \"occupant-currencyexchange\",\n \"occupant-donationcenter\",\n \"occupant-bank\",\n \"occupant-books\",\n \"occupant-postoffice\",\n \"opening-emergencyexit\",\n]\n\nconst SPRITE_HIGHLIGHT_MARKER_FEATURE = SPRITE_MARKER_FEATURE.map(\n (featCate) =>\n `${PREFIX_HIGHLIGHTED_SYMBOL_KEY}-${featCate.split(\"-\").join(\".\")}`\n)\n\nconst OCCUPANT_TEXT_MARKER_CLASSNAME = \"mtk-occupant-text-marker\"\n\nconst getAltitude = (properties) =>\n Math.max(0, properties.ordinal * ORDINAL_HEIGHT || 0)\n\nconst createRoomUnit = (feature, style, options) => {\n const { geometry, id, properties } = feature\n const { allowOverride, inheritFillColorToLine } = options\n const symbolStyle = { ...style }\n if (allowOverride) _.merge(symbolStyle, properties.style)\n\n if (inheritFillColorToLine) symbolStyle.lineColor = symbolStyle.polygonFill\n\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n id,\n feature_type: \"unit\",\n category: properties.category,\n altitude: getAltitude(properties),\n },\n symbol: symbolStyle,\n defaultSymbol: symbolStyle,\n })\n}\n\n\nconst createNonpublicUnit = (feature, style, options = {}) => {\n const { geometry, id, properties } = feature\n const { allowOverride, inheritFillColorToLine } = options\n const symbolStyle = { ...style }\n\n if (allowOverride) _.merge(symbolStyle, properties.style)\n if (inheritFillColorToLine) symbolStyle.lineColor = symbolStyle.polygonFill\n\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n id,\n feature_type: \"unit\",\n category: properties.category,\n altitude: getAltitude(properties),\n },\n symbol: {\n ...style,\n },\n })\n}\nconst createWalkwayUnit = (feature, style, options) => {\n const { geometry, id, properties } = feature\n const { allowOverride, inheritFillColorToLine } = options\n const symbolStyle = { ...style }\n\n if (allowOverride) _.merge(symbolStyle, properties.style)\n if (inheritFillColorToLine) symbolStyle.lineColor = symbolStyle.polygonFill\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n id,\n feature_type: \"unit\",\n category: properties.category,\n altitude: getAltitude(properties),\n },\n symbol: {\n ...symbolStyle,\n },\n })\n}\n\nconst createWaterFixture = (feature, style, options = {}) => {\n const { geometry, properties } = feature\n const { allowOverride, inheritFillColorToLine, zIndex } = options\n const symbolStyle = { ...style }\n\n if (allowOverride) _.merge(symbolStyle, properties.style)\n if (inheritFillColorToLine) symbolStyle.lineColor = symbolStyle.polygonFill\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: {\n ...style,\n },\n zIndex,\n })\n}\n\nconst createVegetationFixture = (feature, style, options = {}) => {\n const { geometry, properties } = feature\n const { allowOverride, inheritFillColorToLine, zIndex } = options\n const symbolStyle = { ...style }\n\n if (allowOverride) _.merge(symbolStyle, properties.style)\n if (inheritFillColorToLine) symbolStyle.lineColor = symbolStyle.polygonFill\n\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: {\n ...symbolStyle,\n },\n zIndex,\n })\n}\n\nconst createObstructionalFixture = (feature, style = {}, options = {}) => {\n const { geometry, properties = {} } = feature\n const { model3d } = properties\n const { allowOverride, inheritFillColorToLine, zIndex } = options\n const symbolStyle = { ...style }\n if (!_.isEmpty(model3d)) return\n if (allowOverride) _.merge(symbolStyle, properties.style)\n if (inheritFillColorToLine) symbolStyle.lineColor = symbolStyle.polygonFill\n //create polygon with line-offset if geometry is lineString\n if (geometry.type === \"LineString\") {\n const polygon = createPolygonFromLineString(geometry)\n return new GeometryType[\"Polygon\"](polygon, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: symbolStyle,\n defaultSymbol: symbolStyle,\n zIndex,\n })\n }\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: symbolStyle,\n defaultSymbol: symbolStyle,\n zIndex,\n })\n}\n\nconst createVegetationSection = (feature, symbol = {}) => {\n const { geometry, properties } = feature\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol,\n zIndex: SECTION_Z_INDEX,\n })\n}\n\nconst creatingSeatingSection = (feature, symbol = {}) => {\n const { geometry, properties } = feature\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol,\n zIndex: SECTION_Z_INDEX,\n })\n}\n\nconst creatingDefaultSection = (feature, symbol = {}) => {\n const { geometry, properties } = feature\n try {\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol,\n zIndex: SECTION_Z_INDEX,\n })\n } catch (error) {\n console.warn(`Error creatingDefaultSection`, geometry.type)\n }\n}\n\nconst createEatingDrinkingSection = (feature, symbol = {}) => {\n const { geometry, properties } = feature\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol,\n zIndex: SECTION_Z_INDEX,\n })\n}\n\nconst createPrincipalOpening = (feature, style, options = {}) => {\n const { geometry, properties } = feature\n const { allowOverride, zIndex } = options\n const symbolStyle = { ...style }\n if (allowOverride) _.merge(symbolStyle, properties.style)\n\n try {\n return new LineString(geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: symbolStyle,\n zIndex,\n })\n } catch (error) {\n console.log(`error creating pedestrian principal opening:`, feature)\n }\n}\n\nconst createEmergencyExitOpening = (feature, style, options = {}) => {\n const { geometry, properties } = feature\n const { allowOverride, zIndex } = options\n const symbolStyle = { ...style }\n if (allowOverride) _.merge(symbolStyle, properties.style)\n\n try {\n return new LineString(geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: symbolStyle,\n zIndex,\n })\n } catch (error) {\n console.log(`error creating emergency exit opening:`, feature)\n }\n}\nconst createPedestrianOpening = (feature, style, options = {}) => {\n const { geometry, properties, id } = feature\n const { allowOverride, zIndex } = options\n const symbolStyle = { ...style }\n\n if (allowOverride) _.merge(symbolStyle, properties.style)\n\n try {\n return new LineString(geometry.coordinates, {\n properties: {\n id,\n feature_type: \"opening\",\n category: properties.category,\n altitude: getAltitude(properties),\n },\n symbol: symbolStyle,\n zIndex,\n })\n } catch (error) {\n console.log(`error creating pedestrian opening:`, feature)\n }\n}\n\nconst createExtrudePolygon = (\n geometry,\n threeLayer,\n material,\n height,\n properties = {},\n options\n) => {\n const { offset = 0, altitude = 0 } = options\n const offsetGeometry = turfBuffer(geometry, offset, { units: \"meters\" })\n const object = threeLayer.toExtrudePolygon(\n offsetGeometry,\n { height, async: true, altitude },\n material\n )\n object.properties = properties\n return object\n}\n\nconst create3DMarker = (\n coordinates,\n options,\n material,\n threeLayer,\n markerProperties\n) => {\n return new SpriteMarker(\n coordinates,\n options,\n material,\n threeLayer,\n markerProperties\n )\n}\n\n/**\n * Retrieves the extrude configuration for a feature.\n *\n * @param {Object} baseExtrudeConfig - The default extrude configuration defined in the map settings within the app config content type.\n * @param {Object} feature - The target feature object for which the extrude value is required.\n * @returns {Object|undefined} - The extrude value from the feature's `properties` field, or the base extrude configuration as a fallback if not defined.\n */\nexport const getExtrudeConfigByFeature = (baseExtrudeConfig, feature = {}) => {\n const { feature_type: featureType } = feature\n // Retrieve extrude configuration from the extrude field in the feature's properties\n const featureExtrudeConfig = _.get(feature, \"properties.extrude\")\n\n // Retrieve extrude configuration from the base extrude settings. (Map Config)\n const featureCategory = _.get(feature, \"properties.category\")\n const baseFeatureExtrudeConfig = _.get(\n baseExtrudeConfig,\n `${featureType}.${featureCategory || featureType}`\n )\n\n // Fallback to base extrude configuration if the feature's extrude field is not defined.\n return featureExtrudeConfig ?? baseFeatureExtrudeConfig\n}\n\nconst getFeatureMarkerConfig = (feature, mapConfig = {}) => {\n const { textMarkerType, extrudeConfig = {}, symbol } = mapConfig\n\n const location = getLocationByFeature(feature)\n const featureExtrudeConfig = getExtrudeConfigByFeature(\n extrudeConfig,\n location\n )\n\n return {\n markerSymbol: symbol,\n textMarkerType,\n featureExtrudeConfig,\n }\n}\n\nexport const createSpriteMaterialByLabelSymbol = (labelSymbol = []) => {\n const material = new SpriteMaterial()\n try {\n const [base, icon] = labelSymbol\n const { markerWidth: baseWidth = 24 } = base\n const { markerWidth: iconWidth = 24 } = icon\n const viewBoxDimension = Math.max(baseWidth, iconWidth)\n\n const baseSVG = createSVGPathFromMarkerSymbol(base)\n const iconSVG = createSVGPathFromMarkerSymbol(icon)\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${viewBoxDimension}\" height=\"${viewBoxDimension}\">${baseSVG}${iconSVG}</svg>`\n const textureLoader = new TextureLoader()\n const scaleFactor = 200 / 24 // Scale factor to upscale from 24px to 200px to ensure the resolution is high enough\n\n svgToPng(svg, scaleFactor).then((png) => {\n const texture = textureLoader.load(png, () => {\n material.map = texture\n material.needsUpdate = true\n })\n })\n } catch (error) {\n console.warn(`Error createSpriteMaterialByLabelSymbol: `, labelSymbol)\n }\n return material\n}\n\nexport const createStyledUIMarkerElement = ({\n style,\n textContent,\n className,\n}) => {\n const element = document.createElement(\"div\")\n for (const key in style) {\n element.style[key] = style[key]\n }\n element.className = className\n element.textContent = textContent\n //! Use outerHTML to return HTML string instead of element object to avoid DOM event warnings from Maptalks.js.\n return element.outerHTML\n}\n\nexport const styledFeatureGenerator = (mapTheme) => {\n const getElementSymbol = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeTheme = _.get(mapTheme, `${featureType}.geometry.symbol`)\n if (featureType === key) return featureTypeTheme\n const categoryTheme = _.get(mapTheme, `${key}.geometry.symbol`)\n return _.merge({}, featureTypeTheme, categoryTheme)\n }\n\n const getLabelSymbol = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeTheme = _.get(mapTheme, `${featureType}.label`)\n const categoryTheme = _.get(mapTheme, `${key}.label`)\n const mergedSymbol = _.merge({}, featureTypeTheme, categoryTheme)\n let symbols = _.values(_.map(mergedSymbol, \"symbol\"))\n const markerIndexToMove = symbols.findIndex(\n ({ elementType }) => elementType === \"label.marker\"\n )\n\n // Move the label.marker symbol to the last of array\n if (markerIndexToMove >= 0) {\n const markerSymbolToMove = _.pullAt(symbols, markerIndexToMove)[0]\n symbols.push(markerSymbolToMove)\n }\n\n return symbols\n }\n\n const getUIMarkerSymbol = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeTheme = _.get(mapTheme, `${featureType}.ui.marker`)\n const categoryTheme = _.get(mapTheme, `${key}.ui.marker`)\n const mergedSymbol = _.merge({}, featureTypeTheme, categoryTheme)\n const symbol = _.get(mergedSymbol, \"symbol\")\n return symbol\n }\n const getUIMarkerOptions = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeTheme = _.get(mapTheme, `${featureType}.ui.marker`)\n const categoryTheme = _.get(mapTheme, `${key}.ui.marker`)\n const mergedSymbol = _.merge({}, featureTypeTheme, categoryTheme)\n const options = _.get(mergedSymbol, \"options\")\n return options\n }\n\n const getLabelOptions = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeSymbol = _.get(mapTheme, `${featureType}.label`)\n const categorySymbol = _.get(mapTheme, `${key}.label`)\n const mergedSymbol = _.merge({}, featureTypeSymbol, categorySymbol)\n return _.reduce(\n mergedSymbol,\n (acc, symbol) => ({ ...acc, ..._.get(symbol, \"options\", {}) }),\n {}\n )\n }\n\n const generateSpriteMarkerMaterial = () => {\n return SPRITE_MARKER_FEATURE.reduce((acc, featCate) => {\n const [featureType, category] = featCate.split(\"-\")\n const key = `${featureType}.${category}`\n const labelSymbol = getLabelSymbol(key)\n const material = createSpriteMaterialByLabelSymbol(labelSymbol)\n return { ...acc, [key]: material }\n }, {})\n }\n\n const generateSpriteHighlightMarkerOption = () => {\n return SPRITE_HIGHLIGHT_MARKER_FEATURE.reduce((acc, featCate) => {\n const categoryKey = _.last(featCate.split(\"-\")) // Example: highlighted-amenity.atm -> amenity.atm\n const defaultLabelSymbol = getLabelSymbol(categoryKey)\n const highlightLabelSymbol = getLabelSymbol(featCate)\n const [defaultBase, defaultIcon] = defaultLabelSymbol\n const [highlightBase, highlightIcon] = highlightLabelSymbol\n const base = _.merge({}, defaultBase, highlightBase)\n const icon = _.merge({}, defaultIcon, highlightIcon)\n\n const material = createSpriteMaterialByLabelSymbol([base, icon])\n const options = getLabelOptions(featCate)\n return { ...acc, [featCate]: { material, options } }\n }, {})\n }\n\n const spriteMarkerMaterialObj = generateSpriteMarkerMaterial()\n const spriteHighlightMarkerOptionObj = generateSpriteHighlightMarkerOption()\n\n const getElementOptions = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeOptions = _.get(\n mapTheme,\n `${featureType}.geometry.options`\n )\n\n const categoryOptions = _.get(mapTheme, `${key}.geometry.options`)\n\n return _.merge({}, featureTypeOptions, categoryOptions)\n }\n\n const createOccupantMarker = (feature, locatedFeature, mapConfig) => {\n const { textMarkerType, featureExtrudeConfig } = getFeatureMarkerConfig(\n feature,\n mapConfig\n )\n const markerHeight = _.get(featureExtrudeConfig, \"height\", 0)\n const { properties, id, feature_type } = feature\n if (!properties.anchor) return\n\n /**\n * Prepare geometry for occupant marker positioning:\n * - Use anchor coordinates if the location feature is the main location\n * - Otherwise, use the center of the location feature\n */\n const mainLocationId =\n _.get(properties, \"unit.id\") || _.get(properties, \"kiosk.id\")\n const isMainLocationFeature = mainLocationId === locatedFeature?.id\n const { geometry: mainLocationGeometry } = properties?.anchor\n const geometry = isMainLocationFeature\n ? mainLocationGeometry\n : turfCenter(locatedFeature)?.geometry\n\n const baseProperties = {\n id,\n feature_type,\n category: properties.category,\n altitude: getAltitude(properties),\n }\n const occupantName = _.isEmpty(properties.short_name)\n ? properties.name\n : properties.short_name\n\n if (locatedFeature) {\n const { feature_type, properties } = locatedFeature\n const { category } = properties\n const locatedLabelOption =\n feature_type === \"kiosk\"\n ? getLabelOptions(`${feature_type}`)\n : getLabelOptions(`${feature_type}.${category}`)\n const { hidden = false } = locatedLabelOption || {}\n if (hidden) return\n }\n\n const getValidatedRenderType = (requestedType, logoUrl) => {\n // If requestType is \"Logo\" or \"Logo + Name\" and no logo, fallback to \"Name\"\n if (requestedType === \"Logo\" || requestedType === \"Logo + Name\") {\n return logoUrl ? requestedType : \"Name\"\n }\n return requestedType\n }\n\n const logoUrl = _.get(properties, \"logo.url\")\n const requestedRenderType = _.get(properties, \"render_type\", \"Name\")\n const renderType = getValidatedRenderType(requestedRenderType, logoUrl)\n if (renderType === \"Label\") return null\n\n const renderPriority = properties.render_priority || 3\n const labelSymbol = getLabelSymbol(`occupant-${_.toLower(renderType)}`)\n const markerSymbol = _.last(labelSymbol)\n\n const coordinates = _.get(geometry, \"coordinates\")\n\n const priorityLabelSymbol = getLabelSymbol(\n `occupant-${_.toLower(renderType)}-${renderPriority}`\n )\n const priorityMarkerSymbol = _.last(priorityLabelSymbol) || {}\n\n switch (renderType) {\n case \"Logo\":\n _.set(priorityMarkerSymbol, \"markerFile\", logoUrl)\n\n return new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties) + markerHeight,\n ...baseProperties,\n },\n symbol: priorityLabelSymbol,\n })\n\n case \"Logo + Name\":\n return new Marker(coordinates, {\n properties: {\n name: occupantName.en,\n altitude: getAltitude(properties) + markerHeight,\n ...baseProperties,\n },\n symbol: {\n textName: \"{name}\",\n markerFile: logoUrl,\n textHaloRadius: {\n stops: [\n [20, 1],\n [21, 2],\n ],\n },\n ...markerSymbol,\n ...priorityMarkerSymbol,\n },\n })\n case \"None\":\n return new ui.UIMarker(coordinates, {\n properties: { ...baseProperties },\n content: createStyledUIMarkerElement({\n style: { display: \"none\" },\n textContent: occupantName.en,\n }),\n altitude: getAltitude(properties) + markerHeight,\n })\n case \"Name\":\n default:\n if (textMarkerType === \"marker\") {\n return new Marker(coordinates, {\n properties: {\n name: occupantName.en,\n altitude: getAltitude(properties) + markerHeight,\n ...baseProperties,\n },\n symbol: {\n textName: \"{name}\",\n //TODO:: implement symbol scaler later\n textHaloRadius: {\n stops: [\n [20, 1],\n [21, 2],\n ],\n },\n ...markerSymbol,\n ...priorityMarkerSymbol,\n },\n })\n }\n\n const uiMarkerSymbol = getUIMarkerSymbol(\n `occupant-${_.toLower(renderType)}`\n )\n const uiMarkerPrioritySymbol = getUIMarkerSymbol(\n `occupant-${_.toLower(renderType)}-${renderPriority}`\n )\n const uiMarkerPriorityOptions = getUIMarkerOptions(\n `occupant-${_.toLower(renderType)}-${renderPriority}`\n )\n\n const style = { ...uiMarkerSymbol, ...uiMarkerPrioritySymbol }\n return new ui.UIMarker(coordinates, {\n properties: { ...baseProperties },\n content: createStyledUIMarkerElement({\n style,\n textContent: occupantName.en,\n className: OCCUPANT_TEXT_MARKER_CLASSNAME,\n }),\n collision: true,\n collisionFadeIn: true,\n altitude: getAltitude(properties) + markerHeight,\n ...uiMarkerPriorityOptions,\n })\n }\n }\n\n const getFeatureProperties = (feature) => {\n const { id, feature_type, properties } = feature\n const { category, ordinal, style = {} } = properties\n const elementStyle = getElementSymbol(`${feature_type}.${category}`)\n const { allowOverride } = getElementOptions(`${feature_type}.${category}`)\n if (allowOverride) _.merge(elementStyle, style)\n const { polygonFill: color } = elementStyle\n const featureProperty = {\n id,\n feature_type,\n category: category || feature_type,\n ordinal,\n defaultColor: color,\n }\n return featureProperty\n }\n\n return {\n getElementSymbol,\n getHilighPolygonalSymbol: (type) => {\n switch (type) {\n case \"MultiPolygon\":\n case \"Polygon\": {\n return getElementSymbol(\"hilight-polygonal\")\n }\n case \"Point\": {\n return getElementSymbol(\"hilight-marker\")\n }\n default:\n break\n }\n },\n getHighlightMarkerSymbol: () => {\n return getElementSymbol(\"highlighted-marker\")\n },\n createVenue: (feature) => {\n const { geometry, feature_type } = feature\n const symbolStyle = getElementSymbol(feature_type)\n return new GeometryType[geometry.type](geometry.coordinates, {\n symbol: {\n ...symbolStyle,\n },\n zIndex: VENUE_Z_INDEX,\n })\n },\n\n createLevel: (feature) => {\n const { geometry, properties, feature_type } = feature\n const { category } = properties\n\n const style = getElementSymbol(`${feature_type}.${category}`)\n // const options = getElementOptions(`${feature_type}.${category}`)\n\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: {\n ...style,\n },\n zIndex: LEVEL_Z_INDEX,\n })\n },\n\n\n createMarker: (feature) => {\n try {\n const { geometry, properties } = feature\n const coordinates = getCenterFromGeometry(geometry)\n const markerSymbol = getElementSymbol(\"pin-marker\")\n return new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: markerSymbol,\n })\n } catch (err) {\n console.log(`error creating marker:`, feature)\n }\n },\n createOriginMarker: (feature) => {\n const { id, geometry, properties } = feature\n const coordinates = getCenterFromGeometry(geometry)\n const markerSymbol = getElementSymbol(\"origin-marker\")\n try {\n return new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n id,\n symbol: markerSymbol,\n })\n } catch (error) {\n console.log(`error creating origin marker:`, feature)\n }\n },\n createDestinationPinMarker: (feature, mapConfig) => {\n const { featureExtrudeConfig } = getFeatureMarkerConfig(\n feature,\n mapConfig\n )\n const markerHeight = _.get(featureExtrudeConfig, \"height\")\n // Get Label from located unit / kiosk\n const { id, properties } = feature\n const geometry =\n _.get(feature, \"geometry\") ||\n _.get(feature, \"properties.anchor.geometry\")\n const coordinates = getCenterFromGeometry(geometry)\n const symbol = getElementSymbol(\"pin-marker\")\n try {\n return new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties) + markerHeight,\n },\n id,\n symbol,\n })\n } catch (error) {\n console.log(`error creating destination marker:`, feature)\n }\n },\n createDestinationLogoMarker: (feature, mapConfig = {}) => {\n const { featureExtrudeConfig } = getFeatureMarkerConfig(\n feature,\n mapConfig\n )\n const markerHeight = _.get(featureExtrudeConfig, \"height\", 0)\n\n // Get Label from located unit / kiosk\n const { properties, id } = feature\n const { geometry } = properties.anchor\n const logoUrl = _.get(properties, \"logo.url\")\n const coordinates = getCenterFromGeometry(geometry)\n const [markerBase, markerLabel] = getLabelSymbol(\n \"highlighted-logo-marker\"\n )\n try {\n return new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties) + markerHeight,\n },\n id,\n symbol: [markerBase, { ...markerLabel, markerFile: logoUrl }],\n })\n } catch (error) {\n console.log(`error creating destination marker:`, feature)\n }\n },\n\n createUserLocationMarker: (feature) => {\n try {\n const { geometry, properties } = feature\n const coordinates = getCenterFromGeometry(geometry)\n const symbolStyle = getElementSymbol(\"user-location\") || {}\n const marker = new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties),\n ordinal: properties.ordinal !== null ? properties.ordinal : null,\n },\n symbol: symbolStyle.start,\n zIndex: USER_LOCATION_Z_INDEX,\n })\n\n marker.animate(\n {\n symbol: symbolStyle.end,\n },\n {\n repeat: true,\n easing: \"upAndDown\",\n duration: 1500,\n }\n )\n return marker\n } catch (err) {\n console.log(`error creating marker:`, feature)\n }\n },\n\n createLastUserLocationMarker: (feature) => {\n try {\n const { geometry, properties } = feature\n const coordinates = getCenterFromGeometry(geometry)\n const symbolStyle = getElementSymbol(\"last-user-location\") || {}\n const options = getElementOptions(\"last-user-location\") || {}\n const marker = new Marker(coordinates, {\n properties: {\n ...options,\n altitude: getAltitude(properties),\n ordinal: properties.ordinal !== null ? properties.ordinal : null,\n },\n symbol: symbolStyle,\n zIndex: LAST_LOCATION_Z_INDEX,\n })\n\n return marker\n } catch (err) {\n console.log(`error creating marker:`, feature)\n }\n },\n\n createHighlightOccupantMarker: (feature, mapConfig) => {\n const { featureExtrudeConfig, markerSymbol } = getFeatureMarkerConfig(\n feature,\n mapConfig\n )\n const markerHeight = _.get(featureExtrudeConfig, \"height\")\n const { id, feature_type, properties } = feature\n\n if (!properties.anchor) return\n\n const markerProperties = {\n ...properties,\n id,\n feature_type,\n altitude: getAltitude(properties) + markerHeight,\n }\n\n const { geometry } = properties?.anchor\n const coordinates = _.get(geometry, \"coordinates\")\n const logoUrl = _.get(properties, \"logo.url\")\n\n // If the symbol option is defined, create a marker.\n if (markerSymbol) {\n return new Marker(coordinates, {\n properties: markerProperties,\n symbol: markerSymbol,\n })\n }\n\n //use pin-marker if no logo\n if (!logoUrl) {\n const symbol = getElementSymbol(\"pin-marker\")\n return new Marker(coordinates, {\n properties: markerProperties,\n symbol,\n })\n }\n\n const labelSymbol = getLabelSymbol(\"highlight-occupant-logo\")\n const priorityMarkerSymbol = _.last(labelSymbol) || {}\n _.set(priorityMarkerSymbol, \"markerFile\", logoUrl)\n return new Marker(coordinates, {\n properties: markerProperties,\n symbol: labelSymbol,\n })\n },\n createHighlight2DAmenityMarkerFrom3DMarker: (feature, mapConfig) => {\n const { coordinates, units, kiosk } = feature\n const amenityLocatedUnit = _.first(units)\n\n const unitConfig = getExtrudeConfigByFeature(\n mapConfig,\n amenityLocatedUnit\n )\n const unitHeight = _.get(unitConfig, \"height\", 0)\n const kioskConfig = getExtrudeConfigByFeature(mapConfig, kiosk)\n const kioskHeight = _.get(kioskConfig, \"height\", 0)\n\n const markerHeight = unitHeight + kioskHeight\n\n const symbol = getElementSymbol(\"highlight-amenity-marker\")\n return new Marker(coordinates, {\n properties: {\n ...feature,\n altitude: markerHeight,\n },\n symbol,\n })\n },\n\n createSection: (feature) => {\n const { properties, feature_type } = feature\n const { category } = properties\n const elementStyle = getElementSymbol(`${feature_type}.${category}`)\n switch (category) {\n case \"eatingdrinking\":\n return createEatingDrinkingSection(feature, elementStyle)\n case \"vegetation\":\n return createVegetationSection(feature, elementStyle)\n case \"seating\":\n return creatingSeatingSection(feature, elementStyle)\n default:\n return creatingDefaultSection(feature, elementStyle)\n }\n },\n\n createOccupant: (feature, location, mapConfig) => {\n return createOccupantMarker(feature, location, mapConfig)\n },\n\n createOpening: (feature) => {\n const {\n feature_type,\n properties: { category },\n } = feature\n const elementStyle = getElementSymbol(`${feature_type}.${category}`)\n const options = {\n ...getElementOptions(`${feature_type}.${category}`),\n zIndex: OPENING_Z_INDEX,\n }\n switch (feature.properties.category) {\n case \"pedestrian\":\n return createPedestrianOpening(feature, elementStyle, options)\n case \"pedestrian.principal\":\n return createPrincipalOpening(feature, elementStyle, options)\n case \"emergencyexit\":\n return createEmergencyExitOpening(feature, elementStyle, options)\n default:\n break\n }\n },\n\n createFixture: (feature) => {\n const {\n feature_type,\n properties: { category },\n } = feature\n const elementStyle = getElementSymbol(`${feature_type}.${category}`)\n const options = {\n ...getElementOptions(`${feature_type}.${category}`),\n zIndex: FIXTURE_Z_INDEX,\n }\n switch (feature.properties.category) {\n case \"water\":\n return createWaterFixture(feature, elementStyle, options)\n case \"vegetation\":\n return createVegetationFixture(feature, elementStyle, options)\n case \"equipment\":\n case \"obstruction\":\n case \"stage\":\n case \"desk\":\n case \"wall\":\n return createObstructionalFixture(feature, elementStyle, options)\n default:\n break\n }\n },\n\n createLineStringFromGeometries: (geometries) => {\n const mergedCoordinates = _(geometries)\n .map((geometry) => {\n switch (geometry.type) {\n case \"Point\":\n return [\n geometry?.getCoordinates\n ? geometry?.getCoordinates()\n : new Coordinate(geometry.coordinates),\n ]\n case \"Polygon\":\n return [\n geometry?.getCenter\n ? geometry?.getCenter()\n : new Polygon(geometry.coordinates).getCenter(),\n ]\n case \"MultiPolygon\":\n return [\n geometry?.getCenter\n ? geometry?.getCenter()\n : new MultiPolygon(geometry.coordinates).getCenter(),\n ]\n case \"LineString\":\n default:\n return geometry?.getCoordinates\n ? geometry?.getCoordinates()\n : new LineString(geometry.coordinates).getCoordinates()\n }\n })\n .flatten()\n .value()\n const stepPathLineSymbol = getElementSymbol(\"navigation-path\")\n const startPathSymbolMarker = getElementSymbol(\"navigation-path-start\")\n\n const line = new LineString(mergedCoordinates, {\n smoothness: 0.5,\n symbol: [...stepPathLineSymbol, startPathSymbolMarker],\n })\n\n return line\n },\n create3DStepPath: (feature, threeLayer, option = {}) => {\n const stepPathLineSymbol = getElementSymbol(\"navigation-path\")\n const pathLineSymbol = stepPathLineSymbol[1]\n const pathLineEffect = stepPathLineSymbol[0]\n const lineOptions = {\n color: pathLineSymbol?.lineColor,\n opacity: pathLineSymbol?.lineOpacity,\n }\n const outlineOptions = {\n color: pathLineEffect?.lineColor,\n opacity: pathLineEffect?.lineOpacity,\n }\n\n return new NavigationPath(\n feature,\n threeLayer,\n getFeatureProperties(feature),\n option,\n lineOptions,\n outlineOptions\n )\n },\n\n createDecoration: (decoration, options) => {\n const { type, coordinates } = decoration\n const { id, ordinal, symbol } = options\n const formattedProperties = {\n properties: {\n id,\n altitude: getAltitude(options),\n ordinal,\n },\n symbol,\n zIndex: DECORATION_Z_INDEX,\n }\n switch (type) {\n case \"Polygon\":\n return new Polygon(coordinates, formattedProperties)\n case \"MultiPolygon\":\n return new MultiPolygon(coordinates, formattedProperties)\n case \"LineString\":\n return new LineString(coordinates, formattedProperties)\n case \"MultiLineString\":\n return new MultiLineString(coordinates, formattedProperties)\n default:\n return null\n }\n },\n \n create3DBillboard: (billboard, threeLayer) => {\n const { id, feature_type, properties } = billboard\n const {\n logo,\n altitude,\n scale,\n alphaTest,\n legColor,\n showLeg,\n is_clickable,\n } = properties\n const coordinates = getCenterFromGeometry(billboard.geometry)\n const billboardProperties = {\n ...billboard.properties,\n id,\n feature_type,\n }\n\n const options = {\n altitude,\n scale,\n alphaTest,\n legColor,\n showLeg,\n interactive: is_clickable,\n }\n\n return new Billboard(\n coordinates,\n options,\n logo?.url,\n threeLayer,\n billboardProperties\n )\n },\n create3DAmenityMarker: (feature, threeLayer, config) => {\n const { geometry, properties, feature_type, id } = feature\n const { category, units, kiosk, is_clickable } = properties\n const amenityLocatedUnit = _.first(units)\n const isLocatedUnitModel3dAvailable = !_.isEmpty(\n amenityLocatedUnit?.properties?.model3d\n )\n const isLocatedKioskModel3dAvailable = !_.isEmpty(\n kiosk?.properties?.model3d\n )\n\n const unitConfig = getExtrudeConfigByFeature(config, amenityLocatedUnit)\n const unitHeight = isLocatedUnitModel3dAvailable\n ? 0\n : _.get(unitConfig, \"height\", 0)\n const kioskConfig = getExtrudeConfigByFeature(config, kiosk)\n const kioskHeight = isLocatedKioskModel3dAvailable\n ? 0\n : _.get(kioskConfig, \"height\", 0)\n\n const coordinates = _.get(geometry, \"coordinates\")\n\n const markerProperties = {\n ...properties,\n coordinates,\n id,\n feature_type,\n }\n\n const material = _.get(\n spriteMarkerMaterialObj,\n `${feature_type}.${category}`\n )\n\n const highlightOptions = _.get(\n spriteHighlightMarkerOptionObj,\n `${PREFIX_HIGHLIGHTED_SYMBOL_KEY}-${feature_type}.${category}`\n )\n\n const options = {\n scale: 0.05,\n altitude: unitHeight + kioskHeight,\n highlight: highlightOptions,\n interactive: is_clickable,\n }\n\n return create3DMarker(\n coordinates,\n options,\n material,\n threeLayer,\n markerProperties\n )\n },\n\n create3DOccupantAmenityMarker: (feature, threeLayer, config) => {\n const { geometry, properties, feature_type, id } = feature\n const { category, unit, kiosk } = properties\n const amenityLocation = kiosk || unit\n const locationConfig = getExtrudeConfigByFeature(config, amenityLocation)\n const coordinates = _.get(geometry, \"coordinates\")\n\n const markerProperties = {\n ...properties,\n coordinates,\n id,\n feature_type,\n }\n\n const material = _.get(\n spriteMarkerMaterialObj,\n `${feature_type}.${category}`\n )\n\n const highlightOptions = _.get(\n spriteHighlightMarkerOptionObj,\n `${PREFIX_HIGHLIGHTED_SYMBOL_KEY}-${feature_type}.${category}`\n )\n\n const options = {\n scale: 0.05,\n altitude: _.get(locationConfig, \"height\", 0),\n highlight: highlightOptions,\n }\n\n return create3DMarker(\n coordinates,\n options,\n material,\n threeLayer,\n markerProperties\n )\n },\n create3DOpeningMarker: (feature, threeLayer, config) => {\n const { geometry, properties, feature_type, id } = feature\n const { category, unit, kiosk } = properties\n const amenityLocation = kiosk || unit\n const locationConfig = getExtrudeConfigByFeature(config, amenityLocation)\n const coordinates = _.get(geometry, \"coordinates\")\n\n const markerProperties = {\n ...properties,\n coordinates,\n id,\n feature_type,\n }\n\n const material = _.get(\n spriteMarkerMaterialObj,\n `${feature_type}.${category}`\n )\n\n const highlightOptions = _.get(\n spriteHighlightMarkerOptionObj,\n `${PREFIX_HIGHLIGHTED_SYMBOL_KEY}-${feature_type}.${category}`\n )\n\n const options = {\n scale: 0.05,\n altitude: _.get(locationConfig, \"height\", 0),\n highlight: highlightOptions,\n }\n\n return create3DMarker(\n coordinates,\n options,\n material,\n threeLayer,\n markerProperties\n )\n },\n\n createExtrudedUnit: (unit, threeLayer, options) => {\n const extrudeHeight = _.get(options, \"height\")\n if (!extrudeHeight) return\n //NOTE: this is temporary condition that only extrude when the unit is \"room\"\n const unitProperty = getFeatureProperties(unit)\n //NOTE: offset will be dynamic in future improvement\n const options3d = {\n // TODO: Move to extrude config later\n offset: -0.1,\n altitude: _.get(options, \"altitude\", 0),\n }\n const color = unitProperty.defaultColor\n if (color === \"transparent\") return\n const material = new MeshLambertMaterial({\n color,\n transparent: true,\n })\n //create polygon with line-offset if geometry is lineString\n if (unit.geometry.type === \"LineString\") {\n const polygon = createPolygonFromLineString(unit.geometry)\n const geometry = {\n type: \"Polygon\",\n coordinates: polygon,\n }\n return createExtrudePolygon(\n geometry,\n threeLayer,\n material,\n extrudeHeight,\n unitProperty,\n options3d\n )\n }\n const object = createExtrudePolygon(\n unit.geometry,\n threeLayer,\n material,\n extrudeHeight,\n unitProperty,\n options3d\n )\n return object\n },\n }\n}\n\nconst EXCEPT_AMENITY_LOCATION_CATEGORIES = [\n \"walkway\",\n \"nonpublic\",\n \"parking\",\n \"opentobelow\",\n \"unspecified\",\n]\nexport const getLocationByAmenity = (feature) => {\n const unit = _.get(feature, \"properties.units[0]\", null)\n const unitCategory = _.get(unit, \"properties.category\")\n if (!unit) return feature.id\n return EXCEPT_AMENITY_LOCATION_CATEGORIES.includes(unitCategory)\n ? feature\n : unit\n}\n\nexport const getLocationByOccupant = (feature) => {\n const kiosk = _.get(feature, \"properties.kiosk\", null)\n const unit = _.get(feature, \"properties.anchor.properties.unit\", null)\n return kiosk || unit\n}\n\nexport const getLocationIdByFeature = (feature) => {\n switch (feature?.feature_type) {\n case \"kiosk\":\n case \"unit\":\n case \"opening\":\n return feature.id\n case \"amenity\":\n return getLocationByAmenity(feature)?.id\n case \"occupant\":\n return getLocationByOccupant(feature)?.id\n case \"promotion\":\n case \"event\":\n return feature.properties?.feature_id\n default:\n return\n }\n}\n\nexport const getFeatureByLocationId = (id, features = []) => {\n return features?.find((f) => {\n const mainLocationId = getLocationIdByFeature(f)\n const relatedLocationIds = getRelatedLocationIdsByFeature(f)\n return mainLocationId === id || relatedLocationIds.includes(id)\n })\n}\n\nexport const isClickableFeature = (feature) => {\n const isClickable = _.get(feature, \"properties.is_clickable\")\n switch (feature?.feature_type) {\n case \"amenity\":\n return _.isNull(isClickable) ? true : isClickable\n case \"occupant\":\n return true\n default:\n return\n }\n}\n\nexport const getLocationByFeature = (feature) => {\n switch (feature?.feature_type) {\n case \"amenity\":\n return getLocationByAmenity(feature)\n case \"occupant\":\n return getLocationByOccupant(feature)\n default:\n return\n }\n}\n\n/*\n * Utility functions to retrieve related locations for amenities and occupants.\n * - Used for highlighting on the floor plan.\n * - Displays location details.\n */\n\nexport const getRelatedLocationsByOccupant = (feature) => {\n const kiosks = _.get(feature, \"properties.kiosks\", [])\n const units = _.get(feature, \"properties.units\", [])\n return [...kiosks, ...units]\n}\n\nexport const getRelatedLocationsByAmenity = (feature) => {\n const units = _.get(feature, \"properties.units\", [])\n\n if (units.length === 0) return [feature]\n\n return units.filter((unit) => {\n const unitCategory = _.get(unit, \"properties.category\")\n return !EXCEPT_AMENITY_LOCATION_CATEGORIES.includes(unitCategory)\n })\n}\n\nexport const getRelatedLocationIdsByFeature = (feature) => {\n switch (feature?.feature_type) {\n case \"amenity\":\n return getRelatedLocationsByAmenity(feature).map((v) => v?.id)\n case \"occupant\":\n return getRelatedLocationsByOccupant(feature).map((v) => v?.id)\n default:\n return []\n }\n}\n\nexport const getRelatedLocationsByFeature = (feature) => {\n switch (feature?.feature_type) {\n case \"amenity\":\n return getRelatedLocationsByAmenity(feature)\n case \"occupant\":\n return getRelatedLocationsByOccupant(feature)\n default:\n return []\n }\n}\n\nexport const getOrdinalByLocationId = (locationId, feature) => {\n if (!feature) return null\n\n const mainUnit = _.get(feature, \"properties.unit\")\n const mainKiosk = _.get(feature, \"properties.kiosk\")\n const relatedLocations = getRelatedLocationsByFeature(feature)\n\n const allLocations = [mainUnit, mainKiosk, ...relatedLocations].filter(\n Boolean\n )\n const targetLocation = allLocations.find(\n (location) => location.id === locationId\n )\n\n return targetLocation\n ? _.get(targetLocation, \"properties.level.properties.ordinal\") ||\n _.get(targetLocation, \"properties.ordinal\")\n : null\n}\n","import * as maptalks from \"maptalks\"\nimport { BaseObject } from \"maptalks.three\"\nimport {\n LineBasicMaterial,\n BufferGeometry,\n Float32BufferAttribute,\n Line,\n TextureLoader,\n SpriteMaterial,\n Sprite,\n} from \"three\"\nimport _ from \"lodash\"\n\nconst OPTIONS = {\n altitude: 25,\n scale: 0.00015,\n alphaTest: 0.3,\n legColor: \"#ff0400\",\n showLeg: true,\n}\n\nconst getImgDimension = async (url) => {\n const img = new Image()\n img.src = url\n await img.decode()\n return { naturalWidth: img.naturalWidth, naturalHeight: img.naturalHeight }\n}\n\nexport class Billboard extends BaseObject {\n #layer = null\n constructor(coordinate, options, src, layer, properties) {\n options = maptalks.Util.extend({}, OPTIONS, options, {\n layer,\n coordinate,\n })\n super()\n //Initialize internal configuration\n this.#layer = layer\n this._initOptions(options)\n const {\n altitude = OPTIONS.altitude,\n scale = OPTIONS.scale,\n alphaTest = OPTIONS.alphaTest,\n legColor = OPTIONS.legColor,\n showLeg = OPTIONS.showLeg,\n } = options\n this.properties = { ...properties }\n this._createGroup()\n\n // Screen size / base mobile screen size ratio => 375\n const divider = _.clamp(window.innerWidth / 375 / 1.75, 1, 1.7)\n // Leg\n if (showLeg) {\n const lineMaterial = new LineBasicMaterial({\n color: legColor,\n transparent: true,\n })\n const lineHeight = layer.altitudeToVector3(altitude, altitude).x\n const lineGeometry = new BufferGeometry()\n const positions = [0, 0, 0, 0, 0, -lineHeight]\n lineGeometry.setAttribute(\n \"position\",\n new Float32BufferAttribute(positions, 3)\n )\n const line = new Line(lineGeometry, lineMaterial)\n this.getObject3d().add(line)\n }\n\n getImgDimension(src).then(({ naturalWidth, naturalHeight }) => {\n // Image\n const map = new TextureLoader().load(src)\n const material = new SpriteMaterial({\n map: map,\n color: 0xffffff,\n alphaTest: alphaTest,\n })\n material.needsUpdate = true\n const sprite = new Sprite(material)\n sprite.material.sizeAttenuation = false\n sprite.scale.set(\n (scale * naturalWidth) / divider,\n (scale * naturalHeight) / divider,\n 1\n )\n this.getObject3d().add(sprite)\n })\n\n // set object3d position\n const z = layer.altitudeToVector3(altitude, altitude).x\n const position = layer.coordinateToVector3(coordinate, z)\n _.set(this.properties, \"default.position\", position)\n _.set(this.properties, \"default.altitude\", altitude)\n _.set(this.properties, \"default.scale\", scale)\n this.getObject3d().position.copy(position)\n }\n\n setLineHeight(altitude) {\n const lineHeight = this.#layer.altitudeToVector3(altitude, altitude).x\n const geometry = this.getObject3d().children[0].geometry\n const positionAttribute = geometry.getAttribute(\"position\")\n positionAttribute.setZ(1, -lineHeight)\n positionAttribute.needsUpdate = true\n\n this.getObject3d().position.z = lineHeight\n }\n}\n","import { BaseObject, ThreeLayer } from \"maptalks.three\"\nimport { Sprite, SpriteMaterial } from \"three\"\nimport _ from \"lodash\"\n\nconst DEFAULT_SCALE = 0.05\nconst DEFAULT_ALTITUDE = 0\nconst DEFAULT_ALPHATEST = 0.3\nconst DEFAULT_OPTIONS = {\n scale: DEFAULT_SCALE,\n altitude: DEFAULT_ALTITUDE,\n alphaTest: DEFAULT_ALPHATEST,\n highlight: {\n options: {\n scale: DEFAULT_SCALE * 1.25,\n },\n material: null,\n },\n}\n\ninterface IOptions {\n scale: number\n altitude: number\n alphaTest?: number\n highlight?: {\n options: {\n altitude?: number\n scale?: number\n }\n material?: SpriteMaterial\n }\n}\n\nexport class SpriteMarker extends BaseObject {\n #default = null\n #highlight = null\n constructor(\n coordinate,\n options: IOptions,\n material: SpriteMaterial,\n layer: ThreeLayer,\n properties: object\n ) {\n super()\n //Initialize internal configuration\n this._initOptions(options)\n this._createGroup()\n const {\n altitude = DEFAULT_OPTIONS.altitude,\n scale = DEFAULT_OPTIONS.scale,\n highlight = DEFAULT_OPTIONS.highlight,\n alphaTest = DEFAULT_OPTIONS.alphaTest,\n } = options\n this.properties = { ...properties }\n\n const modifiedAltitude = altitude + 2\n\n this.#default = { options: { scale, altitude: modifiedAltitude }, material }\n this.#highlight = _.merge({}, DEFAULT_OPTIONS.highlight, highlight)\n\n /**\n * Add alphaTest to render only non-transparent pixels in PNG images.\n * [@Doc](https://threejs.org/docs/#api/en/materials/Material.alphaTest)\n */\n if (material && material instanceof SpriteMaterial)\n material.alphaTest = alphaTest\n\n const sprite = new Sprite(material)\n sprite.scale.set(scale, scale, scale) // Set sprite scale\n\n const obj3d = this.getObject3d()\n obj3d.add(sprite)\n // set object3d position\n const z = layer.altitudeToVector3(modifiedAltitude, modifiedAltitude).x\n const position = layer.coordinateToVector3(coordinate, z)\n _.set(this.properties, \"default.position\", position)\n this.getObject3d().position.copy(position)\n }\n\n // Different objects need to implement their own methods\n setSymbol(material: SpriteMaterial) {\n if (material && material instanceof SpriteMaterial) {\n const sprite = (this.getObject3d() as any).children[0]\n\n if (!sprite) return this\n\n sprite.material = material\n sprite.material.needsUpdate = true\n }\n return this\n }\n\n setScale(scaleX: number, scaleY: number = scaleX, scaleZ: number = scaleX) {\n const sprite = (this.getObject3d() as any).children[0]\n if (!sprite) return this\n\n sprite.scale.set(scaleX, scaleY, scaleZ)\n\n return this\n }\n\n // Different objects need to implement their own methods\n getSymbol(): SpriteMaterial {\n return (this.getObject3d() as any)?.children[0]?.material\n }\n\n highlight() {\n const { material, options } = this.#highlight\n if (material) this.setSymbol(material)\n if (options.scale) this.setScale(options.scale)\n if (options.altitude) this.setAltitude(options.altitude)\n return this\n }\n\n removeHighlight() {\n const { material, options } = this.#default\n if (material) this.setSymbol(material)\n if (options.scale) this.setScale(options.scale)\n if (options.altitude) this.setAltitude(options.altitude)\n return this\n }\n}\n","import * as maptalks from \"maptalks\"\nimport { BaseObject } from \"maptalks.three\"\nimport { MeshBasicMaterial, ShaderMaterial, Color } from \"three\"\n\nconst OPTIONS = {\n altitude: 0,\n}\n\nconst DEFAULT_LINE_OPTION = {\n color: \"#000\",\n opacity: 1,\n}\nconst DEFAULT_LINE_EFFECT_OPTION = {\n color: \"#000\",\n opacity: 1,\n}\n\n// In case we want to open/close this animation per project.\nconst ENABLE_ANIMATED_PATH = true\n\nexport class NavigationPath extends BaseObject {\n constructor(\n feature,\n layer,\n properties,\n options,\n lineOptions = DEFAULT_LINE_OPTION,\n outlineOption = DEFAULT_LINE_EFFECT_OPTION\n ) {\n options = maptalks.Util.extend({}, OPTIONS, options, {\n layer,\n })\n super()\n //Initialize internal configuration\n this._initOptions(options)\n const { altitude = OPTIONS.altitude } = options\n this.properties = { ...properties }\n this._createGroup()\n\n const { color: lineColor, opacity: lineOpacity } =\n lineOptions || DEFAULT_LINE_OPTION\n\n const staticMaterial = new MeshBasicMaterial({\n transparent: true,\n color: lineColor || \"#fff\",\n opacity: lineOpacity || 1,\n depthWrite: false,\n })\n\n const uniforms = {\n time: { value: 0 },\n color: { value: new Color(lineColor || \"#fff\") },\n opacity: { value: lineOpacity || 1 },\n }\n this._uniforms = uniforms\n this._t = 0 // Start time = 0\n\n /**\n * Animation formula\n * float dash = smoothstep(0.3, 0.7, abs(sin(vUv.x * 1.0 - time * 0.1)));\n * | vUv.x * 1.0 | controls dash length & frequency\n * | - time * 1.0 | animates motion to the right\n */\n const animatedMaterial = new ShaderMaterial({\n uniforms,\n transparent: true,\n depthWrite: false,\n vertexShader: `\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n }\n `,\n fragmentShader: `\n uniform float time;\n uniform vec3 color;\n uniform float opacity;\n varying vec2 vUv;\n\n void main() {\n float dash = smoothstep(0.3, 0.7, abs(sin(vUv.x * 1.0 - time * 0.1)));\n gl_FragColor = vec4(color, opacity * dash);\n }\n `,\n })\n\n const pathGeometry = maptalks.GeoJSON.toGeometry(feature)\n const line = layer.toPath(\n pathGeometry,\n {\n interactive: false,\n cornerRadius: 2,\n width: 0.5,\n },\n ENABLE_ANIMATED_PATH ? animatedMaterial : staticMaterial\n )\n\n const { color: outlineColor, opacity: outlineOpacity } = outlineOption || {}\n const outlineMaterial = new MeshBasicMaterial({\n transparent: true,\n color: outlineColor || \"#fff\",\n opacity: outlineOpacity || 1,\n })\n\n const lineOutLine = layer.toPath(\n pathGeometry,\n {\n interactive: false,\n cornerRadius: 2,\n width: 1,\n },\n outlineMaterial\n )\n this.getObject3d().add(lineOutLine.getObject3d())\n this.getObject3d().add(line.getObject3d())\n\n // set object3d position\n const z = layer.altitudeToVector3(altitude + 0.25, altitude + 0.25).x\n const pos = this.getObject3d().position\n\n const position = layer.coordinateToVector3([pos.x, pos.y], z)\n // _.set(this.properties, \"default.position\", position)\n\n this.getObject3d().position.copy(position)\n }\n\n _animation() {\n this._t = this._t + 1\n this._uniforms.time.value = this._t\n }\n}\n","import center from \"@turf/center\"\nimport { Polygon, MultiPolygon, Point, LineString } from \"geojson\"\nimport _ from \"lodash\"\nimport turfLineOffset from \"@turf/line-offset\"\nimport { lineString as turfLineString } from \"@turf/helpers\"\n\n// Calculates the center point of a GeoJSON geometry and Return as a Coordinates.\nexport const getCenterFromGeometry = (geometry?: Polygon | MultiPolygon | Point | LineString): number[] | null => {\n try {\n const { type = null, coordinates = null } = geometry\n if (!type || !coordinates) return null\n const centerPoint = center(geometry)\n return _.get(centerPoint, \"geometry.coordinates\") // Coordinates\n } catch (error) {\n return null\n }\n}\n\nexport const createPolygonFromLineString = (geometry) => {\n const line = turfLineString(geometry.coordinates)\n const left = turfLineOffset(line, 0.3, { units: \"meters\" })\n const right = turfLineOffset(line, -0.3, { units: \"meters\" })\n const leftCoords = left.geometry.coordinates\n const rightCoords = right.geometry.coordinates.reverse()\n const polygon = [...leftCoords, ...rightCoords, leftCoords[0]]\n return [polygon]\n}\n","export const svgToPng = (svgString: string, scaleFactor: number = 1) => {\n const svgBlob = new Blob([svgString], { type: \"image/svg+xml\" })\n const url = URL.createObjectURL(svgBlob)\n const img = new Image()\n return new Promise((resolve, reject) => {\n img.onload = function () {\n // Calculate the new dimensions\n const newWidth = img.width * scaleFactor\n const newHeight = img.height * scaleFactor\n\n // Create a canvas with the new dimensions\n const canvas = document.createElement(\"canvas\")\n canvas.width = newWidth\n canvas.height = newHeight\n const ctx = canvas.getContext(\"2d\")\n\n // Draw the SVG image onto the canvas with the scaled dimensions\n ctx.drawImage(img, 0, 0, newWidth, newHeight)\n\n // Convert canvas to PNG\n const pngDataUrl = canvas.toDataURL(\"image/png\")\n\n // Resolve the Promise with the PNG data URL\n resolve(pngDataUrl)\n }\n\n // Handle image load errors\n img.onerror = function (error) {\n reject(error)\n }\n\n img.src = url\n })\n}\n\nexport const createSVGPathFromMarkerSymbol = (style) => {\n const {\n markerWidth = 24,\n markerDx = 0,\n markerDy = 0,\n markerFill,\n markerPath,\n } = style\n const scale = markerWidth / 24\n return `<path d=\"${markerPath}\" style=\"transform:translate(${markerDx}px, ${markerDy}px) scale(${scale})\" fill=\"${markerFill}\"/>`\n}\n","interface ICoordinate {\n x: number\n y: number\n z?: number\n}\n\ntype RadToDegree = (rad: number) => number\n\ntype GetBearingBetweenPoints = (\n origin: ICoordinate,\n destination: ICoordinate\n) => number\n\ntype GetSuitablyValueBetweenBearings = (\n newBearing: number,\n currentBearing: number\n) => number\n\nconst radToDegree: RadToDegree = (rad) => rad * (180 / Math.PI)\n\nexport const getBearingBetweenPoints: GetBearingBetweenPoints = (\n origin,\n destination\n) => {\n const twoPI = Math.PI * 2\n\n if (origin.x === destination.x && origin.y === destination.y) return\n let theta = Math.atan2(destination.x - origin.x, destination.y - origin.y)\n\n if (theta < 0.0) theta += twoPI\n\n return Math.floor(radToDegree(theta))\n}\n\nexport const getSuitablyValueBetweenBearings: GetSuitablyValueBetweenBearings =\n (newBearing, currentBearing) => {\n const difference = Math.abs(newBearing - currentBearing)\n\n // Adjust newBearing to ensure the shortest direction\n if (difference > 180)\n return newBearing > 0 ? newBearing - 360 : newBearing + 360\n\n return newBearing // Return as is if the difference is within limits\n }\n","import { Extent } from \"maptalks\"\nimport { Map } from \"maptalks-gl\"\nimport { MapAnimationOptionsType, MapPaddingType, MapViewType } from \"maptalks/dist/map/Map\"\nimport bbox from \"@turf/bbox\"\nimport scale from \"@turf/transform-scale\"\nimport bboxPolygon from \"@turf/bbox-polygon\"\n\nexport interface CameraManagerOptions {\n defaultView?: MapViewType\n}\n\nexport class CameraManager {\n map: Map\n\n constructor(map: Map, options?: CameraManagerOptions) {\n this.map = map\n\n if (options?.defaultView) {\n this.setView(options?.defaultView)\n }\n }\n\n /** Public methods */\n getView = (): MapViewType => {\n return this.map.getView()\n }\n \n setView = (value: MapViewType) => {\n if (this.map && Object.keys(value).length !== 0) {\n this.map.setView(value)\n }\n }\n\n animateTo = (view: MapViewType, options: MapAnimationOptionsType = {}, step?: (frame: any) => void) => {\n this.map.animateTo(view, options, step)\n }\n\n setMaxExtent(extent: Extent) {\n return this.map.setMaxExtent(extent)\n }\n\n getFeatureExtent = (feature, scaleFactor = 1) => {\n const [minX, minY, maxX, maxY] = bbox(\n scale(bboxPolygon(bbox(feature)), scaleFactor)\n )\n return new Extent(minX, minY, maxX, maxY)\n }\n\n getExtentZoom = (\n extent: Extent,\n options: { isFraction?: boolean; padding?: MapPaddingType } = {\n isFraction: false,\n padding: {\n paddingLeft: 0,\n paddingRight: 0,\n paddingTop: 0,\n paddingBottom: 0,\n },\n }\n ) => {\n const { isFraction = false, padding } = options\n return this.map.getFitZoom(extent, isFraction, padding)\n }\n\n set maxZoom(value: number) {\n this.map.setMaxZoom(value)\n const spatialReference = {\n projection: \"EPSG:3857\",\n resolutions: (function () {\n const resolutions = []\n const d = 2 * 6378137 * Math.PI\n for (let i = 0; i < value; i++) {\n resolutions[i] = d / (256 * Math.pow(2, i))\n }\n return resolutions\n })(),\n }\n this.map.setSpatialReference(spatialReference)\n }\n\n set minZoom(value: number) {\n this.map.setMinZoom(value)\n }\n\n}\n","import { feature, point, lineString, isObject } from \"@turf/helpers\";\n\n/**\n * Callback for coordEach\n *\n * @callback coordEachCallback\n * @param {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 * @returns {void}\n */\n\n/**\n * Iterate over coordinates in any GeoJSON object, similar to Array.forEach()\n *\n * @function\n * @param {AllGeoJSON} geojson any GeoJSON object\n * @param {coordEachCallback} 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,\n k,\n l,\n geometry,\n stopG,\n 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\n ? geojson.features[featureIndex].geometry\n : isFeature\n ? geojson.geometry\n : geojson;\n isGeometryCollection = geometryMaybeCollection\n ? geometryMaybeCollection.type === \"GeometryCollection\"\n : false;\n stopG = isGeometryCollection\n ? geometryMaybeCollection.geometries.length\n : 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]\n : 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 =\n excludeWrapCoord &&\n (geomType === \"Polygon\" || geomType === \"MultiPolygon\")\n ? 1\n : 0;\n\n switch (geomType) {\n case null:\n break;\n case \"Point\":\n if (\n callback(\n coords,\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n return false;\n coordIndex++;\n multiFeatureIndex++;\n break;\n case \"LineString\":\n case \"MultiPoint\":\n for (j = 0; j < coords.length; j++) {\n if (\n callback(\n coords[j],\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n 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 (\n callback(\n coords[j][k],\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n 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 geometryIndex = 0;\n for (k = 0; k < coords[j].length; k++) {\n for (l = 0; l < coords[j][k].length - wrapShrink; l++) {\n if (\n callback(\n coords[j][k][l],\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n 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 (\n coordEach(geometry.geometries[j], callback, excludeWrapCoord) ===\n false\n )\n 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 {Reducer} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {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 * @returns {Reducer}\n */\n\n/**\n * Reduce coordinates in any GeoJSON object, similar to Array.reduce()\n *\n * @function\n * @param {AllGeoJSON} geojson any GeoJSON object\n * @param {coordReduceCallback} callback a method that takes (previousValue, currentCoord, coordIndex)\n * @param {Reducer} [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 {Reducer} 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(\n geojson,\n function (\n currentCoord,\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) {\n if (coordIndex === 0 && initialValue === undefined)\n previousValue = currentCoord;\n else\n previousValue = callback(\n previousValue,\n currentCoord,\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n );\n },\n excludeWrapCoord\n );\n return previousValue;\n}\n\n/**\n * Callback for propEach\n *\n * @callback propEachCallback\n * @param {GeoJsonProperties} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @returns {void}\n */\n\n/**\n * Iterate over properties in any GeoJSON object, similar to Array.forEach()\n *\n * @function\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {propEachCallback} 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 * 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 {Reducer} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {GeoJsonProperties} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @returns {Reducer}\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 * @function\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {propReduceCallback} callback a method that takes (previousValue, currentProperties, featureIndex)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer} 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)\n previousValue = currentProperties;\n else\n 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 * @returns {void}\n */\n\n/**\n * Iterate over features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @function\n * @param {FeatureCollection|Feature|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {featureEachCallback} 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 {Reducer} 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 * @returns {Reducer}\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @function\n * @param {FeatureCollection|Feature|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {featureReduceCallback} callback a method that takes (previousValue, currentFeature, featureIndex)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer} 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)\n 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 * @function\n * @param {AllGeoJSON} 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 {GeometryObject} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {GeoJsonProperties} featureProperties The current Feature Properties being processed.\n * @param {BBox} featureBBox The current Feature BBox being processed.\n * @param {Id} featureId The current Feature Id being processed.\n * @returns {void}\n */\n\n/**\n * Iterate over each geometry in any GeoJSON object, similar to Array.forEach()\n *\n * @function\n * @param {FeatureCollection|Feature|Geometry|GeometryObject|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {geomEachCallback} 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,\n j,\n g,\n geometry,\n 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 geometryMaybeCollection = isFeatureCollection\n ? geojson.features[i].geometry\n : isFeature\n ? geojson.geometry\n : geojson;\n featureProperties = isFeatureCollection\n ? geojson.features[i].properties\n : isFeature\n ? geojson.properties\n : {};\n featureBBox = isFeatureCollection\n ? geojson.features[i].bbox\n : isFeature\n ? geojson.bbox\n : undefined;\n featureId = isFeatureCollection\n ? geojson.features[i].id\n : isFeature\n ? geojson.id\n : undefined;\n isGeometryCollection = geometryMaybeCollection\n ? geometryMaybeCollection.type === \"GeometryCollection\"\n : false;\n stopG = isGeometryCollection\n ? geometryMaybeCollection.geometries.length\n : 1;\n\n for (g = 0; g < stopG; g++) {\n geometry = isGeometryCollection\n ? geometryMaybeCollection.geometries[g]\n : geometryMaybeCollection;\n\n // Handle null Geometry\n if (geometry === null) {\n if (\n callback(\n null,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) === false\n )\n 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 (\n callback(\n geometry,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) === false\n )\n return false;\n break;\n }\n case \"GeometryCollection\": {\n for (j = 0; j < geometry.geometries.length; j++) {\n if (\n callback(\n geometry.geometries[j],\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) === false\n )\n 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 {Reducer} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {GeometryObject} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {GeoJsonProperties} featureProperties The current Feature Properties being processed.\n * @param {BBox} featureBBox The current Feature BBox being processed.\n * @param {Id} featureId The current Feature Id being processed.\n * @returns {Reducer}\n */\n\n/**\n * Reduce geometry in any GeoJSON object, similar to Array.reduce().\n *\n * @function\n * @param {FeatureCollection|Feature|GeometryObject|GeometryCollection|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {geomReduceCallback} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer} 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(\n geojson,\n function (\n currentGeometry,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) {\n if (featureIndex === 0 && initialValue === undefined)\n previousValue = currentGeometry;\n else\n previousValue = callback(\n previousValue,\n currentGeometry,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n );\n }\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 * @returns {void}\n */\n\n/**\n * Iterate over flattened features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @function\n * @param {FeatureCollection|Feature|GeometryObject|GeometryCollection|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {flattenEachCallback} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex)\n * @returns {void}\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 (\n callback(\n feature(geometry, properties, { bbox: bbox, id: id }),\n featureIndex,\n 0\n ) === false\n )\n 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 (\n var multiFeatureIndex = 0;\n multiFeatureIndex < geometry.coordinates.length;\n multiFeatureIndex++\n ) {\n var coordinate = geometry.coordinates[multiFeatureIndex];\n var geom = {\n type: geomType,\n coordinates: coordinate,\n };\n if (\n callback(feature(geom, properties), featureIndex, multiFeatureIndex) ===\n false\n )\n 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 {Reducer} 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 * @returns {Reducer}\n */\n\n/**\n * Reduce flattened features in any GeoJSON object, similar to Array.reduce().\n *\n * @function\n * @param {FeatureCollection|Feature|GeometryObject|GeometryCollection|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {flattenReduceCallback} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer} 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(\n geojson,\n function (currentFeature, featureIndex, multiFeatureIndex) {\n if (\n featureIndex === 0 &&\n multiFeatureIndex === 0 &&\n initialValue === undefined\n )\n previousValue = currentFeature;\n else\n previousValue = callback(\n previousValue,\n currentFeature,\n featureIndex,\n multiFeatureIndex\n );\n }\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 {AllGeoJSON} geojson any GeoJSON\n * @param {segmentEachCallback} 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, featureIndex, multiFeatureIndex) {\n var segmentIndex = 0;\n\n // Exclude null Geometries\n if (!feature.geometry) return;\n // (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n var type = feature.geometry.type;\n if (type === \"Point\" || type === \"MultiPoint\") return;\n\n // Generate 2-vertex line segments\n var previousCoords;\n var previousFeatureIndex = 0;\n var previousMultiIndex = 0;\n var prevGeomIndex = 0;\n if (\n coordEach(\n feature,\n function (\n currentCoord,\n coordIndex,\n featureIndexCoord,\n multiPartIndexCoord,\n geometryIndex\n ) {\n // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false`\n if (\n previousCoords === undefined ||\n featureIndex > previousFeatureIndex ||\n multiPartIndexCoord > previousMultiIndex ||\n geometryIndex > prevGeomIndex\n ) {\n previousCoords = currentCoord;\n previousFeatureIndex = featureIndex;\n previousMultiIndex = multiPartIndexCoord;\n prevGeomIndex = geometryIndex;\n segmentIndex = 0;\n return;\n }\n var currentSegment = lineString(\n [previousCoords, currentCoord],\n feature.properties\n );\n if (\n callback(\n currentSegment,\n featureIndex,\n multiFeatureIndex,\n geometryIndex,\n segmentIndex\n ) === false\n )\n return false;\n segmentIndex++;\n previousCoords = currentCoord;\n }\n ) === false\n )\n 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 {Reducer} 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 * @returns {Reducer}\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 {segmentReduceCallback} callback a method that takes (previousValue, currentSegment, currentIndex)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer}\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 * //= segmentIndex\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(\n geojson,\n function (\n currentSegment,\n featureIndex,\n multiFeatureIndex,\n geometryIndex,\n segmentIndex\n ) {\n if (started === false && initialValue === undefined)\n previousValue = currentSegment;\n else\n previousValue = callback(\n previousValue,\n currentSegment,\n featureIndex,\n multiFeatureIndex,\n geometryIndex,\n segmentIndex\n );\n started = true;\n }\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 * @returns {void}\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 * @function\n * @param {FeatureCollection<Lines>|Feature<Lines>|Lines|Feature<GeometryCollection>|GeometryCollection} geojson object\n * @param {lineEachCallback} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @returns {void}\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, featureIndex, multiFeatureIndex) {\n if (feature.geometry === null) return;\n var type = feature.geometry.type;\n var coords = feature.geometry.coordinates;\n switch (type) {\n case \"LineString\":\n if (callback(feature, featureIndex, multiFeatureIndex, 0, 0) === false)\n return false;\n break;\n case \"Polygon\":\n for (\n var geometryIndex = 0;\n geometryIndex < coords.length;\n geometryIndex++\n ) {\n if (\n callback(\n lineString(coords[geometryIndex], feature.properties),\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n 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 {Reducer} 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 * @returns {Reducer}\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @function\n * @param {FeatureCollection<Lines>|Feature<Lines>|Lines|Feature<GeometryCollection>|GeometryCollection} geojson object\n * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer} 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(\n geojson,\n function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n if (featureIndex === 0 && initialValue === undefined)\n previousValue = currentLine;\n else\n previousValue = callback(\n previousValue,\n currentLine,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n );\n }\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)\n 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(\n [coords[segmentIndex], coords[segmentIndex + 1]],\n properties,\n options\n );\n case \"Polygon\":\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (segmentIndex < 0)\n segmentIndex = coords[geometryIndex].length + segmentIndex - 1;\n return lineString(\n [\n coords[geometryIndex][segmentIndex],\n coords[geometryIndex][segmentIndex + 1],\n ],\n properties,\n options\n );\n case \"MultiLineString\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (segmentIndex < 0)\n segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1;\n return lineString(\n [\n coords[multiFeatureIndex][segmentIndex],\n coords[multiFeatureIndex][segmentIndex + 1],\n ],\n properties,\n options\n );\n case \"MultiPolygon\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0)\n geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (segmentIndex < 0)\n segmentIndex =\n coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1;\n return lineString(\n [\n coords[multiFeatureIndex][geometryIndex][segmentIndex],\n coords[multiFeatureIndex][geometryIndex][segmentIndex + 1],\n ],\n properties,\n options\n );\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)\n 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)\n 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)\n coordIndex = coords[geometryIndex].length + coordIndex;\n return point(coords[geometryIndex][coordIndex], properties, options);\n case \"MultiLineString\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (coordIndex < 0)\n coordIndex = coords[multiFeatureIndex].length + coordIndex;\n return point(coords[multiFeatureIndex][coordIndex], properties, options);\n case \"MultiPolygon\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0)\n geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (coordIndex < 0)\n coordIndex =\n coords[multiFeatureIndex][geometryIndex].length - coordIndex;\n return point(\n coords[multiFeatureIndex][geometryIndex][coordIndex],\n properties,\n options\n );\n }\n throw new Error(\"geojson is invalid\");\n}\n\nexport {\n coordReduce,\n coordEach,\n propEach,\n propReduce,\n featureReduce,\n featureEach,\n coordAll,\n geomReduce,\n geomEach,\n flattenReduce,\n flattenEach,\n segmentReduce,\n segmentEach,\n lineReduce,\n lineEach,\n findSegment,\n findPoint,\n};\n","import { BBox } from \"geojson\";\nimport { AllGeoJSON } from \"@turf/helpers\";\nimport { coordEach } from \"@turf/meta\";\n\n/**\n * Calculates the bounding box for any GeoJSON object, including FeatureCollection.\n * Uses geojson.bbox if available and options.recompute is not set.\n *\n * @function\n * @param {GeoJSON} geojson any GeoJSON object\n * @param {Object} [options={}] Optional parameters\n * @param {boolean} [options.recompute] Whether to ignore an existing bbox property on geojson\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(\n geojson: AllGeoJSON,\n options: {\n recompute?: boolean;\n } = {}\n): BBox {\n if (geojson.bbox != null && true !== options.recompute) {\n return geojson.bbox;\n }\n const result: BBox = [Infinity, Infinity, -Infinity, -Infinity];\n coordEach(geojson, (coord) => {\n if (result[0] > coord[0]) {\n result[0] = coord[0];\n }\n if (result[1] > coord[1]) {\n result[1] = coord[1];\n }\n if (result[2] < coord[0]) {\n result[2] = coord[0];\n }\n if (result[3] < coord[1]) {\n result[3] = coord[1];\n }\n });\n return result;\n}\n\nexport { bbox };\nexport default bbox;\n","import * as maptalks from \"maptalks-gl\"\nimport { min, compact, isFunction } from \"lodash\"\nimport { center as turfCenter } from \"@turf/center\"\nimport { polygon } from \"@turf/helpers\"\nimport { Position } from \"geojson\"\nimport { BaseObject, ThreeLayer } from \"maptalks.three\"\nimport * as THREE from \"three\"\n\nimport type { HighlightElementOptions, IHighlightController, MapElement, RendererManagerOptions } from \"./types\"\nimport { Element3DRenderer } from \"./3d/Element3DRenderer\"\nimport { Element2DRenderer } from \"./2d/Element2DRenderer\"\nimport { Marker2DRenderer } from \"./2d/Marker2DRenderer\"\nimport { AnyMarkerOptions, ImageMarkerOptions, Marker3DRenderer } from \"./3d/Marker3DRenderer\"\n\nimport {\n KioskFeaturePopulated,\n OpeningFeature,\n OpeningFeaturePopulated,\n UnitFeaturePopulated,\n VenueDataClient,\n} from \"../../data\"\nimport { angleBetweenLineStrings } from \"./utils/angleBetweenLineString\"\nimport { findUnitOnPoint } from \"./utils/findUnitOnPoint\"\nimport { TextMarkerOptions } from \"./3d/objects/TextSpriteMarker\"\n\nfunction delay(ms: number) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nexport class RendererManager extends EventTarget {\n map: maptalks.Map\n\n options: RendererManagerOptions\n\n // Client for fetching data\n #dataClient: VenueDataClient\n\n #isClicked = false\n #onClickElement = (e) => {}\n\n /** Elements: Responsible for converting feature info elements and add to map */\n private elementRenderer: Element2DRenderer | Element3DRenderer\n private markerRenderer: Marker2DRenderer | Marker3DRenderer\n\n private elementsMap: Map<string, MapElement>\n private elementsByOrdinal: Map<\n number,\n Array<MapElement>\n >\n\n private currentOrdinals: number | number[] | null\n\n private markersMap: Map<string, maptalks.ui.UIMarker | BaseObject>\n private markersByOrdinal: Map<\n number,\n Array<maptalks.ui.UIMarker> | Array<BaseObject>\n >\n\n private highlightControllers: IHighlightController[] = []\n\n constructor(map: maptalks.Map, dataClient: VenueDataClient, options: RendererManagerOptions) {\n super()\n this.map = map\n this.options = options\n this.elementsMap = new Map()\n this.elementsByOrdinal = new Map()\n\n this.markersMap = new Map()\n this.markersByOrdinal = new Map()\n\n this.#dataClient = dataClient\n \n const _this = this\n\n if (options.type === \"3D\") {\n const groupLayer = this.map.getLayer('group') as maptalks.GroupGLLayer\n const threeLayer = groupLayer.getLayer('three') as ThreeLayer\n\n threeLayer.prepareToDraw = function (gl, scene, camera) {\n \n function findBadMeshes(scene: THREE.Scene) {\n const bad: Array<{ mesh: THREE.Mesh; index: number; value: number }> = [];\n\n scene.traverse((obj: any) => {\n if (!obj?.isMesh) return;\n const geom = obj.geometry as THREE.BufferGeometry | undefined;\n const pos = geom?.attributes?.position?.array as Float32Array | undefined;\n if (!pos || pos.length === 0) return;\n\n for (let i = 0; i < pos.length; i++) {\n const v = pos[i];\n if (!Number.isFinite(v)) {\n bad.push({ mesh: obj, index: i, value: v });\n break;\n }\n }\n });\n\n if (bad.length) {\n console.group(`❌ Found ${bad.length} meshes with invalid positions`);\n for (const b of bad) {\n console.log({\n name: b.mesh.name,\n userData: b.mesh.userData,\n uuid: b.mesh.uuid,\n badIndex: b.index,\n badValue: b.value,\n });\n }\n console.groupEnd();\n } else {\n console.log(\"✅ No invalid meshes found\");\n }\n\n return bad;\n }\n\n const ambientLight = new THREE.AmbientLight(0xffffff, 0.3)\n scene.add(ambientLight)\n \n const dirColor = 0xffffff\n const dllight = new THREE.DirectionalLight(dirColor, 0.8)\n dllight.position.set(0, -10, 20).normalize()\n scene.add(dllight)\n \n // nice optional fill\n const hemi = new THREE.HemisphereLight(0xffffff, 0x444444, 0.4)\n scene.add(hemi)\n\n // Element renderer creates and owns the ThreeLayer\n _this.elementRenderer = new Element3DRenderer(map, options.elements)\n\n // Get the ThreeLayer from element renderer to share with marker renderer\n _this.markerRenderer = new Marker3DRenderer(map, {}, threeLayer)\n\n if (typeof options.onRendererReady === 'function') {\n options.onRendererReady()\n }\n\n _this.#createElements()\n\n setTimeout(() => {\n findBadMeshes(scene)\n }, 3000)\n }\n \n } else {\n // 2D doesn't need shared layer\n this.elementRenderer = new Element2DRenderer(map, options.elements)\n this.markerRenderer = new Marker2DRenderer(map)\n\n this.#createElements()\n }\n }\n\n set onClickElement(func) {\n this.#onClickElement = func\n }\n\n handleClickElement = (e) => {\n if (this.#isClicked) return\n this.#isClicked = true\n const onClickElement = this.#onClickElement\n if (!isFunction(onClickElement)) return\n this.#onClickElement(e)\n this.#isClicked = false\n }\n\n getElementsByOrdinal = (ordinal: number) => {\n const exist = this.elementsByOrdinal.get(ordinal)\n if (!exist) this.elementsByOrdinal.set(ordinal, [])\n return this.elementsByOrdinal.get(ordinal)\n }\n\n addElementsToManager = (id, elements, ordinal) => {\n // console.log(`addElementsToManager`, { id, elements })\n this.elementsMap.set(id, elements)\n elements.forEach((el) => {\n el.on('click', e => this.handleClickElement(id))\n this.getElementsByOrdinal(ordinal).push(el)\n })\n\n const inOrdinal = Array.isArray(this.currentOrdinals) ? this.currentOrdinals.includes(ordinal) : ordinal === this.currentOrdinals\n if (inOrdinal) {\n this.elementRenderer.showElements(elements as any, ordinal)\n } else {\n this.elementRenderer.hideElements(elements as any, ordinal)\n }\n }\n\n async #createElements() {\n\n // Add some delay to mitigate react re-renders multiple times\n await delay(this.options.delayBeforeCreateElements ?? 0)\n\n /** Levels */\n const levels = await this.#dataClient.filterByType(\"level\", {\n populate: true,\n })\n\n const openings = await this.#dataClient.filterByType(\"opening\", {\n populate: true,\n })\n\n const relationships = await this.#dataClient.filterByType('relationship')\n /** Fixtures */\n const fixtures = (await this.#dataClient.filterByType(\"fixture\", { populate: true }))\n fixtures\n .forEach((fixture) => {\n const element = this.elementRenderer.createGeometry(fixture)\n if (element) {\n const _elements = Array.isArray(element) ? element : [element]\n this.addElementsToManager(fixture.id, _elements, fixture.properties.level.properties.ordinal)\n }\n })\n\n /** Units */\n const units = (await this.#dataClient.filterByType<\"unit\">(\"unit\", {\n populate: true,\n })) as UnitFeaturePopulated[]\n\n units\n .filter(\n (u) => ![\"opentobelow\", \"escalator\", \"room\"].includes(u.properties.category)\n )\n .forEach((unit) => {\n const element = this.elementRenderer.createGeometry(unit)\n if (element) {\n const _elements = Array.isArray(element) ? element : [element]\n this.addElementsToManager(unit.id, _elements, unit.properties.level.properties.ordinal)\n }\n })\n\n units\n .filter(u => u.properties.category === \"room\")\n .forEach(unit => {\n const openingRelationships = relationships.filter(r => r.properties.origin?.id === unit.id || r.properties.destination?.id === unit.id)\n const roomOpenings = compact(openingRelationships.map(rel => {\n const openingId = rel?.properties.intermediary[0].id\n return openings.find(o => o.id === openingId)\n })) as OpeningFeature[]\n \n const innerElements = this.elementRenderer.createGeometry(unit)\n const wallElements = []\n // const wallElements = this.elementRenderer.createRoomWall(unit, roomOpenings)\n if (innerElements || wallElements) {\n const _innerElements = Array.isArray(innerElements) ? innerElements : [innerElements]\n const _wallElements = Array.isArray(wallElements) ? wallElements : [wallElements]\n const _elements = [..._innerElements, ..._wallElements]\n const ordinal = unit.properties.level.properties.ordinal\n this.addElementsToManager(unit.id, _elements, ordinal)\n }\n\n })\n\n /** Kiosks */\n const kiosks = (await this.#dataClient.filterByType<\"kiosk\">(\"kiosk\", {\n populate: true,\n })) as KioskFeaturePopulated[]\n kiosks.forEach((kiosk) => {\n const element = this.elementRenderer.createGeometry(kiosk)\n if (element) {\n const _elements = Array.isArray(element) ? element : [element]\n this.addElementsToManager(kiosk.id, _elements, kiosk.properties.level.properties.ordinal)\n }\n })\n\n /**\n * Escalators\n */\n const escalators = units.filter(u => u.properties.category === 'escalator')\n for (const escalator of escalators) {\n try {\n const escalatorRelationships = relationships.filter(r => (r.properties?.intermediary || []).some(inter => inter.id === escalator.id))\n if (escalatorRelationships.length === 0) {\n throw new Error('Cannot find escalator relationship')\n }\n if (escalatorRelationships.length > 1) {\n throw new Error('Found more than one relationship')\n }\n const thisOrdinal = escalator.properties.ordinal\n const relationship = escalatorRelationships[0]\n if (!relationship.properties.origin?.id) throw new Error(`relationship (id=${relationship.id}) - origin not exists`)\n if (!relationship.properties.destination?.id) throw new Error(`relationship (id=${relationship.id}) - destination not exists`)\n\n const bothOpeningIds = [relationship.properties.origin.id, relationship.properties.destination.id]\n const bothOpenings = await Promise.all(\n bothOpeningIds.map(id => this.#dataClient.findById('opening', id, { populate: true }))\n ) as OpeningFeaturePopulated[]\n const thisLevelOpening = bothOpenings.find(opening => opening.properties.ordinal === thisOrdinal)\n const thatLevelOpening = bothOpenings.find(opening => opening.properties.ordinal !== thisOrdinal)\n const angle = 180 * (1 / Math.PI) * angleBetweenLineStrings(thisLevelOpening.geometry.coordinates, thatLevelOpening.geometry.coordinates)\n const direction = thisOrdinal < thatLevelOpening.properties.ordinal ? 'up' : 'down'\n const escalatorEntryPoint = turfCenter(thisLevelOpening).geometry.coordinates\n const element = await this.elementRenderer.createEscalator(escalator, escalatorEntryPoint, { direction, angle })\n if (element) {\n const _elements = (Array.isArray(element)) ? element : [element]\n this.addElementsToManager(escalator.id, _elements, escalator.properties.ordinal)\n }\n } catch (err) {\n console.warn(`cannot create escalator`, err.message)\n }\n }\n\n /** \n * Ground Label \n */\n const groundLabels = await this.#dataClient.filterByType(\"label\")\n for (const label of groundLabels) {\n const center = turfCenter(polygon(label.geometry.coordinates)).geometry.coordinates\n const unit = findUnitOnPoint(units, center)\n if (unit) {\n const element = this.elementRenderer.createGroundLabel(label, unit)\n if (element) {\n const _elements = (Array.isArray(element)) ? element : [element]\n this.addElementsToManager(label.id, _elements, label.properties.ordinal)\n }\n }\n }\n \n if (this.options.type === \"3D\") {\n const model3ds = await this.#dataClient.filterByType(\"model3d\")\n for (const model3d of model3ds) {\n (this.elementRenderer as Element3DRenderer).createModel3d(model3d)\n }\n }\n // const buildingElement = await this.elementRenderer.createBuilding([100.51015958563418, 13.72669948541647], 0)\n // if (buildingElement) {\n // const _elements = (Array.isArray(buildingElement)) ? buildingElement : [buildingElement]\n // this.addElementsToManager('venue', _elements, 0)\n // }\n\n // Call changeLevelByOrdinal again to show/hide elements\n this.changeLevelByOrdinal(this.currentOrdinals)\n\n this.dispatchEvent(new CustomEvent('renderermanager:elements_created'))\n\n }\n\n changeLevelByOrdinal(targetOrdinal: null | number | number[]): void {\n // if targetOrdinal = null, show all\n this.currentOrdinals = targetOrdinal\n\n if (targetOrdinal === null) {\n const baseOrdinal = 0\n for (const [ordinal, elements] of this.elementsByOrdinal) {\n this.elementRenderer.showElements(elements as any, ordinal - baseOrdinal)\n }\n\n for (const [ordinal, markers] of this.markersByOrdinal) {\n this.markerRenderer.showMarkers(markers as any, ordinal - baseOrdinal)\n }\n } else {\n // if targetOrdinal = number | number[], show target levels\n const baseOrdinal = Array.isArray(targetOrdinal) ? min(targetOrdinal) : targetOrdinal\n\n for (const [ordinal, elements] of this.elementsByOrdinal) {\n const inOrdinal = Array.isArray(targetOrdinal) ? targetOrdinal.includes(ordinal) : ordinal === targetOrdinal\n if (inOrdinal) {\n this.elementRenderer.showElements(elements as any, ordinal - baseOrdinal)\n } else {\n this.elementRenderer.hideElements(elements as any, ordinal - baseOrdinal)\n }\n }\n\n for (const [ordinal, markers] of this.markersByOrdinal) {\n const inOrdinal = Array.isArray(targetOrdinal) ? targetOrdinal.includes(ordinal) : ordinal === targetOrdinal\n if (inOrdinal) {\n this.markerRenderer.showMarkers(markers as any, ordinal - baseOrdinal)\n } else {\n this.markerRenderer.hideMarkers(markers as any, ordinal - baseOrdinal)\n }\n }\n }\n }\n\n highlightElements = (elemIds: string[], options?: HighlightElementOptions) => {\n const { reset = true } = options ?? {};\n\n if (reset) {\n this.clearHighlightElements()\n }\n\n const elements = elemIds.map(id => this.elementsMap.get(id)).flat()\n\n elements.forEach(element => {\n const controller: IHighlightController = this.elementRenderer.createHighlightController(element) \n if (controller && isFunction(controller.start)) {\n controller.start()\n this.highlightControllers.push(controller)\n }\n })\n }\n\n clearHighlightElements = () => {\n this.highlightControllers.forEach((controller) => {\n if (isFunction(controller?.clear)) controller.clear()\n })\n }\n\n /** \n * ========================================================================\n * Markers\n * ======================================================================== */\n _getMarkersByOrdinal = (ordinal: number) => {\n const exist = this.markersByOrdinal.get(ordinal)\n if (!exist) this.markersByOrdinal.set(ordinal, [])\n return this.markersByOrdinal.get(ordinal)\n }\n\n _addMarkersToManager = (id, markers, ordinal) => {\n this.markersMap.set(id, markers)\n markers.forEach((el) => {\n this._getMarkersByOrdinal(ordinal).push(el)\n })\n\n const inOrdinal = Array.isArray(this.currentOrdinals) ? this.currentOrdinals.includes(ordinal) : ordinal === this.currentOrdinals\n if (inOrdinal) {\n this.markerRenderer.showMarkers(markers, ordinal)\n } else {\n this.markerRenderer.hideMarkers(markers, ordinal)\n }\n }\n\n createMarker(type: 'text' | 'image', coordinate: Position, ordinal: number, textOrPath: string, options: AnyMarkerOptions) {\n\n const meshes = type === 'text' \n ? this.markerRenderer.createTextMarker(coordinate, textOrPath, options as TextMarkerOptions)\n : this.markerRenderer.createImageMarker(coordinate, textOrPath, options as ImageMarkerOptions)\n const markerId = `${this.markersMap.size + 1}`\n const markerMeshes = Array.isArray(meshes) ? meshes : [meshes]\n this._addMarkersToManager(markerId, markerMeshes, ordinal)\n }\n\n clearMarkers() {\n for (const [markerId, marker] of this.markersMap) {\n this.markerRenderer.removeMarker(marker as any)\n }\n }\n\n \n}\n","import * as maptalks from \"maptalks-gl\"\nimport { GeoJSONLineStringFeature, GeoJSONMultiPolygonFeature, GeoJSONPolygonFeature } from \"maptalks.three/dist/type\"\nimport * as THREE from \"three\"\nimport { BaseObject, ThreeLayer } from \"maptalks.three\"\nimport { Feature, LineString, Polygon, Position } from \"geojson\"\nimport turfBuffer from \"@turf/buffer\"\nimport { cleanCoords } from \"@turf/clean-coords\";\nimport { point, multiPoint, polygon } from \"@turf/helpers\"\nimport { polygonToLine } from \"@turf/polygon-to-line\"\nimport { nearestPointOnLine } from \"@turf/nearest-point-on-line\";\nimport { length } from \"@turf/length\"\nimport { along } from \"@turf/along\";\nimport { pointToLineDistance } from \"@turf/point-to-line-distance\";\nimport { ImdfFeature, LabelFeature, Model3dFeature, OpeningFeature, UnitFeature } from \"../../../data\"\nimport {\n Element3DRendererOptions,\n IElementRenderer,\n IHighlightController,\n MapElement,\n} from \"../types\"\nimport { GroundLabel, GroundLabelOptions } from \"./objects/GroundLabel\"\nimport { get3DRendererOption } from \"./utils/get3DRendererOption\"\nimport lineSplit from \"@turf/line-split\"\n\nexport const HEIGHT_METER = 4\nexport const MULTIORDINAL_HEIGHT_METER = 9\nexport const WALKWAY_HEIGHT = 0.5\n\nexport class Element3DRenderer\n extends EventTarget\n implements IElementRenderer\n{\n private options: Element3DRendererOptions\n private map: maptalks.Map\n private gltfLayer: maptalks.GLTFLayer\n public threeLayer: ThreeLayer\n public scene: THREE.Scene\n private lineMaterial: THREE.LineBasicMaterial\n private materialByColorMap: Map<string, THREE.Material>\n\n // Renderer is Ready\n public isReady: boolean = false\n\n constructor(map: maptalks.Map, options: Element3DRendererOptions) {\n super()\n\n this.options = options\n this.map = map\n const groupLayer = this.map.getLayer('group') as maptalks.GroupGLLayer\n this.threeLayer = groupLayer.getLayer('three') as ThreeLayer\n this.gltfLayer = groupLayer.getLayer('gltf') as maptalks.GLTFLayer\n\n this.lineMaterial = new THREE.LineBasicMaterial({ color: \"#000\" })\n \n this.render()\n }\n\n animation() {\n // layer animation support Skipping frames\n this.threeLayer._needsUpdate = !this.threeLayer._needsUpdate\n if (this.threeLayer._needsUpdate) {\n this.threeLayer.redraw()\n }\n requestAnimationFrame(this.animation)\n }\n\n /** Materials */\n getOrCreateMaterialByColor(color) {\n if (!this.materialByColorMap) this.materialByColorMap = new Map()\n\n const existingMaterial = this.materialByColorMap.get(color)\n if (existingMaterial) return existingMaterial\n\n const created = new THREE.MeshLambertMaterial({ color, transparent: true })\n created.toneMapped = false\n this.materialByColorMap.set(color, created)\n return created\n }\n\n createGeometry = (feature: ImdfFeature): MapElement | MapElement[] => {\n const {\n offset = 0,\n height: heightOptions,\n bottomHeight: bottomHeightOptions,\n color: colorOptions,\n ...options\n } = get3DRendererOption(feature.feature_type, feature.properties.category, this.options)\n\n const _this = this\n\n /** Internal createPolygon function */\n const createPolygon = (geometry: Polygon, feature: GeoJSONPolygonFeature|GeoJSONMultiPolygonFeature) => {\n try {\n const [outerRing, ...innerRings] = geometry.coordinates\n const offsetFeature =\n offset !== 0\n ? turfBuffer(geometry, offset, { units: \"meters\" }) as GeoJSONPolygonFeature\n : feature\n const color =\n feature.properties.style.polygonFill ?? colorOptions ?? \"#ffffff\"\n if (color === \"transparent\") return\n const material = this.getOrCreateMaterialByColor(color)\n const altitude = 0\n const height = feature.properties.height ?? heightOptions ?? HEIGHT_METER\n const bottomHeight = feature.properties.bottomHeight ?? bottomHeightOptions ?? 0\n const extrudedPolygon = this.threeLayer.toExtrudePolygon(\n offsetFeature,\n { asynchronous: true, ...options, height, bottomHeight, altitude },\n material\n )\n\n // Create extra lines for visual clarity\n const topLineStrings = [\n new maptalks.LineString(outerRing),\n ...innerRings.map(innerRing => new maptalks.LineString(innerRing))\n ]\n const topLines = this.threeLayer.toLines(\n topLineStrings,\n { altitude, bottomHeight: bottomHeight + height + 0.001, interactive: false },\n this.lineMaterial\n )\n\n const bottomLineStrings = [\n new maptalks.LineString(outerRing),\n ...innerRings.map(innerRing => new maptalks.LineString(innerRing))\n ]\n const bottomLines = this.threeLayer.toLines(\n bottomLineStrings,\n { altitude: altitude, bottomHeight, interactive: false },\n this.lineMaterial\n )\n return [extrudedPolygon, topLines, bottomLines]\n } catch (err) {\n return []\n }\n }\n\n const createLineString = (geometry: LineString, feature: GeoJSONLineStringFeature) => {\n try {\n const color =\n feature.properties.style.polygonFill ?? colorOptions ?? \"#000000\"\n const material = this.getOrCreateMaterialByColor(color)\n const extrudedLine = this.threeLayer.toExtrudeLine(\n new maptalks.LineString(geometry.coordinates),\n { height: heightOptions, ...options },\n material\n )\n return [extrudedLine]\n } catch (err) {\n return []\n }\n }\n\n try {\n switch (feature.geometry.type) {\n case \"MultiPolygon\": {\n const { coordinates } = feature.geometry\n if (!coordinates) return []\n\n const multiMeshes = coordinates.flatMap(polygonCoordinates => {\n const meshes = createPolygon({ type: 'Polygon', coordinates: polygonCoordinates }, feature as GeoJSONMultiPolygonFeature)\n this.threeLayer.addMesh(meshes)\n return meshes\n })\n return multiMeshes\n }\n case \"Polygon\": {\n const { coordinates } = feature.geometry\n if (!coordinates) return []\n\n const meshes = createPolygon(feature.geometry, feature as GeoJSONPolygonFeature)\n this.threeLayer.addMesh(meshes)\n return meshes\n }\n\n case \"LineString\": {\n const { coordinates } = feature.geometry\n if (!coordinates) return []\n\n const meshes = createLineString(feature.geometry, feature as GeoJSONLineStringFeature)\n this.threeLayer.addMesh(meshes)\n return meshes\n }\n }\n } catch (err) {\n console.log(`error createGeometry`, err, { feature, options })\n }\n }\n\n createRoomWall(unit: UnitFeature, openings: OpeningFeature[] = []): MapElement | MapElement[] | null {\n\n const polygons = unit.geometry.type === 'Polygon' ? [unit.geometry.coordinates] : unit.geometry.coordinates\n return polygons.map(plg => {\n return plg.map(ring => {\n const roomWall = cleanCoords(polygonToLine(polygon([ring]))) as Feature<LineString>\n if (openings.length === 0) {\n const color = \"#ababab\"\n const material = this.getOrCreateMaterialByColor(color)\n const extrudedWall = this.threeLayer.toExtrudeLine(\n new maptalks.LineString(roomWall.geometry.coordinates),\n { height: 4, width: 1 },\n material\n )\n return extrudedWall\n }\n \n // Split ring with each opening\n let openingPoints = []\n openings.forEach(opening => {\n const doorCoords = opening?.geometry?.coordinates;\n \n const p0 = point(doorCoords[0]);\n const p1 = point(doorCoords[doorCoords.length - 1]);\n\n // 3) snap door endpoints to boundary\n const s0 = nearestPointOnLine(roomWall, p0, { units: \"meters\" });\n const s1 = nearestPointOnLine(roomWall, p1, { units: \"meters\" });\n\n // Optional sanity check: ensure the door is actually on the boundary (within tolerance)\n const d0 = s0.properties.dist as number;\n const d1 = s1.properties.dist as number;\n if (d0 > 1 || d1 > 1) {\n // Door endpoints are not on (or near) the roomWall. Increase tolerance or fix input.\");\n } else {\n openingPoints = openingPoints.concat([s0.geometry.coordinates, s1.geometry.coordinates])\n }\n })\n \n try {\n const split = lineSplit(roomWall, multiPoint(openingPoints))\n /** \n * Remove the segment that corresponds to the door:\n * use midpoint distance-to-door test (robust for angled doors)\n */\n \n const wallsOnly = split.features.filter((seg) => {\n const mid = along(seg, length(seg, { units: \"meters\" }) / 2, { units: \"meters\" });\n for (const opening of openings) {\n const dist = pointToLineDistance(mid, opening, { units: \"meters\" });\n if (dist < 0.05) return false\n }\n return true\n });\n\n const wallMeshes = wallsOnly.map((feature, i) => {\n const color = \"#ababab\"\n const material = this.getOrCreateMaterialByColor(color)\n \n const extrudedLine = this.threeLayer.toExtrudeLine(\n new maptalks.LineString(feature.geometry.coordinates),\n { height: 3, width: 0.4, id: unit.id },\n material\n )\n extrudedLine.getObject3d().userData = {\n unitId: unit.id,\n coords: feature.geometry.coordinates, \n }\n return extrudedLine\n }).flat()\n\n this.threeLayer.addMesh(wallMeshes)\n return wallMeshes\n } catch (e) {\n console.log(e.message, { unit, roomWall })\n return []\n }\n }).flat()\n }).flat()\n }\n\n async createEscalator(\n f: ImdfFeature,\n coordinate: Position,\n options: { angle: number; direction: 'up' | 'down' },\n ): Promise<MapElement | MapElement[] | null> {\n\n const model = {\n url: 'https://cdn.venue.in.th/static/glb/escalator.glb',\n size: 4.4, \n }\n \n const { direction: dir, angle } = options;\n const rotationZ = (dir === \"up\") ? (180 + angle) : angle\n var escalatorMarker = new maptalks.GLTFMarker(coordinate, {\n symbol: {\n url: model.url,\n rotationZ,\n translationX: dir === \"up\" ? 0 : model.size * Math.cos(Math.PI * rotationZ / 180),\n translationY: dir === \"up\" ? 0 : model.size * Math.sin(Math.PI * rotationZ / 180),\n translationZ: dir === \"up\" ? -0.05 * model.size : -0.5 * model.size,\n },\n });\n\n escalatorMarker.addTo(this.gltfLayer);\n return escalatorMarker\n }\n\n // Note: Move to another renderer and keep this file on Geometry only?\n createGroundLabel(f: LabelFeature, unit: UnitFeature): MapElement | MapElement[] | null {\n const text = f.properties.name\n const bound = f.geometry.coordinates[0]\n\n const { height: unitHeight } = get3DRendererOption('unit', unit.properties.category, this.options)\n const options: GroundLabelOptions = { bottomHeight: unitHeight + 0.005 }\n\n const groundLabel = new GroundLabel(bound, text, options, this.threeLayer)\n this.threeLayer.addMesh(groundLabel)\n return groundLabel\n }\n\n async createModel3d(f: Model3dFeature): Promise<MapElement | MapElement[] | null> {\n const marker = new maptalks.GLTFMarker(f.properties.center, {\n symbol: {\n url: f.properties.model,\n },\n });\n\n marker.addTo(this.gltfLayer);\n return marker\n }\n\n async createBuilding(coordinate: Position, ordinal: number): Promise<MapElement | MapElement[] | null> {\n // const marker = new maptalks.GLTFMarker(coordinate, {\n // symbol: {\n // url: 'https://cdn.venue.in.th/static/glb/iconsiam.glb',\n // rotationZ: 4,\n // translationY: -10,\n // scaleX: 49,\n // scaleY: 49,\n // scaleZ: 49,\n // },\n // });\n // marker.on(\"zoom\", (e) => {\n // console.log(`zoom`, e)\n // })\n // marker.addTo(this.gltfLayer);\n // return marker\n return Promise.resolve(null)\n }\n \n createElement(f: ImdfFeature): MapElement[] | null {\n switch (f.feature_type) {\n default:\n return null\n }\n }\n\n showElements(elements: MapElement[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n element.setAltitude(ordinalDiff * MULTIORDINAL_HEIGHT_METER)\n element.show()\n })\n }\n\n hideElements(elements: MapElement[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n try { \n element.hide()\n } catch (err) {\n console.log(`cannot hide`, err, element)\n }\n })\n }\n\n createHighlightController(element: MapElement): IHighlightController {\n if (!(element instanceof BaseObject)) {\n return null; // not my responsibility\n }\n switch (element.type) {\n case 'ExtrudePolygon':\n case 'ExtrudeLine': {\n const mesh = element.getObject3d() as THREE.Mesh\n const originalMaterial = mesh.material;\n const highlightMaterial = this.getOrCreateMaterialByColor('#ff0000');\n\n return {\n start: () => {\n mesh.material = highlightMaterial;\n },\n clear: () => {\n mesh.material = originalMaterial;\n },\n };\n }\n\n default: {\n return {\n start() {},\n clear() {}\n }\n }\n }\n \n }\n\n render() {\n this.threeLayer._needsUpdate = !this.threeLayer._needsUpdate\n if (this.threeLayer._needsUpdate) {\n // @ts-ignore\n this.threeLayer.redraw()\n }\n\n // this.#animationsToRun.forEach(({ callback }) => callback(this))\n\n //update TWEEN.js animaton\n // TWEEN.update()\n\n requestAnimationFrame(this.render.bind(this))\n }\n}\n\n\n/**\n * Legacy threejs way\n * async loadModel3d(model3d: LoadModel3dParameters) {\n const loader = new GLTFLoader()\n loader.setDRACOLoader(this.dracoLoader)\n\n const { url, properties: modelProperties } = model3d\n const gltf = await loader.loadAsync(url)\n \n const model = gltf.scene\n // จัดขนาด + scale ที่เหมาะสม\n model.rotation.x = modelProperties.rotation.x\n model.rotation.y = modelProperties.rotation.y\n\n model.position.x = modelProperties.position.x\n model.position.y = modelProperties.position.y\n model.position.z = modelProperties.position.z\n \n const scale = modelProperties.scale\n model.scale.set(scale, scale, scale)\n return model\n }\n\n * const model = await this.loadModel3d({\n url: 'https://dashboard.situm.com/uploads/3dmodels/demoaccount/new_escalator.glb',\n properties: {\n rotation: {\n x: 0.5 * Math.PI, // Rotate the model up (new_escalator.glb)\n y: 0,\n z: 0,\n },\n position: { x: 0, y: 0, z: 0 },\n scale: 0.01,\n },\n });\n\n // map heading\n model.rotation.y += (dir === \"up\") ? Math.PI + angle : angle;\n\n const box = new THREE.Box3().setFromObject(model);\n const pivotPoint =\n dir === 'up'\n ? new THREE.Vector3(0, 0, 0)\n : new THREE.Vector3(\n 1 * (box.min.x + box.max.x),\n 1 * (box.min.y + box.max.y),\n 0.60 * box.max.z,\n );\n\n const pivot = new THREE.Group();\n pivot.add(model);\n\n model.position.sub(pivotPoint);\n model.updateMatrixWorld(true);\n\n const altitude = f.properties.ordinal * HEIGHT_METER;\n\n const baseObjectModel = this.threeLayer.toModel(pivot, {\n coordinate,\n altitude,\n });\n\n this.threeLayer.addMesh(baseObjectModel);\n return baseObjectModel;\n */","import * as maptalks from \"maptalks-gl\"\nimport { BaseObject, ThreeLayer } from \"maptalks.three\"\nimport {\n Texture,\n Mesh,\n MeshPhongMaterial,\n PlaneGeometry,\n Material,\n} from \"three\"\nimport { largestRect } from \"d3plus-shape\"\nimport { max, merge, isNumber, isArray, range } from \"lodash\"\nimport { Position } from \"geojson\"\n\nexport type GroundLabelOptions = {\n bottomHeight?: number\n altitude?: number\n fontSize?: number\n fontWeight?: number\n fillStyle?: string\n textAlign?: string\n fontFamily?: string\n textBaseline?: string\n strokeStyle?: string\n lineWidth?: number\n lineHeight?: number\n margin?: number\n angle?: number[]\n scaleMin?: number\n scaleStep?: number\n maxFontScale?: number\n offsetX?: number\n offsetY?: number\n}\n\nconst OPTIONS = {\n // Allowing click through and prevent interaction\n interactive: false,\n altitude: 0,\n}\n\nconst defaultFlatLabelOptions: GroundLabelOptions = {\n fontSize: 14,\n fontFamily: \"Manrope\",\n fontWeight: 600,\n margin: 0,\n scaleMin: 0.5,\n lineHeight: 1.05,\n scaleStep: 0.05,\n textAlign: \"center\",\n textBaseline: \"middle\",\n fillStyle: \"#000\",\n}\n\nconst defaultRectAngleToCalc = range(-90, 92, 2)\n\nexport const getMaterial = (text, flatLabelOptions) => {\n const options = merge({}, defaultFlatLabelOptions, flatLabelOptions)\n\n const {\n fontSize: initialFontSize,\n fontFamily,\n fontWeight,\n margin,\n scaleMin,\n scaleStep,\n fillStyle,\n lineHeight,\n textAlign,\n strokeStyle,\n lineWidth,\n textBaseline,\n } = options\n\n const pixelMultiplier = 4\n const SIZE = 100 * pixelMultiplier\n const fontSize = initialFontSize * (pixelMultiplier * 1.25)\n const canvas = document.createElement(\"canvas\")\n canvas.width = canvas.height = SIZE\n const ctx = canvas.getContext(\"2d\")\n\n ctx.font = `${fontWeight} ${fontSize}px \"${fontFamily}\", Arial`\n ctx.textAlign = textAlign\n ctx.textBaseline = textBaseline\n ctx.fillStyle = fillStyle\n ctx.strokeStyle = strokeStyle\n ctx.lineWidth = lineWidth\n\n // Function to wrap text automatically\n const wrapText = (ctx, text, maxWidth) => {\n const words = text.trim().split(/\\s+/)\n if (words.length <= 1) return [text]\n\n const lines = []\n const MAX_LINES = 3\n let currentLine = words[0]\n\n for (let i = 1; i < words.length; i++) {\n const lineToMeasure = currentLine + \" \" + words[i]\n if (ctx.measureText(lineToMeasure).width > maxWidth) {\n lines.push(currentLine)\n currentLine = words[i]\n } else {\n currentLine = lineToMeasure\n }\n }\n lines.push(currentLine)\n return lines.slice(0, MAX_LINES) // Limit to 3 lines\n }\n\n /** Check if text contains manual line breaks */\n const hasManualBreaks = text.includes(\"\\n\")\n let texts\n\n if (hasManualBreaks) {\n // Use manual line breaks\n texts = text.split(/\\n/g)\n } else {\n // Auto-wrap text\n const maxWidth = SIZE - 2 * margin\n texts = wrapText(ctx, text, maxWidth)\n }\n\n /** Automatically recalculate font size to fit the bound */\n let textWidth: number = max(texts.map((text) => ctx.measureText(text).width))\n let scale = 1\n while (scale > 0 && textWidth + 2 * margin > SIZE) {\n scale -= scaleStep\n ctx.font = `${fontWeight} ${scale * fontSize}px \"${fontFamily}\", Arial`\n textWidth = max(texts.map((text) => ctx.measureText(text).width))\n }\n\n // If the text is larger than scaleMin, then render it\n const center = { x: 0.5 * SIZE, y: 0.5 * SIZE }\n\n if (scale > scaleMin) {\n const totalHeight = texts.length * (fontSize * scale * lineHeight)\n const startY =\n center.y - totalHeight / 2 + fontSize * scale * lineHeight * 0.5 // Adjust startY when offset multi text line\n\n texts.forEach((text, index) => {\n const yOffset = startY + index * (fontSize * scale * lineHeight)\n if (strokeStyle && lineWidth) {\n ctx.strokeText(text, center.x, yOffset) // Draw outlined text\n }\n ctx.fillText(text, center.x, yOffset)\n })\n }\n\n const texture = new Texture(canvas)\n texture.needsUpdate = true\n\n const material = new MeshPhongMaterial({\n map: texture,\n transparent: true,\n // @ref: https://threejs.org/docs/#api/en/materials/Material.alphaTest\n alphaTest: 0.3,\n })\n return material\n}\n\nexport class GroundLabel extends BaseObject {\n\n declare options: GroundLabelOptions;\n \n #angle = 0\n #bearing = 0\n #text = \"\"\n #offsetX = 0\n #offsetY = 0\n #originalPosition = null\n #layer: ThreeLayer = null\n\n constructor(bound: Position[], text: string, options: GroundLabelOptions, layer: ThreeLayer) {\n\n options = maptalks.Util.extend({}, OPTIONS, options, {\n layer,\n coordinate: bound,\n })\n\n const {\n altitude = 0,\n bottomHeight = 0,\n fontSize,\n fillStyle,\n textAlign,\n fontFamily,\n textBaseline,\n strokeStyle,\n lineWidth,\n angle = defaultRectAngleToCalc,\n maxFontScale,\n offsetX = 0,\n offsetY = 0,\n ...properties\n } = options\n\n super()\n this._initOptions(options)\n this.properties = properties\n\n this.#offsetX = offsetX\n this.#offsetY = offsetY\n this.#layer = layer\n\n const material = getMaterial(text, {\n fillStyle,\n fontSize,\n textAlign,\n textBaseline,\n fontFamily,\n strokeStyle,\n lineWidth,\n })\n\n // Convert angle to array if it's a single number\n const rectAngles = isArray(angle) ? angle : [angle]\n\n material.needsUpdate = true\n\n const rect = largestRect(bound, {\n cache: true,\n /**\n * Black magic here:\n * For some reason if we allow angle -90 or 90, some polygon will use that angle even if it's wrong angle to use.\n * So we remove -90 and 90 from choices, and use -85 & 85 instead.\n */\n angle: rectAngles,\n })\n\n const { cx, cy, width, angle: calculatedAngle } = rect\n this.#text = text\n this.#angle = calculatedAngle // Always use calculated angle from largestRect\n\n const geometry = new PlaneGeometry(1, 1)\n this._createMesh(geometry, material)\n\n // set object3d position\n const z = layer.altitudeToVector3(altitude + bottomHeight, altitude + bottomHeight).x\n const basePosition = layer.coordinateToVector3([cx, cy], z)\n\n this.#originalPosition = basePosition.clone()\n const finalPosition = this.#calculateFinalPosition(basePosition)\n\n const scale = width / 0.0006456122659\n // check if it has maxFontScaleLimit from option use maxFontScale\n const finalScale =\n maxFontScale && scale > maxFontScale ? maxFontScale : scale\n this.getObject3d().scale.set(finalScale, finalScale, finalScale)\n this.getObject3d().position.copy(finalPosition)\n this.getObject3d().rotation.z = (Math.PI / 180) * this.#angle\n }\n\n #calculateFinalPosition(basePosition) {\n if (this.#offsetX === 0 && this.#offsetY === 0) {\n return basePosition\n }\n\n const offsetCoordinate = [this.#offsetX, this.#offsetY]\n\n const z = this.#layer.altitudeToVector3(0, 0).x\n const offsetVector = this.#layer.coordinateToVector3(offsetCoordinate, z)\n const zeroVector = this.#layer.coordinateToVector3([0, 0], z)\n\n const worldOffsetX = offsetVector.x - zeroVector.x\n const worldOffsetY = offsetVector.y - zeroVector.y\n\n return {\n x: basePosition.x + worldOffsetX,\n y: basePosition.y + worldOffsetY,\n z: basePosition.z,\n }\n }\n\n #updatePosition() {\n if (this.#originalPosition && this.#layer) {\n const finalPosition = this.#calculateFinalPosition(this.#originalPosition)\n this.getObject3d().position.copy(finalPosition)\n }\n }\n\n set bearing(value) {\n this.#bearing = value\n const degree = this.#angle + this.#bearing\n const angle = degree > 90 || degree < -90 ? this.#angle + 180 : this.#angle\n this.getObject3d().rotation.z = (Math.PI / 180) * angle\n }\n\n get angle() {\n return this.#angle\n }\n\n get currentAngle() {\n return this.#angle\n }\n\n get text() {\n return this.#text\n }\n\n get offsetX() {\n return this.#offsetX\n }\n\n get offsetY() {\n return this.#offsetY\n }\n\n get offset() {\n return { x: this.#offsetX, y: this.#offsetY }\n }\n\n set offsetX(value) {\n if (isNumber(value)) {\n this.#offsetX = value\n this.#updatePosition()\n }\n }\n\n set offsetY(value) {\n if (isNumber(value)) {\n this.#offsetY = value\n this.#updatePosition()\n }\n }\n\n set angle(newAngle) {\n if (isNumber(newAngle)) {\n this.#angle = newAngle\n this.getObject3d().rotation.z = (Math.PI / 180) * this.#angle\n }\n }\n\n setOffset(offsetX, offsetY) {\n if (isNumber(offsetX) && isNumber(offsetY)) {\n this.#offsetX = offsetX\n this.#offsetY = offsetY\n this.#updatePosition()\n }\n }\n\n addOffset(deltaX, deltaY) {\n if (isNumber(deltaX) && isNumber(deltaY)) {\n this.#offsetX += deltaX\n this.#offsetY += deltaY\n this.#updatePosition()\n }\n }\n\n resetOffset() {\n this.#offsetX = 0\n this.#offsetY = 0\n this.#updatePosition()\n }\n\n moveToPosition(targetX, targetY) {\n if (this.#originalPosition && this.#layer) {\n const currentCenter = this.#layer.vector3ToCoordinate(\n this.#originalPosition\n )\n this.#offsetX = targetX - currentCenter.x\n this.#offsetY = targetY - currentCenter.y\n this.#updatePosition()\n }\n }\n\n updateText(newText, options: Record<string, unknown> = {}) {\n this.#text = newText\n\n const materialOptions = {\n fillStyle: options.fillStyle || this.properties.fillStyle,\n fontSize: options.fontSize || this.properties.fontSize,\n textAlign: options.textAlign || this.properties.textAlign,\n textBaseline: options.textBaseline || this.properties.textBaseline,\n fontFamily: options.fontFamily || this.properties.fontFamily,\n strokeStyle: options.strokeStyle || this.properties.strokeStyle,\n lineWidth: options.lineWidth || this.properties.lineWidth,\n }\n\n const newMaterial = getMaterial(newText, materialOptions) as Material\n ;(this.getObject3d() as Mesh).material = newMaterial\n newMaterial.needsUpdate = true\n }\n\n _animation() {\n // Flip text, if needed\n const map = this.getMap();\n if (!map) return;\n\n const bearing = map.getBearing();\n this.bearing = bearing\n }\n\n // Add bottomHeight to altitude as final altitude position\n setAltitude(altitude: number) {\n const bottomHeight = this.options.bottomHeight ?? 0\n return super.setAltitude(altitude + bottomHeight)\n }\n}\n","import { Element3DRendererOptions } from \"../types\";\n\n/**\n * minZoom, maxZoom = สำหรับระบุ zoom ที่จะให้ปรากฎตัว\n */\n\nexport const element3DRendererOptions: Element3DRendererOptions = {\n unit: {\n default: { color: \"#ffffff\", height: 0.2 },\n byCategory: {\n walkway: { color: \"#cccccc\", height: 0.1 },\n terrace: { color: \"#cccccc\", height: 0.1 },\n unenclosedarea: { color: \"#cccccc\", height: 0.2 },\n nonpublic: { color: \"#999999\", height: 0.3 },\n escalator: { height: 0.2 },\n parking: { color: \"#999999\", height: 0.1 },\n room: { color: \"#ffffff\", height: 0.5, bottomHeight: 0.12 }\n },\n },\n kiosk: {\n default: { color: \"#666666\", height: 0.6, bottomHeight: 0.12 },\n },\n fixture: {\n default: { color: \"#ffffff\", height: 0.5 },\n byCategory: {\n water: { color: \"#ACD7EC\", height: 0.1 },\n vegetation: { color: \"#91C499\", height: 0.5 },\n wall: { color: \"#787878\", topColor: '#ffffff', height: 4.2, width: 1 }\n }\n }\n}","import {\n CreateExtrudeLineStringOptionType,\n CreateExtrudePolygonOptionType,\n Element3DRendererOptions,\n} from '../../types'\nimport { element3DRendererOptions as defaultOptions } from '../element3DRendererOptions'\n\n\nconst DEFAULT_POLYGON_OPTION: CreateExtrudePolygonOptionType = {\n color: \"#FFFFFF\",\n offset: 0,\n altitude: 0,\n}\n\nexport const get3DRendererOption = (\n featureType: string,\n category: string,\n options: Element3DRendererOptions = {}\n): CreateExtrudePolygonOptionType | CreateExtrudeLineStringOptionType => {\n try {\n const option = options[featureType] ?? defaultOptions[featureType]\n return (\n (category && option.byCategory?.[category]) ??\n option?.default ??\n DEFAULT_POLYGON_OPTION\n )\n } catch (err) {\n console.log(err.message, { options, featureType, category })\n }\n}\n","import * as maptalks from \"maptalks\"\nimport { Element2DRendererOptions, IElementRenderer, IHighlightController, MapElement } from \"../types\"\nimport { ImdfFeature, LabelFeature, LevelFeature, OpeningFeature, UnitFeature } from \"../../../data\"\nimport { element2DRendererOptions as defaultOptions } from \"./element2DRendererOptions\"\nimport { PolygonOptionsType } from \"maptalks/dist/geometry/Polygon\"\nimport { Position } from \"geojson\"\n\nconst DEFAULT_POLYGON_OPTION: PolygonOptionsType = {\n zIndex: 0,\n symbol: {\n polygonFill: \"#FFFFFF\",\n lineColor: \"#34495E\",\n polygonOpacity: 1,\n lineWidth: 2,\n },\n}\n\nconst ORDINAL_HEIGHT = 4\nconst MULTIORDINAL_HEIGHT_METER = 10\n\nconst getAltitude = (f: LevelFeature) =>\n Math.max(0, f.properties.ordinal * ORDINAL_HEIGHT || 0)\n\nconst getGeometryProperties = (feature: ImdfFeature) => ({\n // Core\n type: \"Feature\",\n id: feature.id,\n geometry: feature.geometry,\n properties: feature.properties,\n // Extra\n feature_type: feature.feature_type,\n category: feature.properties.category,\n name: feature.properties.name?.en,\n})\n\nconst getGeometryOption = (\n feature: ImdfFeature,\n options: Element2DRendererOptions\n): PolygonOptionsType => {\n try {\n const option = options[feature.feature_type] ?? defaultOptions[feature.feature_type]\n const category = feature.properties.category\n return (\n (category && option.byCategory?.[category]) ??\n option?.default ??\n DEFAULT_POLYGON_OPTION\n )\n } catch (err) {\n console.log(err.message, { options, feature })\n }\n}\n\nexport class Element2DRenderer\n extends EventTarget\n implements IElementRenderer\n{\n public isReady: boolean = false\n\n private options: Element2DRendererOptions\n private map: maptalks.Map\n private elementLayer: maptalks.VectorLayer\n private markerLayer: maptalks.VectorLayer\n\n constructor(map: maptalks.Map, options: Element2DRendererOptions) {\n super()\n this.options = options\n this.map = map\n\n // Create Layer for elements\n this.elementLayer = new maptalks.VectorLayer(\"elements\")\n this.elementLayer.addTo(this.map)\n\n this.markerLayer = new maptalks.VectorLayer(\"markers\")\n this.markerLayer.addTo(this.map)\n\n // Dispatch ready event, to let manager know we're ready to start\n this.isReady = true\n }\n\n createGeometry = (imdfFeature: ImdfFeature): MapElement => {\n // Create Element (Geometry)\n const feature = getGeometryProperties(imdfFeature)\n const { symbol, ...options } = getGeometryOption(imdfFeature, this.options)\n const altitude = feature.properties.ordinal * 10\n const geometry = maptalks.Geometry.fromJSON({\n feature,\n symbol,\n options: {\n ...options,\n zIndex: altitude,\n properties: { altitude },\n },\n })\n\n // Add to layer, and return\n if (Array.isArray(geometry)) {\n geometry.forEach((g) => g.addTo(this.elementLayer))\n return new maptalks.GeometryCollection(geometry)\n } else {\n geometry.addTo(this.elementLayer)\n return geometry\n }\n }\n\n createRoomWall(unit: UnitFeature, openings: OpeningFeature[]): MapElement | MapElement[] | null {\n return null\n }\n\n async createEscalator(f: ImdfFeature, coordinates: Position): Promise<MapElement | null> {\n return Promise.resolve(null)\n }\n\n createGroundLabel(f: LabelFeature, unit: UnitFeature): MapElement | MapElement[] | null {\n const text = f.properties.name\n const bound = f.geometry.coordinates[0]\n return null\n }\n\n async createBuilding(coordinate: Position, ordinal: number): Promise<MapElement | null> {\n return Promise.resolve(null)\n }\n\n createElement = (imdfFeature: ImdfFeature): MapElement | null => {\n switch (imdfFeature.feature_type) {\n default:\n return null\n }\n }\n\n showElements(elements: MapElement[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n element.setAltitude(ordinalDiff * MULTIORDINAL_HEIGHT_METER)\n element.show()\n })\n }\n hideElements(elements: MapElement[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n element.hide()\n })\n }\n\n createHighlightController(element: MapElement): IHighlightController {\n if (!(element instanceof maptalks.Geometry)) return null;\n return {\n start() {},\n clear() {}\n }\n }\n \n \n}\n","import { Element2DRendererOptions } from \"../types\";\n\nexport const element2DRendererOptions: Element2DRendererOptions = {\n unit: { \n default: { symbol: { polygonFill: '#cccccc' } },\n byCategory: {\n room: { symbol: { polygonFill: '#fff' } },\n walkway: { symbol: { polygonFill: \"#efefef\", lineColor: \"#dadada\", lineWidth: 2 } },\n terrace: { symbol: { polygonFill: \"#efefef\" } },\n unenclosedarea: { symbol: { polygonFill: \"#fff\" } },\n nonpublic: { symbol: { polygonFill: \"#999999\" }},\n }\n },\n kiosk: { \n default: {},\n },\n fixture: {\n default: { symbol: { polygonFill: \"#ffffff\" } },\n byCategory: {\n water: { symbol: { polygonFill: \"#ACD7EC\" } },\n vegetation: { symbol: { polygonFill: \"#91C499\" } }\n }\n }\n}\n","import * as maptalks from \"maptalks\"\nimport { IMarkerRenderer } from \"../types\"\nimport { Position } from \"geojson\"\n\nexport class Marker2DRenderer\n extends EventTarget\n implements IMarkerRenderer<maptalks.ui.UIMarker>\n{\n public isReady: boolean = false\n\n private map: maptalks.Map\n private markerLayer: maptalks.VectorLayer\n\n constructor(map: maptalks.Map) {\n super()\n this.map = map\n }\n\n createMarker = (\n coordinates: Position,\n ordinal: number,\n content: string\n ): maptalks.ui.UIMarker => {\n const marker = new maptalks.ui.UIMarker(coordinates, {\n content,\n collision: true,\n collisionFadeIn: true,\n altitude: 0,\n })\n marker.addTo(this.map)\n return marker\n }\n \n createTextMarker = (\n position: Position,\n label: string,\n options?: any\n ): maptalks.ui.UIMarker | null => {\n return null\n }\n\n createImageMarker = (\n position: Position,\n src: string,\n options?: any\n ): maptalks.ui.UIMarker | null => {\n return null\n }\n\n removeMarker = (marker: maptalks.ui.UIMarker) => {\n marker.remove()\n }\n\n showMarkers(elements: maptalks.ui.UIMarker[], ordinalDiff: number = 0) {}\n hideMarkers(elements: maptalks.ui.UIMarker[], ordinalDiff: number = 0) {}\n}","import * as maptalks from \"maptalks-gl\"\nimport * as THREE from \"three\"\nimport { IMarkerRenderer } from \"../types\"\nimport { BaseObject, ThreeLayer } from \"maptalks.three\"\nimport { Position } from \"geojson\"\n// import { createSpriteMaterialByLabelSymbol } from \"../utils/svg2material\"\nimport { TextMarkerOptions, TextSpriteMarker } from \"./objects/TextSpriteMarker\"\nimport { BarOptionType, BaseObjectOptionType } from \"maptalks.three/dist/type\"\n\nexport const HEIGHT_METER = 4\nexport const MULTIORDINAL_HEIGHT_METER = 9\n\nexport type ImageMarkerOptions = BaseObjectOptionType & {\n src: string\n bottomHeight?: number\n leg?: Omit<BarOptionType, 'height'> & {\n color: string\n }\n}\n\nexport type AnyMarkerOptions = TextMarkerOptions | ImageMarkerOptions\n\nexport class Marker3DRenderer\n extends EventTarget\n implements IMarkerRenderer<BaseObject>\n{\n public isReady: boolean = false\n\n private threeLayer: ThreeLayer\n\n private map: maptalks.Map \n\n constructor(map: maptalks.Map, options: any, layer: ThreeLayer) {\n super()\n this.map = map\n this.threeLayer = layer\n }\n\n createPointMaterialFromSvg(svgPath: string, size: number = 40) {\n return new THREE.PointsMaterial({\n size,\n sizeAttenuation: false, // Always same size in screen pixels (Screen pixel)\n // color: fillStyle, \n alphaTest: 0.5,\n // vertexColors: THREE.VertexColors,\n // color: 0xffffff,\n transparent: true,\n blending: THREE.NormalBlending,\n depthTest: true, // POI is hidden behind building\n depthWrite: true,\n map: new THREE.TextureLoader().load(svgPath)\n });\n }\n \n\n createTextMarker = (\n position: Position,\n label: string,\n options?: TextMarkerOptions\n ): BaseObject|BaseObject[] => {\n const combinedOptions = {\n altitude: 0,\n text: label,\n ...(options ?? {})\n }\n const [lng, lat] = position\n const marker = new TextSpriteMarker(new maptalks.Coordinate(lng, lat), combinedOptions, this.threeLayer)\n this.threeLayer.addMesh([marker])\n return marker\n } \n\n createImageMarker = (position: Position, src: string, options?: ImageMarkerOptions): BaseObject|BaseObject[] => {\n const [lng, lat] = position\n let meshes = []\n\n // Vertical Distance from floor\n const height = options.height ?? 0\n const { leg, ...markerOptions } = options\n const { color: legColor = '#000000', ...legOptions } = leg ?? {}\n const material = this.createPointMaterialFromSvg(src, 40)\n const marker = this.threeLayer.toPoint(new maptalks.Coordinate(lng, lat), { height, ...markerOptions }, material);\n marker.getObject3d().renderOrder = 10;\n\n meshes.push(marker)\n if (options.leg) {\n const legMaterial = new THREE.MeshLambertMaterial({ color: legColor, transparent: true })\n const leg = this.threeLayer.toBar(new maptalks.Coordinate(lng, lat), { ...legOptions, height }, legMaterial)\n // Hide leg behind Image Marker\n const legObj = leg.getObject3d();\n legObj.traverse((o: any) => {\n if (o.isMesh && o.material) {\n o.material.depthWrite = false; // key\n o.material.depthTest = true; // keep\n o.renderOrder = 0;\n }\n });\n meshes = [leg, ...meshes]\n }\n \n this.threeLayer.addMesh(meshes)\n return meshes\n }\n\n removeMarker = (marker: BaseObject) => {\n marker.remove()\n }\n\n showMarkers(elements: BaseObject[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n // element.setAltitude(ordinalDiff * MULTIORDINAL_HEIGHT_METER)\n element.show()\n })\n }\n\n hideMarkers(elements: BaseObject[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n try { \n element.hide()\n } catch (err) {\n console.log(`cannot hide`, err, element)\n }\n })\n }\n\n /** Marker */\n // getOrCreateIconMaterial(key) {\n // if (!this.materialByKey) this.materialByKey = new Map()\n\n // const existingMaterial = this.materialByKey.get(key)\n // if (existingMaterial) return existingMaterial\n\n // // Create new\n // const baseSymbol: maptalks.Path = {\n // markerType: \"path\",\n // markerPath: [\n // {\n // path: \"M20.775 1.2H1.225V20.35H8.215L11.3 22.8L14.385 20.35H20.775V1.2Z\",\n // fill: \"#ff0000\",\n // },\n // ],\n // markerPathWidth: 24,\n // markerPathHeight: 24\n // }\n\n // const markerSymbol: maptalks.PathMarkerSymbol = {\n // markerType: \"path\",\n // markerPath: [],\n // // TODO: Get Path by featureType.category\n // // markerPath: [{ fill: \"#FFFFFF\", path: \"M 19 3 H 5 c -1.1 0 -2 0.9 -2 2 v 14 c 0 1.1 0.9 2 2 2 h 14 c 1.1 0 2 -0.9 2 -2 V 5 c 0 -1.1 -0.9 -2 -2 -2 Z m -2 6 h -1.7 l -5 9 H 7 c -0.83 0 -1.5 -0.67 -1.5 -1.5 S 6.17 15 7 15 h 1.7 l 5 -9 H 17 c 0.83 0 1.5 0.67 1.5 1.5 S 17.83 9 17 9 Z\" }],\n // markerPathWidth: 24,\n // markerPathHeight: 24,\n // markerWidth: 24,\n // markerHeight: 24,\n // markerDy: 1.5,\n // markerDx: 1.5,\n // }\n\n // const created = createSpriteMaterialByLabelSymbol([\n // baseSymbol,\n // markerSymbol,\n // ])\n // this.materialByKey.set(key, created)\n // return created\n // }\n}","// TextSpriteMarker.js\nimport { Coordinate, Util } from \"maptalks\"\nimport * as THREE from \"three\"\nimport { BaseObject, ThreeLayer } from \"maptalks.three\" // in some builds it's maptalks.three.BaseObject\nimport { BaseObjectOptionType } from \"maptalks.three/dist/type\"\nimport { isNil, set } from \"lodash\"\nimport { Stop } from \"../../types\"\nimport { interpolateStops } from \"../../utils/interpolateStops\"\n\nconst OPTIONS: TextMarkerOptions = {\n // Texture options\n text: \"\",\n textAlign: \"center\",\n color: \"#ffffff\",\n fontFamily: \"sans-serif\",\n fontSize: 28,\n fontWeight: 400,\n background: \"transparent\",\n lineHeight: 32,\n padding: 8,\n strokeColor: \"#000000\",\n strokeWidth: 3,\n strokeStyle: \"round\",\n // Sprite options\n /* Overall scale multiplier */\n scale: 1,\n altitude: 0,\n opacity: 1\n}\n\nexport type TextMarkerOptions = BaseObjectOptionType & {\n // Texture options\n text?: string\n textAlign?: CanvasTextAlign\n color?: CanvasFillStrokeStyles[\"fillStyle\"]\n fontFamily?: string\n fontSize?: number\n fontWeight?: number\n background?: CanvasFillStrokeStyles[\"fillStyle\"]\n lineHeight?: number\n strokeColor?: CanvasFillStrokeStyles[\"strokeStyle\"]\n strokeWidth?: number\n strokeStyle?: CanvasLineJoin\n padding?: number\n maxWidth?: number\n // Sprite options\n scale?: number\n altitude?: number\n bottomHeight?: number\n opacity?: number | { stops: Stop[] }\n}\n\nexport class TextSpriteMarker extends BaseObject {\n #altitudeOffset: number = 0\n declare options: TextMarkerOptions;\n\n constructor(\n coordinate: Coordinate,\n options: TextMarkerOptions,\n layer: ThreeLayer,\n properties: Record<string, any> = {}\n ) {\n options = Util.extend({}, OPTIONS, options, { layer })\n super()\n this._coordinate = new Coordinate(coordinate)\n this._initOptions(options)\n this._createGroup()\n\n this.properties = { ...properties }\n const sprite = this._createSprite()\n\n this.getObject3d().add(sprite)\n\n this._updatePosition()\n\n this.type = \"TextSpriteMarker\"\n }\n\n getOptions(): TextMarkerOptions {\n return super.getOptions()\n }\n\n _createSprite() {\n const options = this.getOptions()\n const texture = this._createTextTexture(options.text, options)\n\n const material = new THREE.SpriteMaterial({\n map: texture,\n transparent: true,\n alphaTest: 0.1,\n })\n\n const sprite = new THREE.Sprite(material)\n\n // position will be set in _animation or directly after added to layer\n // scale to match texture aspect\n const w = texture.image.width\n const h = texture.image.height\n const base = 1 / 16 // to bring canvas px to map size-ish\n\n // Normalize text scale by the current map resolution so sprite size stays visually consistent across zoom levels.\n const normalizedScale = options.scale / this.getMap().getGLRes()\n\n sprite.scale.set(w * base * normalizedScale, h * base * normalizedScale, 1)\n\n // Compute world-space height for text and use it as altitude offset.\n this.#altitudeOffset = Math.max(\n h * base * options.scale * 0.5,\n 0.05 // minimum lift in world units\n )\n\n return sprite\n }\n\n _createTextTexture(text: string, options: TextMarkerOptions = {}) {\n const {\n padding,\n fontSize,\n fontFamily,\n fontWeight,\n lineHeight,\n background,\n color,\n textAlign,\n strokeColor,\n strokeWidth,\n maxWidth,\n } = options || {}\n\n // 1. create a temp canvas to measure\n const canvas = document.createElement(\"canvas\")\n const ctx = canvas.getContext(\"2d\")!\n ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`\n\n // 2. split into paragraphs (explicit \\n from user)\n const paragraphs = String(text).split(\"\\n\")\n\n // 3. wrap each paragraph to lines\n const wrappedLines: string[] = []\n\n paragraphs.forEach((paragraph) => {\n if (isNil(maxWidth) || isNaN(maxWidth)) {\n // no wrapping, keep as-is\n wrappedLines.push(paragraph)\n return\n }\n\n const words = paragraph.split(/\\s+/)\n let currentLine = \"\"\n\n words.forEach((word) => {\n const testLine = currentLine ? currentLine + \" \" + word : word\n const testWidth = ctx.measureText(testLine).width\n\n if (testWidth > maxWidth && currentLine) {\n // push current and start new\n wrappedLines.push(currentLine)\n currentLine = word\n } else {\n currentLine = testLine\n }\n })\n\n if (currentLine) {\n wrappedLines.push(currentLine)\n }\n })\n\n // 4. figure out final canvas size\n const lines = wrappedLines.length ? wrappedLines : [\"\"]\n const widest = Math.max(...lines.map((l) => ctx.measureText(l).width), 0)\n const finalWidth =\n (maxWidth ? Math.min(widest, maxWidth) : widest) + padding * 2\n const finalHeight = lineHeight * lines.length + padding * 2\n\n canvas.width = finalWidth\n canvas.height = finalHeight\n\n // 5. reapply styles after resize\n const ctx2 = canvas.getContext(\"2d\")!\n ctx2.font = `${fontWeight} ${fontSize}px ${fontFamily}`\n ctx2.textAlign = textAlign\n\n // background\n if (background && background !== \"transparent\") {\n ctx2.fillStyle = background\n ctx2.fillRect(0, 0, canvas.width, canvas.height)\n }\n\n // 6. draw all lines (stroke first, then fill)\n lines.forEach((line, i) => {\n const y = padding + lineHeight * (i + 0.8)\n let x = padding\n if (textAlign === \"center\") x = canvas.width / 2\n if (textAlign === \"right\" || textAlign === \"end\")\n x = canvas.width - padding\n\n if (strokeWidth > 0) {\n ctx2.lineWidth = strokeWidth\n ctx2.lineJoin = \"round\"\n ctx2.miterLimit = 2\n ctx2.strokeStyle = strokeColor\n ctx2.strokeText(line, x, y)\n }\n\n ctx2.fillStyle = color\n ctx2.fillText(line, x, y)\n })\n\n const texture = new THREE.CanvasTexture(canvas)\n texture.needsUpdate = true\n texture.minFilter = THREE.LinearFilter\n return texture\n }\n\n _updatePosition() {\n const options = this.getOptions()\n const layer = options.layer\n\n if (!layer) return\n\n const altitude = (options.altitude || 0) + this.#altitudeOffset\n const z = layer.altitudeToVector3(altitude, altitude).x\n const position = layer.coordinateToVector3(this._coordinate, z)\n set(this.properties, \"default.position\", position)\n this.getObject3d().position.copy(position)\n }\n\n _animation() {\n const layer = this.getLayer() as ThreeLayer\n\n if (!this.isAdd || !layer) return\n\n if (this._visible === true) {\n const zoom = layer.map.getZoom()\n \n const object3d = this.getObject3d()\n const { opacity } = this.getOptions()\n \n // Calculate opacity based on type\n let opacityValue: number\n if (typeof opacity === 'number') {\n opacityValue = opacity ?? 1\n } else if (Array.isArray(opacity.stops)) {\n opacityValue = interpolateStops(opacity, zoom)\n } else {\n throw new Error(`Unknown opacity value ${opacity}`)\n }\n // Hide object outside zoom range\n const visible = opacityValue > 0.5\n object3d.visible = visible\n }\n }\n\n setText(text: string) {\n const options = this.getOptions()\n options.text = text\n\n const newSprite = this._createSprite()\n const group = this.getObject3d()\n\n // Remove all old sprites from the group (but keep group itself)\n group.children.forEach((child) => group.remove(child))\n group.add(newSprite)\n\n this._updatePosition()\n }\n\n setAltitude(altitude: number) {\n const bottomHeight = this.options.bottomHeight ?? 0\n return super.setAltitude(altitude + bottomHeight + this.#altitudeOffset)\n }\n}\n","import { Stop } from \"../types\"\n\nexport const interpolateStops = ({ stops }: { stops: Stop[] }, zoom: number) => {\n // If zoom is before the first stop\n if (zoom <= stops[0][0]) return stops[0][1]\n // If zoom is after the last stop\n if (zoom >= stops[stops.length - 1][0]) return stops[stops.length - 1][1]\n \n // Find the two stops around the zoom\n for (let i = 0; i < stops.length - 1; i++) {\n const [z1, v1] = stops[i]\n const [z2, v2] = stops[i + 1]\n\n if (zoom >= z1 && zoom <= z2) {\n const t = (zoom - z1) / (z2 - z1)\n return v1 + t * (v2 - v1)\n }\n }\n}","export const getLineCenter = (line: number[][]) => {\n let x = 0, y = 0;\n for (const [lx, ly] of line) {\n x += lx;\n y += ly;\n }\n const len = line.length;\n return [x / len, y / len];\n};\n\n// Returns angle in radians\nexport const angleBetweenLineStrings = (\n line1: number[][],\n line2: number[][],\n): number => {\n const [x1, y1] = getLineCenter(line1);\n const [x2, y2] = getLineCenter(line2);\n\n const dx = x2 - x1;\n const dy = y2 - y1;\n\n // angle in radians, range (-PI, PI)\n return Math.atan2(dy, dx);\n};\n","import { Position } from \"geojson\";\nimport { booleanPointInPolygon } from \"@turf/boolean-point-in-polygon\";\nimport { polygon } from \"@turf/helpers\"\nimport { UnitFeature } from \"../../../data\";\n\nexport const findUnitOnPoint = (units: UnitFeature[], point: Position) => {\n try {\n return units.find(unit => booleanPointInPolygon(point, polygon(unit.geometry.coordinates as Position[][])))\n } catch (err) {\n return null\n }\n}"],"mappings":";;;;;;;AAAA,SAAS,iBAAAA,sBAAqB;;;ACGvB,IAAM,mBAAmB;AAEzB,IAAM,qBAAoC;AAAA,EAC/C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,uBAAiC;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,wBAAuC;AAAA,EAClD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,wBAAuC;AAAA,EAClD,GAAG;AAAA,EACH,GAAG;AACL;AAEO,IAAM,oBAAmC;AAAA,EAC9C,GAAG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AA,IAMH;AAEA,SAAK,iBAAiB,QAAQ,CAAC,EAAE,SAAS,MAAM,SAAS,IAAI,CAAC;AAG9D,UAAM,OAAO;AAEb,0BAAsB,KAAK,OAAO,KAAK,IAAI,CAAC;AAAA,EAC9C;AACF;","names":["QueryObserver","point","polygon","lineString","center","booleanPointInPolygon","unit","kiosk","booleanPointInPolygon","section","unit","center","feature","max","obj","path","norm","value","score","pattern","result","item","_","searchers","query","search","feature","options","Map","LineString","Coordinate","_","isNumber","isNumber","turfCenter","ThreeLayer","_","TextureLoader","SpriteMaterial","scale","BaseObject","Sprite","SpriteMaterial","_","scale","maptalks","BaseObject","OPTIONS","feature","center","_","center","_","polygon","scale","feature","_","polygon","SpriteMaterial","TextureLoader","feature_type","properties","logoUrl","scale","feature","compact","turfCenter","THREE","maptalks","BaseObject","turfBuffer","maptalks","BaseObject","isNumber","isArray","OPTIONS","ctx","text","scale","center","feature","turfBuffer","BaseObject","maptalks","DEFAULT_POLYGON_OPTION","MULTIORDINAL_HEIGHT_METER","feature","DEFAULT_POLYGON_OPTION","MULTIORDINAL_HEIGHT_METER","maptalks","maptalks","THREE","Coordinate","Util","THREE","BaseObject","OPTIONS","BaseObject","Util","Coordinate","leg","booleanPointInPolygon","point","booleanPointInPolygon","scene","compact","turfCenter","center","_","Map","ThreeLayer","turfCenter","center","Coordinate","feature","geometry","LineString"]}
1
+ {"version":3,"sources":["../src/data/index.ts","../src/data/constant.ts","../src/data/api/delivery-project.ts","../src/data/utils/geometry-validator.ts","../src/data/utils/match-filters.ts","../src/data/utils/occupant-helper.ts","../src/data/utils/lodash/compact.ts","../src/data/getDataClient.ts","../src/data/populator/index.ts","../src/data/utils/findContaining.ts","../src/data/search/getSearchClient.ts","../src/data/search/utils/sanitizeInput.ts","../src/data/navigate/getNavigateClient.ts","../src/data/navigate/graph/prepare.ts","../src/data/navigate/graph/nodemap/createTraversalNodeMap.ts","../src/data/navigate/graph/constants.ts","../src/data/navigate/graph/utils/getDistanceOption.ts","../src/data/utils/trace.ts","../src/data/navigate/graph/nodemap/createElevatorNodeMap.ts","../src/data/navigate/graph/nodemap/createEscalatorNodeMap.ts","../src/data/navigate/graph/nodemap/createRampNodeMap.ts","../src/data/navigate/graph/nodemap/createStairNodeMap.ts","../src/data/navigate/graph/nodemap/createOccupantNodeMap.ts","../src/data/navigate/graph/nodemap/createPOINodeMaps.ts","../src/data/navigate/graph/utils/mergeNodeMap.ts","../src/data/navigate/graph/utils/createUnitOpenings.ts","../src/data/navigate/parsers.ts","../src/data/navigate/steps/createStepUtils.ts","../src/data/navigate/description/describe.ts","../src/data/navigate/steps/path/index.ts","../src/data/navigate/constants.ts","../node_modules/@turf/helpers/index.ts","../node_modules/@turf/invariant/index.ts","../../../node_modules/@turf/meta/index.js","../../../node_modules/@turf/bbox/index.ts","../src/data/navigate/steps/path/turf/shortestPath.ts","../src/data/navigate/steps/path/turf/stringPull.ts","../src/data/navigate/steps/path/turf/pruneSmallAngle.ts","../src/data/navigate/steps/path/turf/pruneShortSegments.ts","../src/data/navigate/steps/path/turf/clearance.ts","../src/data/navigate/landmark/createLandmarkUtils.ts","../src/data/navigate/steps/utils/extractStartPoint.ts","../src/data/navigate/steps/utils/featureIdGuard.ts","../src/data/navigate/type-guard.ts","../src/data/navigate/steps/utils/extractEndPint.ts","../src/data/navigate/steps/utils/combineWalkwaySteps.ts","../src/data/navigate/utils/timeDistance.ts","../src/data/navigate/utils/createFindByIdSync.ts","../src/IndoorMap/IndoorMap.ts","../src/IndoorMap/constants.ts","../src/IndoorMap/utils/createElements.js","../src/IndoorMap/object3d/Billboard.js","../src/IndoorMap/object3d/SpriteMarker.ts","../src/IndoorMap/object3d/NavigationPath.ts","../src/IndoorMap/utils/geometry.ts","../src/IndoorMap/utils/svg.ts","../src/IndoorMap/utils/math.ts","../src/IndoorMap/camera/CameraManager.ts","../src/IndoorMap/renderer/RendererManager.ts","../src/IndoorMap/renderer/3d/Element3DRenderer.ts","../src/IndoorMap/renderer/3d/objects/GroundLabel.ts","../src/IndoorMap/renderer/3d/element3DRendererOptions.ts","../src/IndoorMap/renderer/3d/utils/get3DRendererOption.ts","../src/IndoorMap/renderer/2d/Element2DRenderer.ts","../src/IndoorMap/renderer/2d/element2DRendererOptions.ts","../src/IndoorMap/renderer/2d/Marker2DRenderer.ts","../src/IndoorMap/renderer/3d/Marker3DRenderer.ts","../src/IndoorMap/renderer/3d/objects/TextSpriteMarker.ts","../src/IndoorMap/renderer/utils/interpolateStops.ts","../src/IndoorMap/renderer/utils/angleBetweenLineString.ts","../src/IndoorMap/renderer/utils/findUnitOnPoint.ts"],"sourcesContent":["export { QueryObserver } from \"@tanstack/query-core\"\n\nexport * from \"./types\"\nexport * from \"./constant\"\nexport * from \"./api/delivery-project\"\nexport * from './utils'\nexport * from \"./getDataClient\"\nexport * from './search/getSearchClient'","import { FeatureQueryOptions } from \"./types\"\nimport { FeatureType } from \"./types/feature-api\"\n\nexport const DEFAULT_BASE_URL = \"https://service.venue.in.th/api\"\n\nexport const IMDF_FEATURE_TYPES: FeatureType[] = [\n \"address\",\n \"amenity\",\n \"anchor\",\n \"building\",\n \"detail\",\n \"fixture\",\n \"footprint\",\n \"geofence\",\n \"kiosk\",\n \"level\",\n \"occupant\",\n \"opening\",\n \"relationship\",\n \"section\",\n \"unit\",\n \"venue\",\n]\n\nexport const IMDF_UNIT_CATEGORIES: string[] = [\n 'auditorium',\n 'brick',\n 'classroom',\n 'column',\n 'concrete',\n 'conferenceroom',\n 'drywall',\n 'elevator',\n 'escalator',\n 'fieldofplay',\n 'firstaid',\n 'fitnessroom',\n 'foodservice',\n 'footbridge',\n 'glass',\n 'huddleroom',\n 'kitchen',\n 'laboratory',\n 'library',\n 'lobby',\n 'lounge',\n 'mailroom',\n 'mothersroom',\n 'movietheater',\n 'movingwalkway',\n 'nonpublic',\n 'office',\n 'opentobelow',\n 'parking',\n 'phoneroom',\n 'platform',\n 'privatelounge',\n 'ramp',\n 'recreation',\n 'restroom',\n 'restroom.family',\n 'restroom.female',\n 'restroom.female.wheelchair',\n 'restroom.male',\n 'restroom.male.wheelchair',\n 'restroom.transgender',\n 'restroom.transgender.wheelchair',\n 'restroom.unisex',\n 'restroom.unisex.wheelchair',\n 'restroom.wheelchair',\n 'road',\n 'room',\n 'serverroom',\n 'shower',\n 'smokingarea',\n 'stairs',\n 'steps',\n 'storage',\n 'structure',\n 'terrace',\n 'theater',\n 'unenclosedarea',\n 'unspecified',\n 'vegetation',\n 'waitingroom',\n 'walkway',\n 'walkway.island',\n 'wood',\n];\n\nexport const NONIMDF_FEATURE_TYPES: FeatureType[] = [\n \"taxonomy\",\n \"event\",\n \"promotion\",\n \"label\",\n \"privilege\",\n]\n\nexport const GEOJSON_FEATURE_TYPES: FeatureType[] = [\n ...IMDF_FEATURE_TYPES,\n ...NONIMDF_FEATURE_TYPES,\n]\n\nexport const ALL_FEATURE_TYPES: FeatureType[] = [\n ...GEOJSON_FEATURE_TYPES,\n \"sponsored-content\",\n \"element\",\n]\n\nexport const defaultFeatureQueryOptionsMap: Record<\n FeatureType,\n FeatureQueryOptions\n> = {\n // IMDF\n address: {},\n amenity: {},\n anchor: {},\n building: {},\n detail: { enabled: false },\n fixture: {},\n footprint: {},\n geofence: { enabled: false },\n kiosk: {},\n level: {},\n occupant: {\n refetchInterval: 5 * 60 * 1000, // refresh every 5 min\n staleTime: 5 * 60 * 1000,\n },\n opening: {},\n relationship: {},\n section: {},\n unit: {},\n venue: {},\n\n // OTHERS GEOJSON\n taxonomy: {},\n privilege: {},\n event: {},\n promotion: {\n refetchInterval: 0.5 * 60 * 1000, // refresh every 5 min\n staleTime: 0.5 * 60 * 1000,\n },\n label: {},\n\n // NON GEOJSON\n \"sponsored-content\": {\n refetchInterval: 1 * 60 * 1000, // refresh every 5 min\n },\n element: {},\n page: {},\n model3d: {}\n}\n","import type {\n FeatureResponseMap,\n FeatureType,\n SponsoredContentStrapiV4ApiResponse,\n} from \"../types/feature-api\"\nimport { DEFAULT_BASE_URL } from \"../constant\"\n\nexport async function fetchDeliveryApi<T extends FeatureType = FeatureType>(\n projectId: string,\n apiKey: string,\n featureType: FeatureType,\n baseUrl: string = DEFAULT_BASE_URL,\n): Promise<FeatureResponseMap[T][]> {\n // TODO: Update Label Endpoint to match other endpoints\n switch (featureType) {\n case \"label\":\n case \"element\": {\n const pluralFeatureType = `${featureType}s`\n const res = await fetch(\n `${baseUrl}/delivery/projects/${projectId}/${pluralFeatureType}.geojson?api-key=${apiKey}`\n )\n if (res.status !== 200) return []\n const items = await res.json()\n return items\n }\n\n case \"model3d\": {\n const res = await fetch(\n `${baseUrl}/delivery/projects/${projectId}/${featureType}.geojson?api-key=${apiKey}`\n )\n if (res.status !== 200) return []\n const items = await res.json()\n return items.features\n }\n\n case \"sponsored-content\": {\n const res = await fetch(\n `${baseUrl}/delivery/projects/${projectId}/sponsored-content.json?api-key=${apiKey}`\n )\n if (res.status !== 200) return []\n const jsonRes = await res.json()\n const items = jsonRes.data as SponsoredContentStrapiV4ApiResponse[]\n return items.map((item) => ({\n id: item.id,\n ...item.attributes,\n })) as FeatureResponseMap[T][]\n }\n\n default: {\n const res = await fetch(\n `${baseUrl}/delivery/projects/${projectId}/imdf/${featureType}.geojson?api-key=${apiKey}`\n )\n if (res.status !== 200) return []\n const collections = await res.json()\n return collections.features\n }\n }\n}\n\n\nexport async function fetchPreviewApi<T extends FeatureType = FeatureType>(\n projectId: string,\n previewToken: string,\n featureType: FeatureType,\n baseUrl: string = DEFAULT_BASE_URL,\n): Promise<FeatureResponseMap[T][]> {\n // TODO: Update Label Endpoint to match other endpoints\n switch (featureType) {\n case \"label\":\n case \"element\": {\n const pluralFeatureType = `${featureType}s`\n const res = await fetch(\n `${baseUrl}/preview/projects/${projectId}/${pluralFeatureType}.geojson`, {\n headers: {\n Authorization: `Bearer ${previewToken}`\n }\n }\n )\n if (res.status !== 200) return []\n const items = await res.json()\n return items\n }\n\n case \"sponsored-content\": {\n const res = await fetch(\n `${baseUrl}/preview/projects/${projectId}/sponsored-content.json`, {\n headers: {\n Authorization: `Bearer ${previewToken}`\n }\n }\n )\n if (res.status !== 200) return []\n const jsonRes = await res.json()\n const items = jsonRes.data as SponsoredContentStrapiV4ApiResponse[]\n return items.map((item) => ({\n id: item.id,\n ...item.attributes,\n })) as FeatureResponseMap[T][]\n }\n\n default: {\n const res = await fetch(\n `${baseUrl}/preview/projects/${projectId}/imdf/${featureType}.geojson`, {\n headers: {\n Authorization: `Bearer ${previewToken}`\n }\n }\n )\n if (res.status !== 200) return []\n const collections = await res.json()\n return collections.features\n }\n }\n}\n\nexport const safeFetchFeature = async <T extends FeatureType = FeatureType>(\n featureType: FeatureType,\n params: { \n mode: 'delivery' | 'preview',\n projectId: string,\n apiKey: string,\n previewToken?: string,\n baseUrl: string\n } \n): Promise<FeatureResponseMap[T][]> => {\n const mode = params.mode ?? 'delivery'\n const projectId = params.projectId\n const apiKey = params.apiKey\n const previewToken = params.previewToken\n const baseUrl = params.baseUrl ?? DEFAULT_BASE_URL\n\n try {\n let result = []\n \n if (mode === 'delivery') {\n result = await fetchDeliveryApi<T>(\n projectId,\n apiKey,\n featureType,\n baseUrl\n )\n } else if (mode === 'preview') {\n result = await fetchPreviewApi<T>(\n projectId,\n previewToken,\n featureType,\n baseUrl\n )\n }\n return result ?? []\n } catch (e) {\n // Suppress error and return []\n return Promise.resolve([])\n }\n}\n","import { Geometry, GeometryCollection, Position } from \"geojson\"\n\n/**\n * Checks if a point is a valid coordinate pair.\n *\n * @param point - The point to be checked.\n * @return True if the point is a valid coordinate pair, false otherwise.\n */\nexport const isValidCoordinate = (point: Position): boolean => {\n return point.length === 2 && point.every((coord) => typeof coord === \"number\")\n}\n\n/**\n * Checks if a set of points forms a valid linear ring (closed and simple polygon).\n *\n * @param ring - The array of points representing a linear ring.\n * @return True if the linear ring is valid, false otherwise.\n */\nfunction isValidLinearRingCoordinates(ring: Position[]): boolean {\n if (ring.length < 4) {\n return false\n }\n\n return (\n ring.every(isValidCoordinate) &&\n ring[0][0] === ring[ring.length - 1][0] &&\n ring[0][1] === ring[ring.length - 1][1]\n )\n}\n\n/**\n * Checks if an input represents a valid polygon, which may include holes.\n * The input can be a single array of coordinates for simple polygons, or\n * an array of arrays of coordinates for polygons with holes.\n *\n * @param polygon - The input representing a polygon.\n * @return True if the polygon is valid, false otherwise.\n */\nexport const isValidPolygonCoordinates = (\n polygon: Position[] | Position[][]\n): boolean => {\n // Check if it's a simple polygon (without holes)\n if (\n Array.isArray(polygon[0]) &&\n (polygon[0].length === 0 || typeof polygon[0][0] === \"number\")\n ) {\n return isValidLinearRingCoordinates(polygon as Position[])\n }\n\n // Check if it's a polygon with holes\n if (\n Array.isArray(polygon) &&\n polygon.length > 0 &&\n Array.isArray(polygon[0])\n ) {\n // Check the outer ring\n if (!isValidLinearRingCoordinates(polygon[0] as Position[])) {\n return false\n }\n\n // Check each hole\n for (let i = 1; i < polygon.length; i++) {\n if (!isValidLinearRingCoordinates(polygon[i] as Position[])) {\n return false\n }\n }\n\n return true\n }\n\n return false\n}\n\n/**\n * Checks if an array of polygons forms a valid MultiPolygon.\n *\n * @param multipolygon - The array of polygons.\n * @return True if the multipolygon is valid, false otherwise.\n */\nexport const isValidMultiPolygonCoordinates = (\n multipolygon: Position[][][]\n): boolean => {\n return multipolygon.every(isValidPolygonCoordinates)\n}\n\n/**\n * Checks if a set of points forms a valid LineString.\n * A valid LineString must have at least two points, each point must be a valid coordinate,\n * and it should not form a closed loop.\n *\n * @param lineString - The array of points representing a LineString.\n * @return True if the LineString is valid, false otherwise.\n */\nexport const isValidLineStringCoordinates = (\n lineString: Position[]\n): boolean => {\n if (!Array.isArray(lineString) || lineString.length < 2) {\n return false\n }\n\n // Check if the first and last points are the same, which would make it a polygon\n const firstPoint = lineString[0]\n const lastPoint = lineString[lineString.length - 1]\n if (firstPoint[0] === lastPoint[0] && firstPoint[1] === lastPoint[1]) {\n return false\n }\n\n return lineString.every(isValidCoordinate)\n}\n\nexport const isValidMultiPolygon = (\n geometry: Exclude<Geometry, GeometryCollection>\n): boolean => {\n const { type, coordinates } = geometry\n return type === \"MultiPolygon\" && isValidMultiPolygonCoordinates(coordinates)\n}\n\nexport const isValidPolygon = (\n geometry: Exclude<Geometry, GeometryCollection>\n): boolean => {\n const { type, coordinates } = geometry\n return type === \"Polygon\" && isValidPolygonCoordinates(coordinates)\n}\n\nexport const isValidLineString = (\n geometry: Exclude<Geometry, GeometryCollection>\n): boolean => {\n const { type, coordinates } = geometry\n return type === \"LineString\" && isValidLineStringCoordinates(coordinates)\n}\n\nexport const isValidPoint = (\n geometry: Exclude<Geometry, GeometryCollection>\n): boolean => {\n const { type, coordinates } = geometry\n return type === \"Point\" && isValidCoordinate(coordinates)\n}\n","import type { Value, InFilter, Filter, Filters } from '../types/match-filters'\n\nfunction isInFilter(filter: Filter): filter is InFilter {\n return (\n typeof filter === \"object\" &&\n filter !== null &&\n \"$in\" in filter &&\n Array.isArray((filter as any).$in)\n );\n}\n\nconst someIntersect = (a: Value[], b: Value[]) => a.some(v => b.includes(v));\n\nexport function matchFilter(value: Value | Value[], filter: Filter) {\n\n if (Array.isArray(value)) {\n if (isInFilter(filter)) return someIntersect(value, filter.$in);\n \n // Equal\n return value.includes(filter as Value);\n \n } else {\n if (isInFilter(filter)) return filter.$in.includes(value);\n \n // Equal\n return value === filter;\n }\n}\n\nexport function matchFilters<T extends Record<string, any>>(item: T, filters: Filters): boolean {\n return Object.entries(filters).every(([key, filter]) => {\n return matchFilter(item.properties[key], filter)\n });\n}","import { compact } from \"../utils/lodash\"\nimport { KioskFeaturePopulated, OccupantFeaturePopulated, UnitFeaturePopulated } from \"../types\";\n\nexport const getOccupantMainLocation = (occupant: OccupantFeaturePopulated): UnitFeaturePopulated | KioskFeaturePopulated => {\n return occupant.properties.kiosk || occupant.properties.unit\n}\n\nexport const getOccupantCorrelatedLocations = (occupant: OccupantFeaturePopulated): Array<UnitFeaturePopulated | KioskFeaturePopulated> => {\n\n const allCorrelatedLocations = [\n ...occupant.properties.units,\n ...occupant.properties.kiosks,\n ]\n\n return compact(allCorrelatedLocations)\n}\n\nexport type OccupantMarkerPlacementType = 'ONCE_PER_LEVEL' | 'ALL_LOCATIONS'\n\nexport const getOccupantMarkerLocations = (occupant: OccupantFeaturePopulated, options?: { type: OccupantMarkerPlacementType }): Array<UnitFeaturePopulated | KioskFeaturePopulated> => {\n\n /**\n * Use optiosn.type first\n * THEN occupant.show_name_on_all_units \n */\n const placementType = options?.type ? options.type : occupant.properties.show_name_on_all_units ? 'ALL_LOCATIONS' : 'ONCE_PER_LEVEL'\n\n const mainLocation = getOccupantMainLocation(occupant)\n\n const mainLocationLevel = mainLocation?.properties?.level_id\n const allCorrelatedLocations = getOccupantCorrelatedLocations(occupant)\n\n // IF showNameonAllLocations = true, Show All \n if (placementType === 'ALL_LOCATIONS') {\n return compact([mainLocation, ...allCorrelatedLocations])\n }\n \n // ELSE Show Once per level\n const otherLevelLocations = allCorrelatedLocations.filter((f) => f.properties.level_id !== mainLocationLevel)\n const onePerLevelLocations = [...new Map(otherLevelLocations.map(loc => [loc.properties.level_id, loc])).values()]\n return compact([mainLocation, ...onePerLevelLocations])\n}\n","export const compact = <T extends unknown = unknown>(arr: T[]): T[] => arr.filter(item => Boolean(item));\n","import { safeFetchFeature } from \"./api/delivery-project\"\nimport { FeatureResponseMap, FeatureType, ImdfFeature } from \"./types/feature-api\"\nimport {\n EnsureQueryDataOptions,\n QueryClient,\n QueryObserver,\n} from \"@tanstack/query-core\"\nimport {\n FeatureQueryOptions,\n FilterParams,\n FindParams,\n InternalFilterByType,\n InternalFindById,\n NavigateClient,\n PopulatedParams,\n SearchClient,\n VenueClientOptions,\n VenueDataClient,\n} from \"./types/VenueDataClient\"\nimport { createPopulator } from \"./populator\"\nimport { FeaturePopulatedResponseMap } from \"./types\"\nimport { matchFilters } from \"./utils/match-filters\"\nimport { FuseResult } from \"fuse.js\"\nimport { getSearchClient } from \"./search\"\nimport { getNavigateClient } from \"./navigate\"\n\nexport const getDataClient = (options: VenueClientOptions): VenueDataClient => {\n let searchClient: SearchClient;\n let navigateClient: NavigateClient;\n\n const observers = new Map<\n FeatureType,\n { observer: QueryObserver<any, any>, unsubscribe: () => void }\n >()\n\n const queryClient = options.queryClient ?? new QueryClient()\n const { mode = 'delivery', projectId, apiKey, baseUrl, previewToken } = options\n\n if (!projectId)\n throw new Error(\n \"Cannot create VenueDataClient. Reason: `projectId` is missing\"\n )\n \n if (mode === 'delivery' && !apiKey)\n throw new Error(\n \"Cannot create VenueDataClient. Reason: `apiKey` is missing\"\n )\n\n if (mode === 'preview' && !previewToken)\n throw new Error(\n \"Cannot create VenueDataClient. Reason: `previewToken` is missing\"\n )\n\n const createDeliveryApiQueryOptions = <T extends FeatureType = FeatureType>(\n featureType: T\n ) => ({\n queryKey: [\"_deliveryapi\", featureType] as const,\n queryFn: () => safeFetchFeature<T>(featureType, { mode, projectId, apiKey, previewToken, baseUrl }),\n })\n\n /**\n * Internal Functions\n * ***********************************/\n const internalFilterByType: InternalFilterByType = async <T extends FeatureType = FeatureType>(\n featureType: T\n ) => {\n\n try {\n const features = await queryClient.ensureQueryData<\n FeatureResponseMap[T][],\n unknown,\n FeatureResponseMap[T][]\n >(createDeliveryApiQueryOptions(featureType))\n return features\n } catch (error) {\n throw error\n }\n }\n\n const internalFindById: InternalFindById = async <T extends FeatureType = FeatureType>(\n id: string\n ) => {\n if (id === null || id === undefined) return null\n const featureType = id.slice(0, id.lastIndexOf(\"-\")) as FeatureType\n const feature = await queryClient.ensureQueryData<FeatureResponseMap[T]>({\n queryKey: [\"_deliveryapi\", featureType, id],\n queryFn: async () => {\n const features = await internalFilterByType(featureType)\n const feature = features.find(\n (f) => f.id === id\n ) as FeatureResponseMap[T]\n return feature ?? null\n },\n })\n return feature\n }\n\n // Create `Feature Populator` with internal functions\n const populator = createPopulator({ internalFindById, internalFilterByType })\n\n /**\n * Public Functions\n * ***********************************/\n const registerObserver = (\n featureType: FeatureType,\n refetchInterval: number\n ) => {\n if (observers.has(featureType)) {\n console.warn(`Observer for ${featureType} already exists`)\n const record = observers.get(featureType)\n return record.observer\n }\n const options = createDeliveryApiQueryOptions(featureType)\n const observer = new QueryObserver(queryClient, {\n ...options,\n refetchInterval,\n })\n const unsubscribe = observer.subscribe(() => {\n console.log(`[venue-js] Listening to ${featureType} changes (interval = ${refetchInterval}ms)`)\n // TODO: add logs or what to do after subscribe\n })\n observers.set(featureType, { observer, unsubscribe })\n\n return observer\n }\n\n const destroyObserver = (featureType: FeatureType) => {\n const record = observers.get(featureType)\n if (!record) return\n\n record.unsubscribe()\n observers.delete(featureType)\n }\n\n const destroyObservers = () => {\n observers.forEach(({ observer, unsubscribe }) => {\n unsubscribe()\n observer.destroy()\n })\n observers.clear()\n }\n\n const createFilterByTypeQueryOptions = <T extends FeatureType = FeatureType>(\n featureType: T,\n params: FilterParams = {},\n options: FeatureQueryOptions = {}\n ): EnsureQueryDataOptions<FeatureResponseMap[T][] | FeaturePopulatedResponseMap[T][]> => ({\n queryKey: [featureType, \"list\", params] as const,\n queryFn: async () => {\n const features = await internalFilterByType<T>(featureType)\n \n // Filter \n const filters = params.filters ?? {}\n let result = features\n if (params.filters) {\n result = features.filter(f => matchFilters(f, filters))\n }\n\n // Populate\n return params.populate === true\n ? await Promise.all(result.map((f) => populator[featureType](f)))\n : result\n },\n ...(options ?? {}),\n })\n\n const createFindByIdQueryOptions = <T extends FeatureType = FeatureType>(\n featureType: T,\n id: string,\n params: FindParams = {},\n options: FeatureQueryOptions = {}\n ): EnsureQueryDataOptions<FeatureResponseMap[T] | FeaturePopulatedResponseMap[T]> => ({\n queryKey: [featureType, \"detail\", id, params] as const,\n queryFn: async () => {\n const feature = await internalFindById<T>(id)\n return params.populate === true\n ? await populator[featureType](feature)\n : Promise.resolve(feature)\n },\n ...(options ?? {}),\n })\n\n async function filterByType<T extends FeatureType>(featureType: T, params: FilterParams & PopulatedParams): Promise<FeaturePopulatedResponseMap[T][]>\n async function filterByType<T extends FeatureType>(featureType: T, params?: FilterParams): Promise<FeatureResponseMap[T][]>\n async function filterByType<T extends FeatureType>(featureType: T, params?: FilterParams) {\n const filterQueryOptions = createFilterByTypeQueryOptions<T>(\n featureType,\n params\n )\n const features = await queryClient.ensureQueryData(filterQueryOptions)\n return (params?.populate === true) ? features as FeaturePopulatedResponseMap[T][] : features as FeatureResponseMap[T][]\n }\n\n async function findById<T extends FeatureType>(featureType: T, id: string, params: FindParams & PopulatedParams): Promise<FeaturePopulatedResponseMap[T]>\n async function findById<T extends FeatureType>(featureType: T, id: string, params?: FindParams): Promise<FeatureResponseMap[T]>\n async function findById<T extends FeatureType>( featureType: T, id: string, params?: FindParams) {\n const findQueryOptions = createFindByIdQueryOptions<T>(\n featureType,\n id,\n params\n )\n const feature = await queryClient.ensureQueryData(findQueryOptions)\n return feature\n }\n\n const searchFn = async (txt: string): Promise<FuseResult<ImdfFeature>[]> => {\n if (!searchClient) {\n const [occupants, amenities] = await Promise.all([\n filterByType(\"occupant\"),\n filterByType(\"amenity\")\n ])\n const haystack = { occupants, amenities }\n searchClient = getSearchClient(haystack)\n }\n return searchClient.search(txt)\n }\n\n const navigateFn = async (origin: string, destination: string) => {\n if (!navigateClient) {\n const [levels, occupants, openings, relationships, units, fixtures, kiosks, amenities, anchors] = await Promise.all([\n filterByType(\"level\"),\n filterByType(\"occupant\"),\n filterByType(\"opening\"),\n filterByType(\"relationship\"),\n filterByType(\"unit\"),\n filterByType(\"fixture\"),\n filterByType(\"kiosk\"),\n filterByType(\"amenity\"),\n filterByType(\"anchor\")\n ])\n const haystack = { levels, occupants, openings, relationships, units, fixtures, kiosks, amenities, anchors }\n navigateClient = getNavigateClient({ data: haystack })\n }\n return navigateClient.findRoute(origin, destination)\n }\n\n return {\n projectId,\n queryClient,\n registerObserver,\n destroyObserver,\n destroyObservers,\n createFilterByTypeQueryOptions,\n createFindByIdQueryOptions,\n _internalFindById: internalFindById,\n filterByType,\n findById,\n search: searchFn,\n navigate: navigateFn\n }\n}\n","import {\n FeatureResponseMap,\n FeaturePopulatedResponseMap,\n InternalFindById,\n InternalFilterByType,\n SectionFeature,\n} from \"../types\"\nimport { compact } from '../utils/lodash'\n\nimport { center } from '@turf/center'\nimport { booleanPointInPolygon } from \"@turf/boolean-point-in-polygon\"; // หรือ pointOnFeature\nimport { findContainingUnit } from \"../utils/findContaining\";\n\n \ntype CreatePopulatorOptions = {\n internalFindById: InternalFindById\n internalFilterByType: InternalFilterByType\n}\n\ntype PopulatableFeatureType = Extract<\n keyof FeatureResponseMap,\n keyof FeaturePopulatedResponseMap\n>\ntype PopulatorFn<T extends PopulatableFeatureType> = (\n f: FeatureResponseMap[T]\n) => Promise<FeaturePopulatedResponseMap[T]>\n\nexport type Populator = {\n [K in PopulatableFeatureType]?: PopulatorFn<K>\n}\n\nexport const createPopulator = ({\n internalFindById,\n internalFilterByType,\n}: CreatePopulatorOptions): Populator => {\n const populateAddress: PopulatorFn<\"address\"> = (address) =>\n Promise.resolve(address)\n const populateBuilding: PopulatorFn<\"building\"> = (building) =>\n Promise.resolve(building)\n const populateDetail: PopulatorFn<\"detail\"> = (detail) =>\n Promise.resolve(detail)\n const populateFootprint: PopulatorFn<\"footprint\"> = (footprint) =>\n Promise.resolve(footprint)\n const populateGeofence: PopulatorFn<\"geofence\"> = (geofence) =>\n Promise.resolve(geofence)\n const populatePrivilege: PopulatorFn<\"privilege\"> = (privilege) =>\n Promise.resolve(privilege)\n const populateEvent: PopulatorFn<\"event\"> = (event) => Promise.resolve(event)\n\n const populatePromotion: PopulatorFn<\"promotion\"> = async (promotion) => {\n const venue = await internalFindById<\"venue\">(promotion.properties.venue_id)\n return {\n ...promotion,\n properties: {\n ...promotion.properties,\n venue,\n },\n }\n }\n\n const populateAmenity: PopulatorFn<\"amenity\"> = async (amenity) => {\n const units = await Promise.all(\n amenity.properties.unit_ids.map(internalFindById<\"unit\">)\n )\n\n const populatedUnits = await Promise.all(units.map(populateUnit))\n\n const venue = await internalFindById<\"venue\">(amenity.properties.venue_id)\n\n const defaultLevel = populatedUnits[0].properties.level\n\n const kiosks = await internalFilterByType<\"kiosk\">(\"kiosk\")\n const ordinalKiosks = kiosks.filter(\n (kiosk) => kiosk.properties.level_id === defaultLevel.id\n )\n const kiosk = ordinalKiosks.find((kiosk) => booleanPointInPolygon(amenity, kiosk))\n return {\n ...amenity,\n properties: {\n ...amenity.properties,\n ordinal: defaultLevel.properties.ordinal,\n level_name: defaultLevel.properties.name.en,\n level: defaultLevel,\n units: populatedUnits,\n venue,\n _experimental_kiosk: kiosk ? await populateKiosk(kiosk) : null,\n },\n }\n }\n\n const populateAnchor: PopulatorFn<\"anchor\"> = async (anchor) => {\n const unit = await internalFindById<\"unit\">(anchor.properties.unit_id)\n const venue = await internalFindById<\"venue\">(unit.properties.venue_id)\n const level = await internalFindById<\"level\">(unit.properties.level_id)\n\n const sections = await internalFilterByType<\"section\">(\"section\")\n const section = sections.find((section) => booleanPointInPolygon(anchor, section))\n\n return {\n ...anchor,\n properties: {\n ...anchor.properties,\n level: await populateLevel(level),\n unit: await populateUnit(unit),\n section: section ? await populateSection(section) : null,\n venue: await populateVenue(venue),\n ordinal: level.properties.ordinal,\n },\n }\n }\n\n const populateFixture: PopulatorFn<\"fixture\"> = async (fixture) => {\n const level = await internalFindById<\"level\">(fixture.properties.level_id)\n const venue = await internalFindById<\"venue\">(fixture.properties.venue_id)\n const anchor = await internalFindById<\"anchor\">(fixture.properties.anchor_id)\n\n return {\n ...fixture,\n properties: {\n ...fixture.properties,\n anchor: anchor ? await populateAnchor(anchor) : null,\n level: await populateLevel(level),\n venue: await populateVenue(venue),\n ordinal: level.properties.ordinal,\n }\n }\n }\n\n const populateKiosk: PopulatorFn<\"kiosk\"> = async (kiosk) => {\n const level = await internalFindById<\"level\">(kiosk.properties.level_id)\n const venue = await internalFindById<\"venue\">(kiosk.properties.venue_id)\n const anchor = await internalFindById<\"anchor\">(kiosk.properties.anchor_id)\n\n // Find Kiosk's Unit\n // Note: Should check with current code if anchor.unit is correct?\n const units = await internalFilterByType<\"unit\">(\"unit\")\n const unit = findContainingUnit(kiosk, units.filter(unit => unit.properties.category === \"walkway\"))\n\n let section: SectionFeature | null = null\n\n if (anchor) {\n const sections = await internalFilterByType<\"section\">(\"section\")\n section = sections.find((section) => booleanPointInPolygon(anchor, section))\n }\n\n return {\n ...kiosk,\n properties: {\n ...kiosk.properties,\n anchor: anchor ? await populateAnchor(anchor) : null,\n level: await populateLevel(level),\n venue: await populateVenue(venue),\n ordinal: level.properties.ordinal,\n\n unit: unit ? await populateUnit(unit) : null,\n section: section ? await populateSection(section) : null,\n },\n }\n }\n\n const populateLevel: PopulatorFn<\"level\"> = async (level) => {\n const venue = await internalFindById<\"venue\">(level.properties.venue_id)\n return {\n ...level,\n properties: {\n ...level.properties,\n venue,\n },\n }\n }\n\n const populateOccupant: PopulatorFn<\"occupant\"> = async (occupant) => {\n const {\n anchor_id,\n venue_id,\n local_category_ids,\n promotion_ids = [],\n privilege_ids = [],\n kiosk_id,\n unit_id,\n kiosk_ids = [],\n unit_ids = [],\n } = occupant.properties\n const anchor = await internalFindById<\"anchor\">(anchor_id)\n const venue = await internalFindById<\"venue\">(venue_id)\n\n const localCategories = await Promise.all(\n local_category_ids.map(internalFindById<\"taxonomy\">)\n )\n const promotions = await Promise.all(\n promotion_ids.map(internalFindById<\"promotion\">)\n )\n const privileges = await Promise.all(\n privilege_ids.map(internalFindById<\"privilege\">)\n )\n const kiosk = await internalFindById<\"kiosk\">(kiosk_id)\n const unit = await internalFindById<\"unit\">(unit_id)\n\n const kiosks = await Promise.all(kiosk_ids.map(internalFindById<\"kiosk\">))\n const units = await Promise.all(unit_ids.map(internalFindById<\"unit\">))\n return {\n ...occupant,\n properties: {\n ...occupant.properties,\n anchor: anchor ? await populateAnchor(anchor) : null,\n local_categories: await Promise.all(\n compact(localCategories).map(populateTaxonomy)\n ),\n venue,\n promotions,\n privileges,\n\n kiosk: kiosk ? await populateKiosk(kiosk) : null,\n unit: unit ? await populateUnit(unit) : null,\n kiosks: await Promise.all(kiosks.map(populateKiosk)),\n units: await Promise.all(units.map(populateUnit)),\n },\n }\n }\n\n const populateOpening: PopulatorFn<\"opening\"> = async (opening) => {\n const venue = await internalFindById<\"venue\">(opening.properties.venue_id)\n const level = await internalFindById<\"level\">(opening.properties.level_id)\n return {\n ...opening,\n properties: {\n venue,\n level: await populateLevel(level),\n ordinal: level.properties.ordinal,\n }\n }\n }\n\n\n const populateSection: PopulatorFn<\"section\"> = async (section) => {\n const venue = await internalFindById<\"venue\">(section.properties.venue_id)\n const level = await internalFindById<\"level\">(section.properties.level_id)\n return {\n ...section,\n properties: {\n ...section.properties,\n venue,\n level: await populateLevel(level),\n ordinal: level.properties.ordinal,\n },\n }\n }\n\n const populateRelationship: PopulatorFn<\"relationship\"> = async (relationship) => {\n const originId = relationship.properties.origin?.id\n const destinationId = relationship.properties.destination?.id\n const origin = originId ? await internalFindById<\"opening\" | \"unit\">(originId) : null\n const destination = destinationId ? await internalFindById<\"opening\" | \"unit\">(destinationId) : null\n const intermediary_ids = (relationship.properties.intermediary || []).map(({ id }) => id)\n const intermediary = await Promise.all(intermediary_ids.map(internalFindById<\"opening\" | \"unit\">))\n\n return {\n ...relationship,\n properties: {\n ...relationship.properties,\n origin,\n destination,\n intermediary,\n }\n }\n }\n\n const populateUnit: PopulatorFn<\"unit\"> = async (unit) => {\n const venue = await internalFindById<\"venue\">(unit.properties.venue_id)\n const level = await internalFindById<\"level\">(unit.properties.level_id)\n\n const sections = await internalFilterByType<\"section\">(\"section\")\n try {\n const section = unit.geometry.type !== 'MultiPolygon' ? sections.find((section) => booleanPointInPolygon(center(unit), section)) : null\n return {\n ...unit,\n properties: {\n ...unit.properties,\n venue,\n ordinal: level.properties.ordinal,\n level: await populateLevel(level),\n section: section ? await populateSection(section) : null,\n },\n }\n } catch (err) {\n console.log(`error finding section `, { unit, sections })\n }\n }\n\n const populateVenue: PopulatorFn<\"venue\"> = (venue) => {\n return Promise.resolve(venue)\n }\n\n const populateTaxonomy: PopulatorFn<\"taxonomy\"> = async (taxonomy) => {\n const venue = await internalFindById<\"venue\">(taxonomy.properties.venue_id)\n return {\n ...taxonomy,\n properties: {\n ...taxonomy.properties,\n venue: venue ? await populateVenue(venue) : null,\n },\n }\n }\n\n const populateModel3D: PopulatorFn<\"model3d\"> = async (model3d) => {\n const level = await internalFindById<\"level\">(model3d.properties.level_id)\n try {\n return {\n ...model3d,\n properties: {\n ...model3d.properties,\n level: await populateLevel(level),\n },\n }\n } catch (err) {\n console.log(`error finding level`, { model3d, level })\n }\n }\n\n const populateFeature = (feature) => Promise.resolve(feature)\n\n return {\n address: populateAddress,\n building: populateBuilding,\n detail: populateDetail,\n fixture: populateFixture,\n footprint: populateFootprint,\n geofence: populateGeofence,\n opening: populateOpening,\n relationship: populateRelationship,\n privilege: populatePrivilege,\n promotion: populatePromotion,\n event: populateEvent,\n label: populateFeature,\n element: populateFeature,\n page: populateFeature,\n\n amenity: populateAmenity,\n anchor: populateAnchor,\n kiosk: populateKiosk,\n level: populateLevel,\n occupant: populateOccupant,\n section: populateSection,\n unit: populateUnit,\n venue: populateVenue,\n taxonomy: populateTaxonomy,\n\n model3d: populateModel3D,\n }\n}\n","import { center } from '@turf/center'\nimport { booleanPointInPolygon } from \"@turf/boolean-point-in-polygon\";\nimport { AmenityFeature, KioskFeature, UnitFeature } from \"../types\"\nimport { Position } from 'geojson';\n\nexport const findContainingUnit = (poi: KioskFeature | AmenityFeature, units: UnitFeature[]): UnitFeature | null => {\n const unit = units.find(\n (unit) => {\n try {\n return unit.properties.level_id === poi.properties.level_id\n && booleanPointInPolygon(center(poi), unit)\n } catch (e) {\n console.log(`Cannot find containing unit of (${poi.id}):`, e.message)\n return false\n }\n }\n )\n return unit\n}\n\n\nexport const findContainingUnitAtPoint = (point: Position, levelId: string, units: UnitFeature[]): UnitFeature | null => {\n const unit = units.find(\n (unit) => {\n try {\n return unit.properties.level_id === levelId\n && booleanPointInPolygon(point, unit)\n } catch (e) {\n console.log(`Cannot find containing unit of (point: ${point}, levelId: ${levelId}):`, e.message)\n return false\n }\n }\n )\n return unit\n}\n","import Fuse, { FuseResult } from \"fuse.js\"\nimport { AmenityFeature, ImdfFeature, OccupantFeature, SearchClient } from \"../types\"\nimport { sanitizeInput } from \"./utils/sanitizeInput\"\n\nexport const getSearchClient = ({ occupants, amenities }: { occupants: OccupantFeature[], amenities: AmenityFeature[] }): SearchClient => {\n \n //** Create fuse instances once on init */\n const fuseAmenities = new Fuse(amenities, {\n threshold: 0.2,\n keys: [\n { name: \"properties.name\", \"weight\": 1, getFn: (obj) => Object.values(obj.properties.name || {}) },\n { name: \"properties.category\", \"weight\": 1 },\n ]\n })\n const fuseOccupants = new Fuse(occupants, {\n threshold: 0.25, // 0.2 is too strict (can't find Mo-Mo Paradise with \"momo\" search string)\n includeScore: true,\n shouldSort: true,\n keys: [\n { name: \"properties.name\", \"weight\": 4, getFn: (obj) => Object.values(obj.properties.name || {}) },\n { name: \"properties.keywords\", \"weight\": 0.5 },\n { name: \"properties.category\", \"weight\": 0.25 },\n { name: \"properties.local_category_names\", \"weight\": 0.25 },\n { name: \"properties.description\", \"weight\": 0.25, getFn: occ => Object.values(occ.properties.description || {}) },\n { name: \"properties.unit_name\", \"weight\": 0.25 },\n { name: \"properties.kiosk_name\", \"weight\": 0.25 }\n ]\n })\n\n const search = (value: string): FuseResult<ImdfFeature>[] => {\n\n const sanitizedValue = sanitizeInput(value)\n \n // 01. Search amenities\n const matchedAmenities = fuseAmenities.search(sanitizedValue)\n\n // 02. Search Occupants\n const matchedOccupants = fuseOccupants.search(sanitizedValue)\n\n return [...matchedAmenities, ...matchedOccupants]\n }\n\n return {\n search\n }\n}","// Switching languages might inject invisible characters like Zero Width Non-Joiners (\\u200C) or directionality marks (\\u200E, \\u200F)\nexport const sanitizeInput = (str: string) =>\n str\n .replace(/[\\u200E\\u200F\\u202A-\\u202E\\u2066-\\u2069]/g, \"\")\n .replace(/[\\-–—_./()]+/g, '') // remove separators only // remove hyphens, spaces, symbols\n .normalize(\"NFC\")\n .trim()","import { booleanPointInPolygon } from \"@turf/boolean-point-in-polygon\";\nimport { Route, NavigatableParam, GetNavigateClientOptions, CoordinateOrdinalString, FindByIdSync } from \"./type\"\nimport { prepareGraph } from \"./graph/prepare\"\nimport { createStepUtils } from \"./steps/createStepUtils\"\nimport { calculateRoundedDistance, calculateTotalDistance, calculateTravelingDuration } from \"./utils/timeDistance\"\nimport { isCoordinateOrdinalString } from \"./type-guard\"\nimport { trace } from \"../utils/trace\"\nimport { parseOrdinalCoordinate } from \"./parsers\"\nimport { createFindByIdSync } from \"./utils/createFindByIdSync\";\n\ntype NavigateClient = {\n findRoute: (\n routeOriginParam: NavigatableParam,\n routeDestinationParam: NavigatableParam,\n options?: any\n ) => Promise<Route>,\n findByIdSync: FindByIdSync\n}\nexport const getNavigateClient = (options: GetNavigateClientOptions): NavigateClient => {\n const { data } = options\n const { levels, units } = data\n trace('nav', '✓ prepare')\n const t0 = performance.now()\n trace('nav', ' ├─ createGraph (dijkstra)')\n const { defaultGraph, accessibleGraph, addCoordinateOrdinalNode } = prepareGraph({ data })\n const t1 = performance.now()\n trace('nav', ' │ └─ Total ', t1 - t0)\n\n // Create findByIdSync util\n const t2 = performance.now()\n const { findByIdSync } = createFindByIdSync(data)\n const t3 = performance.now()\n trace('nav', ' └─ findByIdSync', t3 - t2)\n\n const findCoordinateOrdinalUnit = (params: CoordinateOrdinalString) => {\n const [lat, lng, ordinal] = parseOrdinalCoordinate(params)\n const levelIdsWithOrdinal = levels.filter(level => level.properties.ordinal === ordinal).map(level => level.id)\n const unit = units.find(unit => levelIdsWithOrdinal.includes(unit.properties.level_id) && booleanPointInPolygon([lat, lng], unit))\n return unit\n }\n\n const stepUtils = createStepUtils({ ...options, findByIdSync })\n \n const findRoute = async (\n routeOriginParam: NavigatableParam,\n routeDestinationParam: NavigatableParam,\n options?: { mode: \"default\" | \"accessible\" }\n ): Promise<Route> => {\n \n // If relationshipGraph is not loaded, return null\n if (!routeOriginParam || !routeDestinationParam) return null\n const graph = options?.mode === \"accessible\" ? accessibleGraph : defaultGraph\n\n // If routeOriginParams | routeDestinationParams is \"lat,lng,or\" add to graph\n if (isCoordinateOrdinalString(routeOriginParam)) {\n const walkwayUnit = findCoordinateOrdinalUnit(routeOriginParam)\n addCoordinateOrdinalNode(routeOriginParam, walkwayUnit)\n }\n\n if (isCoordinateOrdinalString(routeDestinationParam)) {\n const walkwayUnit = findCoordinateOrdinalUnit(routeDestinationParam)\n addCoordinateOrdinalNode(routeDestinationParam, walkwayUnit)\n }\n\n try {\n trace('nav', '✓ findRoute', 0)\n\n // Dijkstra\n const t0 = performance.now()\n const path = graph.path(routeOriginParam, routeDestinationParam) as string[]\n const t1 = performance.now()\n trace('nav', ' ├─ path (dijkstra)', t1 - t0)\n\n const waypoints = stepUtils.toWaypoints(path)\n console.log({ waypoints })\n const t2 = performance.now()\n trace('nav', ' ├─ toWaypoints', t2 - t1)\n trace('nav', ' ├─ toSteps', 0)\n const steps = stepUtils.toSteps(waypoints)\n const t3 = performance.now()\n\n const totalDistance = calculateTotalDistance(steps) // distance in meters\n const roundedDistance = calculateRoundedDistance(totalDistance)\n const duration = calculateTravelingDuration(totalDistance)\n const t4 = performance.now()\n\n trace('nav', ' └─ postProcess', t4 - t3)\n\n return {\n // origin: routeOrigin,\n // destination: routeDestination,\n description: null,\n distance: roundedDistance,\n duration,\n steps,\n }\n } catch (error) {\n console.log(error)\n throw error\n }\n }\n\n return {\n findRoute,\n findByIdSync,\n }\n}\n","import _ from 'lodash'\nimport DijstraGraph from \"node-dijkstra\"\nimport { distance } from \"@turf/distance\";\nimport { center as turfCenter } from '@turf/center'\n\nimport {\n AmenityFeature,\n AnchorFeature,\n OccupantFeature,\n TraversalRelationshipFeature,\n ElevatorRelationshipFeature,\n StairsRelationshipFeature,\n EscalatorRelationshipFeature,\n UnitFeature,\n RampRelationshipFeature,\n KioskFeature,\n LevelFeature,\n RelationshipFeature,\n OpeningFeature,\n} from \"../../types\"\n\nimport {\n /** Horizontal */\n createTraversalNodeMap, \n \n /** Vertical */\n createEscalatorNodeMap,\n createElevatorNodeMap,\n createStairNodeMap,\n createRampNodeMap,\n\n /** POI */\n createOccupantNodeMap,\n createPOINodeMap\n} from './nodemap'\nimport { mergeNodeMap } from './utils/mergeNodeMap'\nimport { createUnitOpenings } from './utils/createUnitOpenings'\nimport { findContainingUnit } from '../../utils/findContaining'\nimport { UnitDistanceOptions } from './type'\nimport { CoordinateOrdinalString } from '../type'\nimport { parseOrdinalCoordinate } from '../parsers'\n\nexport type PrepareGraphOptions = {\n data: {\n relationships?: RelationshipFeature[]\n occupants?: OccupantFeature[]\n levels?: LevelFeature[]\n openings?: OpeningFeature[]\n units?: UnitFeature[]\n kiosks?: KioskFeature[]\n anchors?: AnchorFeature[]\n amenities?: AmenityFeature[]\n }\n unitDistanceOptions?: Partial<UnitDistanceOptions>\n}\n\nexport const prepareGraph = (options: PrepareGraphOptions) => {\n\n const {\n data: {\n amenities = [],\n anchors = [],\n occupants = [],\n relationships = [],\n openings = [],\n units = [],\n kiosks = [],\n levels = []\n }\n } = options\n\n const {\n traversal: traversalRelationships = [],\n escalator: escalatorRelationships = [],\n ramp: rampRelationships = [],\n elevator: elevatorRelationships = [],\n stairs: stairsRelationships = [],\n } = _.groupBy(relationships, \"properties.category\") as {\n traversal?: TraversalRelationshipFeature[]\n escalator?: EscalatorRelationshipFeature[]\n ramp?: RampRelationshipFeature[]\n elevator?: ElevatorRelationshipFeature[]\n stairs?: StairsRelationshipFeature[]\n }\n\n const unitOpenings = createUnitOpenings(traversalRelationships, units, openings)\n \n // Connect Opening <---> Opening\n const traversalNodeMap = createTraversalNodeMap(unitOpenings, options)\n\n // Connect escalators between levels\n const escalatorNodeMap = createEscalatorNodeMap(escalatorRelationships, options)\n\n // Connect ramps between levels\n const rampNodeMap = createRampNodeMap(rampRelationships, options)\n\n // Connect elevators between levels\n const elevatorNodeMap = createElevatorNodeMap(\n elevatorRelationships,\n unitOpenings,\n options,\n )\n\n /** Connect stairs between levels\n * Note:\n * This is treated like elevator. But origin is Opening instead of Unit\n * - ทีม content วาดบันไดเหมือนเป็นลิฟท์ (ทุกชั้นชื่อเดียวกัน)\n * - แต่ตอน seed ทำบันไดเหมือนเป็น ramp (origin is Opening, destination is Opening)\n * - ตอนสร้าง Graph เลยต้องทำคล้ายๆ Elevator (แต่เปลี่ยนวิธีหา opening)\n */\n const stairNodeMap = createStairNodeMap(\n stairsRelationships,\n unitOpenings,\n options\n )\n\n // Connect Amenities <--> Walkway openings (amenity.properties.units[0])\n const amenityNodeMap = createPOINodeMap(amenities, amenity => amenity.properties.unit_ids[0], unitOpenings)\n\n // Connect Anchors <--> Walkway openings (anchor.properties.unit)\n const anchorsNodeMap = createPOINodeMap(anchors, anchor => anchor.properties.unit_id, unitOpenings)\n\n // Connect Section <--> Unit.openings (section.properties.unit)\n // Section: ปัจจุบันไม่ได้ใช้เพราะ const unit = _.get(section, \"properties.unit\") ไม่มีค่า\n\n // Connect Kiosk <--> Walkway openings (kiosk.properties.unit)\n const walkwayUnits = units.filter(unit => unit.properties.category === \"walkway\")\n const kioskNodeMap = createPOINodeMap(kiosks, (kiosk: KioskFeature) => findContainingUnit(kiosk, walkwayUnits)?.id, unitOpenings)\n\n // Connect Unit <--> openings\n const unitNodeMap = createPOINodeMap(units, unit => unit.id, unitOpenings)\n\n /** Connect \n * Occupant <--> Unit \n * Occupant <--> Kiosk \n */\n const occupantNodeMap = createOccupantNodeMap(occupants)\n const defaultGraph = new DijstraGraph(mergeNodeMap([\n traversalNodeMap,\n escalatorNodeMap,\n rampNodeMap,\n elevatorNodeMap,\n stairNodeMap,\n amenityNodeMap,\n anchorsNodeMap,\n kioskNodeMap,\n unitNodeMap,\n occupantNodeMap,\n ]))\n\n const accessibleGraph = new DijstraGraph(mergeNodeMap([\n traversalNodeMap,\n rampNodeMap,\n elevatorNodeMap,\n amenityNodeMap,\n anchorsNodeMap,\n kioskNodeMap,\n unitNodeMap,\n occupantNodeMap,\n ]))\n\n /** Add [13,100,1o] to Graph */\n const addCoordinateOrdinalNode = (params: CoordinateOrdinalString, locatedOnUnit: UnitFeature) => {\n const [lat, lng, ordinal] = parseOrdinalCoordinate(params)\n if (locatedOnUnit) {\n const openings = unitOpenings[locatedOnUnit.id]\n for (const opening of openings) {\n const openingCenter = turfCenter(opening)\n const dis = distance([lat, lng], openingCenter, { units: 'meters' })\n defaultGraph\n .addNode(params, { [opening.id]: dis })\n .addNode(opening.id, { [params]: dis })\n accessibleGraph\n .addNode(params, { [opening.id]: dis })\n .addNode(opening.id, { [params]: dis })\n }\n }\n }\n\n return { defaultGraph, accessibleGraph, unitOpenings, addCoordinateOrdinalNode }\n}","import { distance as turfDistance } from \"@turf/distance\"\nimport { center as turfCenter } from \"@turf/center\"\nimport _ from 'lodash'\n\nimport { AmenityFeature, AnchorFeature, OpeningFeature } from \"../../../types\"\nimport { DistanceOptions, NodeMap } from \"../type\"\nimport { getDistanceOptions } from \"../utils/getDistanceOption\"\nimport { PrepareGraphOptions } from \"../prepare\"\nimport { trace } from '../../../utils/trace'\n\nexport const createTraversalNodeMap = (\n unitOpenings: Record<string, OpeningFeature[]>,\n options: PrepareGraphOptions\n): NodeMap => {\n const { units } = options.data\n let counter = 0\n\n // Find Distance between unit's openings \n const calculateFeatureDistanceWithinUnit = (\n features: (OpeningFeature | AnchorFeature | AmenityFeature)[],\n distanceOptions: DistanceOptions,\n ): NodeMap => {\n let relationshipGraph = {}\n for (let currentIndex = 0; currentIndex < features.length; currentIndex++) {\n const isLastItem = currentIndex + 1 === features.length\n if (isLastItem) break // Skip the last item\n\n for (let j = currentIndex + 1; j < features.length; j++) {\n const opening = features[currentIndex]\n const feature = features[j]\n\n try {\n const distance =\n turfDistance(\n turfCenter(opening.geometry), \n turfCenter(feature.geometry), \n { units: \"meters\" }\n ) + (distanceOptions?.baseDistance ?? 0)\n\n if (opening.id === feature.id) continue // Skip if IDs are the same\n \n _.set(relationshipGraph, `${opening.id}.${feature.id}`, distance)\n _.set(relationshipGraph, `${feature.id}.${opening.id}`, distance)\n counter++\n } catch (error) {\n // Error handling: in case of an error, continue to the next iteration\n continue\n }\n }\n }\n \n return relationshipGraph\n }\n \n const t0 = performance.now()\n\n const nodeMap = _.reduce(unitOpenings, \n (acc: NodeMap, openings: OpeningFeature[], unitId: string) => {\n const unit = units.find(unit => unit.id === unitId)\n const unitDistanceOption = getDistanceOptions(options.unitDistanceOptions, unit.properties.category)\n return _.merge(\n acc,\n calculateFeatureDistanceWithinUnit(openings, unitDistanceOption)\n )\n },\n {}\n )\n const t1 = performance.now()\n trace('nav', ` │ ├─ add ${counter} traversal relationships`, t1 - t0)\n\n return nodeMap\n}","import { UnitDistanceOptions } from \"./type\"\n\nexport const ROOM_BASEDISTANCE = 1000\nexport const TERRACE_BASEDISTANCE = 1000\nexport const ESCALATOR_BASEDISTANCE = 200\nexport const RAMP_BASEDISTANCE = 200\nexport const ELEVATOR_BASEDISTANCE = 500\nexport const STAIR_BASEDISTANCE = 100000\nexport const STAIR_EMERGENCYEXIT_BASEDISTANCE = 1000000\nexport const BASE_POI_BASEDISTANCE = 9999999\n\nexport const DEFAULT_UNIT_BASEDISTANCE_OPTIONS: UnitDistanceOptions = {\n default: { baseDistance: 0 },\n byCategory: {\n room: { baseDistance: ROOM_BASEDISTANCE },\n terrace: { baseDistance: TERRACE_BASEDISTANCE },\n escalator: { baseDistance: ESCALATOR_BASEDISTANCE, scaleDistanceByLevel: false },\n ramp: { baseDistance: RAMP_BASEDISTANCE, scaleDistanceByLevel: false },\n elevator: { baseDistance: ELEVATOR_BASEDISTANCE, scaleDistanceByLevel: false },\n stairs: {\n baseDistance: STAIR_BASEDISTANCE,\n scaleDistanceByLevel: true,\n },\n 'stairs.emergencyexit': {\n baseDistance: STAIR_BASEDISTANCE,\n scaleDistanceByLevel: true,\n }, \n }\n}\n","import { DEFAULT_UNIT_BASEDISTANCE_OPTIONS } from \"../constants\";\nimport { UnitDistanceOptions } from \"../type\";\n\nexport const getDistanceOptions = (options: Partial<UnitDistanceOptions>, category: string) => {\n if (!options) return DEFAULT_UNIT_BASEDISTANCE_OPTIONS.byCategory[category]\n return ((category && options.byCategory?.[category]) ?? DEFAULT_UNIT_BASEDISTANCE_OPTIONS.byCategory[category] ?? options?.default ?? DEFAULT_UNIT_BASEDISTANCE_OPTIONS.default)\n}","export const trace = (namespace: string, text: string, ms?: number, color?: string) => {\n console.log(`[${namespace}] %c${text.padEnd(90)} ${ms !== undefined ? `${(ms).toFixed(1).padStart(6)} ms`: ``}`, color ? `color: ${color}` : undefined)\n}","import _ from \"lodash\"\nimport { ElevatorRelationshipFeature, LevelFeature, OpeningFeature } from \"../../../types\"\nimport { NodeMap, VerticalDistanceOptions } from \"../type\"\nimport { ELEVATOR_BASEDISTANCE } from \"../constants\"\nimport { PrepareGraphOptions } from \"../prepare\"\nimport { getDistanceOptions } from \"../utils/getDistanceOption\"\nimport { compact } from \"../../../utils/lodash\"\nimport { trace } from '../../../utils/trace'\n\ntype OpeningAndLevel = {\n opening: OpeningFeature\n level: LevelFeature\n}\n\nexport const createElevatorNodeMap = (\n elevatorLikeRelationships: ElevatorRelationshipFeature[],\n unitOpenings: Record<string, OpeningFeature[]>,\n options: PrepareGraphOptions,\n): NodeMap => {\n const t0 = performance.now()\n\n const { levels, units } = options.data\n const distanceOptions = getDistanceOptions(options.unitDistanceOptions, 'elevator') as VerticalDistanceOptions\n const {\n baseDistance = ELEVATOR_BASEDISTANCE,\n scaleDistanceByLevel = false,\n } = distanceOptions\n\n let elevatorNodeMap: NodeMap = {}\n let counter = 0\n for (const relationship of elevatorLikeRelationships) {\n \n try {\n // 1. Find Opening & its level\n const {\n origin: originTypeAndId,\n intermediary,\n destination: destinationTypeAndId\n } = relationship.properties\n\n const origin = units.find(unit => unit.id === originTypeAndId.id)\n if (!origin) return\n\n const originOpenings = compact(unitOpenings[origin.id])\n const originLevel = levels.find(level => level.id === origin.properties.level_id)\n \n const destination = units.find(unit => unit.id === destinationTypeAndId.id)\n const destinationOpenings = unitOpenings[destination.id] \n const destinationOpeningAndLevels: OpeningAndLevel[] = destinationOpenings.map(opening => {\n const level = levels.find(level => level.id === destination.properties.level_id)\n return { opening, level }\n })\n\n const intermediaryOpeningAndLevels: OpeningAndLevel[] = intermediary.map(unitTypeAndId => {\n const openings = unitOpenings[unitTypeAndId.id]\n const unit = units.find(unit => unit.id === unitTypeAndId.id)\n const level = levels.find(level => level.id === unit.properties.level_id)\n return openings.map(opening => ({ opening, level }))\n }).flat()\n\n // Link origin ---> [intermediary's openings, destination's openings]\n const connections: OpeningAndLevel[] = compact([...intermediaryOpeningAndLevels, ...destinationOpeningAndLevels])\n if (!originOpenings || originOpenings.length === 0) return\n \n for (const originOpening of originOpenings) {\n for (const connection of connections) {\n const { opening, level } = connection\n let distance = baseDistance\n if (scaleDistanceByLevel) {\n const originOrdinal = originLevel.properties.ordinal\n const connectionOrdinal = level.properties.ordinal\n const levelDifference = Math.abs(originOrdinal - connectionOrdinal)\n if (levelDifference > 0) distance *= levelDifference\n }\n _.set(elevatorNodeMap, `${originOpening.id}.${opening.id}`, distance)\n _.set(elevatorNodeMap, `${opening.id}.${originOpening.id}`, distance)\n counter++\n }\n }\n } catch (err) {\n console.log(err)\n console.log('cannot create elevatorNodeMap for ', { relationship })\n }\n }\n const t1 = performance.now()\n trace('nav', ` │ ├─ add ${counter} escalator relationships`, t1 - t0)\n\n return elevatorNodeMap\n}\n","import set from 'lodash/set'\nimport { EscalatorRelationshipFeature } from \"../../../types\"\nimport {\n NodeMap,\n} from \"../type\"\nimport { PrepareGraphOptions } from '../prepare'\nimport { getDistanceOptions } from '../utils/getDistanceOption'\nimport { trace } from '../../../utils/trace'\n\n// Case Escalator / Ramp Relationships\nexport const createEscalatorNodeMap = (\n relationships: EscalatorRelationshipFeature[],\n options: PrepareGraphOptions\n): NodeMap => {\n const t0 = performance.now()\n const distanceOptions = getDistanceOptions(options.unitDistanceOptions, 'escalator')\n let counter = 0\n let nodeMap: NodeMap = {}\n \n for (const relationship of relationships) {\n const {\n properties: { direction, origin, destination },\n } = relationship\n set(nodeMap, `${origin.id}.${destination.id}`, distanceOptions.baseDistance)\n // Add reverse direction if undirected\n if (direction === \"undirected\") {\n set(nodeMap, `${destination.id}.${origin.id}`, distanceOptions.baseDistance)\n }\n counter++\n }\n const t1 = performance.now()\n trace('nav', ` │ ├─ add ${counter} escalator relationships`, t1 - t0)\n return nodeMap\n}","import set from 'lodash/set'\nimport { RampRelationshipFeature } from \"../../../types\"\nimport {\n NodeMap,\n VerticalDistanceOptions,\n} from \"../type\"\nimport { PrepareGraphOptions } from '../prepare'\nimport { getDistanceOptions } from '../utils/getDistanceOption'\nimport { trace } from '../../../utils/trace'\n\n// Case Ramp Relationships\nexport const createRampNodeMap = (\n relationships: RampRelationshipFeature[],\n options: PrepareGraphOptions\n): NodeMap => {\n const t0 = performance.now()\n const distanceOptions = getDistanceOptions(options.unitDistanceOptions, 'ramp') as VerticalDistanceOptions\n \n let counter = 0\n let nodeMap = {}\n \n relationships.forEach((relationship) => {\n const {\n properties: { origin, destination },\n } = relationship\n // Initialize graph for current relationship\n set(nodeMap, `${origin.id}.${destination.id}`, distanceOptions.baseDistance)\n set(nodeMap,`${destination.id}.${origin.id}`, distanceOptions.baseDistance)\n counter++\n })\n const t1 = performance.now()\n trace('nav', ` │ ├─ add ${counter} ramp relationships`, t1 - t0)\n \n return nodeMap\n}","import _ from \"lodash\"\nimport { LevelFeature, OpeningFeature, StairsRelationshipFeature } from \"../../../types\"\nimport { NodeMap, VerticalDistanceOptions } from \"../type\"\nimport { PrepareGraphOptions } from \"../prepare\"\nimport { getDistanceOptions } from \"../utils/getDistanceOption\"\nimport { trace } from \"../../../utils/trace\"\n\ntype OpeningAndLevel = {\n opening: OpeningFeature\n level: LevelFeature\n}\n\nexport const createStairNodeMap = (\n elevatorLikeRelationships: StairsRelationshipFeature[],\n unitOpenings: Record<string, OpeningFeature[]>,\n options: PrepareGraphOptions\n): NodeMap => {\n const t0 = performance.now()\n const { levels = [], openings = [], units = [] } = options.data\n const { baseDistance, scaleDistanceByLevel } = getDistanceOptions(options.unitDistanceOptions, 'stairs') as VerticalDistanceOptions\n\n let elevatorNodeMap: NodeMap = {}\n let counter = 0\n\n for (const relationship of elevatorLikeRelationships) {\n \n try {\n // 1. Find Opening & its level\n const {\n origin: { id: originId },\n intermediary,\n destination: { id: destinationId },\n } = relationship.properties\n\n const origin = openings.find(opening => opening.id === originId)\n if (!origin) return\n const originLevel = levels.find(level => level.id === origin.properties.level_id)\n \n const destination = openings.find(opening => opening.id === destinationId)\n const destinationOpeningAndLevel: OpeningAndLevel = {\n opening: destination,\n level: levels.find(level => level.id === destination.properties.level_id)\n }\n\n const intermediaryOpeningAndLevels: OpeningAndLevel[] = intermediary.map(unitTypeAndId => {\n const openings = unitOpenings[unitTypeAndId.id]\n const unit = units.find(unit => unit.id === unitTypeAndId.id)\n const level = levels.find(level => level.id === unit.properties.level_id)\n return openings.map(opening => ({ opening, level }))\n }).flat()\n\n // Link origin ---> [intermediary's openings, destination's openings]\n const connections: OpeningAndLevel[] = [...intermediaryOpeningAndLevels, destinationOpeningAndLevel]\n if (!origin) return\n\n for (const connection of connections) {\n const { opening, level } = connection\n let distance = baseDistance\n if (scaleDistanceByLevel) {\n const originOrdinal = originLevel.properties.ordinal\n const connectionOrdinal = level.properties.ordinal\n const levelDifference = Math.abs(originOrdinal - connectionOrdinal)\n if (levelDifference > 0) distance *= levelDifference\n }\n _.set(elevatorNodeMap, `${origin.id}.${opening.id}`, distance)\n _.set(elevatorNodeMap, `${opening.id}.${origin.id}`, distance)\n counter++\n }\n\n } catch (err) {\n console.warn(\n \"Failed to create stairNodeMap\",\n {\n relationshipId: relationship.id,\n featureType: relationship.feature_type,\n error: err instanceof Error ? err.message : err,\n stack: err instanceof Error ? err.stack : undefined,\n }\n )\n }\n }\n const t1 = performance.now()\n trace('nav', ` │ ├─ add ${counter} stairs relationships`, t1 - t0)\n\n return elevatorNodeMap\n}\n","import _ from \"lodash\"\nimport { NodeMap } from \"../type\";\nimport { OccupantFeature } from \"../../../types\";\nimport { compact } from \"../../../utils/lodash\";\nimport { trace } from \"../../../utils/trace\";\n\nexport const createOccupantNodeMap = (\n occupants: OccupantFeature[],\n): NodeMap => {\n const t0 = performance.now()\n\n let nodeMap: NodeMap = {}\n let counter = 0\n occupants.forEach(occupant => {\n const { unit_id, unit_ids = [], kiosk_id, kiosk_ids = [] } = occupant.properties\n const occupantRoomIds = compact([unit_id, ...unit_ids])\n const occupantKioskIds = compact([kiosk_id, ...kiosk_ids])\n\n // Bind Occupant <--> Unit\n for (const roomId of occupantRoomIds) {\n _.set(nodeMap, `${roomId}.${occupant.id}`, 0.001) // Super short distance\n _.set(nodeMap, `${occupant.id}.${roomId}`, 0.001) // Super short distance\n counter++\n }\n // Bind Occupant <--> kiosk\n for (const kioskId of occupantKioskIds) {\n _.set(nodeMap, `${kioskId}.${occupant.id}`, 0.001) // Super short distance\n _.set(nodeMap, `${occupant.id}.${kioskId}`, 0.001) // Super short distance\n counter++\n }\n })\n const t1 = performance.now()\n trace('nav', ` │ ├─ add ${counter} occupants relationships`, t1 - t0)\n\n return nodeMap\n}","import { center as turfCenter } from '@turf/center'\nimport { distance } from \"@turf/distance\";\nimport _ from \"lodash\"\nimport { ImdfFeature } from \"../../../types\"\nimport { NodeMap, UnitOpenings } from \"../type\"\nimport { BASE_POI_BASEDISTANCE } from '../constants';\nimport { trace } from '../../../utils/trace';\n\nexport const createPOINodeMap = (\n features: ImdfFeature[],\n getFeatureUnit: (feat: ImdfFeature) => string,\n unitOpenings: UnitOpenings,\n): NodeMap => {\n const t0 = performance.now()\n let nodeMap: NodeMap = {}\n let counter = 0\n features.forEach(feat => {\n try {\n const locatedOnUnitId = getFeatureUnit(feat)\n const openings = unitOpenings[locatedOnUnitId]\n const center = turfCenter(feat)\n for (const opening of openings) {\n try { \n const openingCenter = turfCenter(opening)\n const dis = distance(center, openingCenter, { units: 'meters' }) + BASE_POI_BASEDISTANCE\n _.set(nodeMap, `${opening.id}.${feat.id}`, dis)\n _.set(nodeMap, `${feat.id}.${opening.id}`, dis)\n counter++\n } catch (err) {\n console.log(err, opening)\n }\n }\n } catch (err) {\n console.log(err)\n console.log(`cannot connect poi to openings`, err.message, { feat })\n }\n })\n const type = features.length > 0 ? features[0].feature_type : '-'\n const t1 = performance.now()\n trace('nav', ` │ ├─ add ${counter} ${type} relationships`, t1 - t0)\n return nodeMap\n\n}","import { NodeMap } from \"../type\"\n\nexport const mergeNodeMap = (nodeMaps: NodeMap[]) => {\n const out: NodeMap = {}\n\n for (const nodeMap of nodeMaps) {\n for (const from in nodeMap) {\n out[from] = {\n ...(out[from] ?? {}),\n ...nodeMap[from],\n }\n }\n }\n\n return out\n}","import uniqBy from \"lodash/uniqBy\"\nimport { OpeningFeature, OpeningTypeAndId, TraversalRelationshipFeature, UnitFeature } from \"../../../types\"\nimport { UnitOpenings } from \"../type\"\n\nexport const createUnitOpenings = (\n relationships: TraversalRelationshipFeature[],\n units: UnitFeature[],\n openings: OpeningFeature[]\n): UnitOpenings => {\n const openingConnections: UnitOpenings = {}\n const relationshipMap: Map<string, TraversalRelationshipFeature[]> = new Map()\n\n // Preprocess relationships for quick access\n relationships.forEach((relationship) => {\n const originId = relationship.properties.origin?.id || null\n const destinationId = relationship.properties.destination?.id || null\n\n if (!relationshipMap.has(originId)) {\n relationshipMap.set(originId, [])\n }\n if (!relationshipMap.has(destinationId)) {\n relationshipMap.set(destinationId, [])\n }\n\n relationshipMap.get(originId).push(relationship)\n relationshipMap.get(destinationId).push(relationship)\n })\n // Iterate units and build connections\n units.forEach((unit) => {\n const unitId = unit.id\n const connectedRelationshop = relationshipMap.get(unitId) || []\n\n const relationshipIntermediaryTypeAndId: OpeningTypeAndId[] = connectedRelationshop.map(\n (relationship) => relationship.properties.intermediary[0] // Assuming intermediary is always an array\n )\n\n const relationshipIntermediary: OpeningFeature[] = relationshipIntermediaryTypeAndId.map(({ id }) => {\n return openings.find(opening => opening.id === id)\n })\n\n openingConnections[unitId] = uniqBy(\n [...(openingConnections[unitId] || []), ...relationshipIntermediary],\n \"id\"\n )\n })\n return openingConnections\n}","export const parseOrdinalCoordinate = (\n id: `${number},${number},${number}o`\n): [number, number, number] => {\n return id\n .slice(0, -1)\n .split(',')\n .map(Number) as [number, number, number]\n}","import _, { capitalize } from \"lodash\"\nimport _intersectionBy from \"lodash/intersectionBy\"\nimport { center } from \"@turf/center\"\n\nimport { FindByIdSync, GetNavigateClientOptions } from \"../type\"\nimport { describeHorizontalStep, describeVerticalStep } from \"../description\"\nimport { createStepPathUtils } from \"./path\"\nimport { createLandmarkUtils } from \"../landmark\"\nimport { OpeningTypeAndId, TransalatableString, UnitFeature, UnitTypeAndId } from \"../../types\"\nimport { Step, Waypoint } from \"./type\"\nimport { extractStartPoint } from \"./utils/extractStartPoint\"\nimport { extractEndPoint } from \"./utils/extractEndPint\"\nimport { findContainingUnitAtPoint } from \"../../utils/findContaining\"\nimport { trace } from \"../../utils/trace\"\nimport { combineWalkwaySteps } from \"./utils/combineWalkwaySteps\"\n\nexport type CreateStepUtilsOptions = GetNavigateClientOptions & { findByIdSync: FindByIdSync }\n\nexport const createStepUtils = (options: CreateStepUtilsOptions) => {\n const { data: { units, relationships }, findByIdSync } = options\n const landmarkUtils = createLandmarkUtils(options)\n const stepPathUtils = createStepPathUtils({ ...options, resolution: 0.00088 })\n\n const findUnitBetweenOpenings = (originId: string, destinationId: string): UnitFeature[] => {\n const origin = findByIdSync<\"opening\">(originId)\n const destination = findByIdSync<\"opening\">(destinationId)\n const matchedOne = relationships.find(rel => rel.properties.intermediary.map(int => int.id).includes(origin.id))\n const matchOneUnits = [matchedOne.properties.origin, matchedOne.properties.destination] as UnitTypeAndId[]\n const matchedTwo = relationships.find(rel => rel.properties.intermediary.map(int => int.id).includes(destination.id))\n const matchTwoUnits = [matchedTwo.properties.origin, matchedTwo.properties.destination] as UnitTypeAndId[]\n const unitIds = _intersectionBy(matchOneUnits, matchTwoUnits, 'id')\n return unitIds.map(({ id }) => findByIdSync<\"unit\">(id)) as UnitFeature[]\n }\n\n /** \n * findHorizontalIntermediary\n * if one of the source !== \"opening\", use it's containingUnit as intermediary\n * Else find intermediary between openings\n */\n const findHorizontalIntermediary = (from: Waypoint, to: Waypoint): UnitFeature[] => {\n\n if (from.source.type !== \"opening\") {\n const unit = findContainingUnitAtPoint(from.point, from.levelId, units)\n return unit ? [unit] : []\n }\n\n if (to.source.type !== \"opening\") {\n const unit = findContainingUnitAtPoint(to.point, to.levelId, units)\n return unit ? [unit] : []\n }\n \n return findUnitBetweenOpenings(from.source.id, to.source.id)\n }\n\n const findVerticalIntermediary = (from: Waypoint, to: Waypoint): UnitFeature[] => {\n const firstOpeningId = (from.source as OpeningTypeAndId).id\n const secondOpeningId = (to.source as OpeningTypeAndId).id\n const relationship = relationships.find(rel => {\n return rel.properties.origin?.id === firstOpeningId && rel.properties.destination?.id === secondOpeningId\n || rel.properties.origin?.id === secondOpeningId && rel.properties.destination?.id === firstOpeningId\n })\n const intermediaryTypeAndId = relationship.properties.intermediary\n return intermediaryTypeAndId.map(({ id }) => findByIdSync<\"unit\">(id)) as UnitFeature[]\n }\n\n const formatCategoryLabel = (category: string): string => {\n return capitalize(category)\n }\n\n /**\n * Get a user-friendly \"toward\" label for navigation instructions.\n *\n * Attempts to infer what the user is heading toward (unit or destination)\n * based on relationship context. Falls back to the destination name\n * @param to \n * @param intermediaryIds \n * @returns \n */\n const getToward = (from: Waypoint, to: Waypoint, intermediary: UnitFeature[]) => {\n if (to.type === \"end\") return to.name\n const intermediaryIds = intermediary.map(int => int.id)\n const relationship = relationships.find(rel => rel.properties.intermediary.map(int => int.id).includes((to.source as OpeningTypeAndId).id))\n if (!relationship) return to.name\n\n const candidates = [relationship.properties.origin.id, relationship.properties.destination.id]\n const nextUnitId = candidates.filter(id => !intermediaryIds.includes(id))[0]\n if (!nextUnitId) return to.name\n\n const nextUnit = findByIdSync<\"unit\">(nextUnitId)\n // If nextUnit exists, use nextUnit category as toward, else use \"to\" waypoint name\n return { en: formatCategoryLabel(`${nextUnit.properties.category}`) }\n }\n\n const toWaypoints = (path: string[]): Waypoint[] => {\n \n const [startPoint, middleAndEndPoints] = extractStartPoint(path, options)\n const [endPoint, middlePoints] = extractEndPoint(middleAndEndPoints, options)\n const waypoints: Waypoint[] = middlePoints.map(openingId => {\n const opening = findByIdSync<\"opening\">(openingId)\n const level = findByIdSync<\"level\">(opening.properties.level_id)\n const coordinates = center(opening).geometry.coordinates\n const landmark = landmarkUtils.findNearestLandmark(coordinates, opening.properties.level_id)\n return {\n id: `${opening.properties.level_id}:${openingId}`,\n type: 'between',\n point: coordinates,\n name: null,\n levelId: opening.properties.level_id,\n ordinal: level.properties.ordinal,\n hint: landmark ? { kind: 'landmark', name: landmark.name } : undefined,\n source: { type: 'opening', id: opening.id }\n }\n })\n \n return [startPoint, ...waypoints, endPoint]\n }\n\n const createHorizontalStep = (from: Waypoint, to: Waypoint): Step => {\n const intermediary: UnitFeature[] = findHorizontalIntermediary(from, to)\n const intermediaryCategories = intermediary.map(unit => unit.properties.category)\n const intermediaryCategory = intermediaryCategories.length > 0 ? intermediaryCategories[0] : 'unspecified'\n \n const toward: TransalatableString = getToward(from, to, intermediary)\n const landmark = to.hint?.kind === \"landmark\" ? to.hint.name : null\n const path = stepPathUtils.findStepPath(from.point, to.point, intermediary)\n const step = {\n from,\n to,\n levelIds: [from.levelId],\n ordinals: [from.ordinal],\n intermediaryCategory,\n description: describeHorizontalStep(intermediaryCategory, toward, landmark),\n path: path.map(coord => [...coord, from.ordinal * 9])\n }\n return step\n }\n\n const createVerticalStep = (from: Waypoint, to: Waypoint): Step => {\n const intermediary = findVerticalIntermediary(from, to)\n const intermediaryCategories = intermediary.map(unit => unit.properties.category)\n const intermediaryCategory = intermediaryCategories.length > 0 ? intermediaryCategories[0] : 'unspecified'\n const fromLevel = findByIdSync<\"level\">(from.levelId)\n const toLevel = findByIdSync<\"level\">(to.levelId)\n\n return {\n from,\n to,\n levelIds: [from.levelId, to.levelId],\n ordinals: [from.ordinal, to.ordinal],\n intermediaryCategory,\n description: describeVerticalStep(fromLevel, toLevel, intermediaryCategory),\n path: [\n [...from.point, from.ordinal * 9],\n [...to.point, to.ordinal * 9],\n ]\n }\n }\n\n const isVertical = (from: Waypoint, to: Waypoint) => {\n const fromLevel = findByIdSync<\"level\">(from.levelId)\n const toLevel = findByIdSync<\"level\">(to.levelId)\n return !!fromLevel && !!toLevel && fromLevel.properties.ordinal !== toLevel.properties.ordinal\n }\n\n const toSteps = (waypoints: Waypoint[]): Step[] => {\n let steps: Step[] = []\n const t0_allSteps = performance.now()\n for (let i = 0; i < waypoints.length - 1; i++) {\n const from: Waypoint = waypoints[i]\n const to: Waypoint = waypoints[i + 1]\n const t0 = performance.now()\n const step = isVertical(from, to) ? createVerticalStep(from, to) : createHorizontalStep(from, to)\n steps.push(step)\n const t1 = performance.now()\n trace('nav', ` │ ├─ #${i} ${from.id.padEnd(25)} → ${`(${step.intermediaryCategory})`.padEnd(12)} → ${to.id}`, t1 - t0)\n trace('nav', ` │ │ ${step.description.text}`, undefined, '#bada55')\n }\n\n // Combine multiple walkways into one walkway \n const simplifySteps = combineWalkwaySteps(steps)\n\n const t1_allSteps = performance.now()\n trace('nav', ' │ └─ Total ', t1_allSteps - t0_allSteps)\n\n\n return simplifySteps\n }\n\n return {\n // createSteps,\n toWaypoints,\n toSteps,\n }\n}","import _ from \"lodash\"\nimport { LevelFeature, TransalatableString } from \"../../types\"\nimport { StepDescription } from \"./type\"\n\ntype TranslateOptions = {\n intermediary?: string\n toward?: TransalatableString // Where user is going to?\n landmark?: TransalatableString\n}\nconst t = (template: string, locale: string, options: TranslateOptions) => {\n return template\n .replace(`{{intermediary}}`, options.intermediary ?? \"\")\n .replace(`{{toward}}`, options.toward?.[locale] ?? \"\")\n .replace(`{{landmark}}`, options.landmark?.[locale] ?? \"\")\n}\n\nexport const describeVerticalStep = (fromLevel: LevelFeature, toLevel: LevelFeature, intermediary: string) => {\n const dir = fromLevel.properties.ordinal < toLevel.properties.ordinal ? \"up\" : \"down\"\n const template = `Take the {{intermediary}} ${dir} to {{toward}}`\n return {\n template,\n text: t(template, \"en\", { intermediary, toward: toLevel.properties.name }),\n }\n}\n\n/**\n * \"To traverse\": \"Follow the path heading toward <toward>{{toward}}</toward>\",\n * \"To traverse on walkway\": \"Follow the path along the walkway\",\n * \"To traverse on walkway toward\": \"Follow the path along the walkway toward <toward>{{toward}}</toward>\",\n * \"To traverse toward\": \"Follow the path toward <toward>{{toward}}</toward>\",\n * \"To traverse toward with landmark\": \"Follow the path toward <toward>{{toward}}</toward> near <landmark>{{landmark}}</landmark>\",\n * \"To destination\": \"Head to your destination.\",\n */\n\nexport const describeHorizontalStep = (intermediary: string, toward: TransalatableString, landmark?: TransalatableString): StepDescription => {\n const template = `Follow the path ${intermediary === 'walkway' ? `along the walkway` : `through {{intermediary}}`} ${toward ? `toward {{toward}}` : ``} ${landmark ? `near {{landmark}}` : ``}`.trim()\n \n return {\n text: t(template, \"en\", { intermediary, toward, landmark }),\n template,\n }\n}\n\nexport const describeLastStep = () => {\n return {\n text: \"To destination\",\n }\n}","import _ from \"lodash\"\nimport { FixtureFeature, KioskFeature, UnitFeature } from \"../../../types\"\nimport { OBSTACLE_CATEGORIES, OBSTACLE_FEATURE_TYPES, WALKABLE_CATEGORY } from \"../../constants\"\nimport { featureCollection, polygon } from \"@turf/helpers\"\nimport { getType } from \"@turf/invariant\";\nimport difference from \"@turf/difference\"\nimport envelope from \"@turf/envelope\"\nimport booleanOverlap from \"@turf/boolean-overlap\"\nimport booleanIntersects from \"@turf/boolean-intersects\"\nimport { GetNavigateClientOptions } from \"../../type\"\nimport shortestPath from \"./turf/shortestPath\"\nimport { Feature, FeatureCollection, LineString, Polygon, Position } from \"geojson\"\n\ntype ObstacleFeature = UnitFeature | KioskFeature | FixtureFeature\n\nexport type StepPathUtils = {\n findStepPath: (\n from: Position,\n to: Position,\n intermediaries: UnitFeature[],\n // routeOrigin: NavigatableFeature,\n // routeDestination: NavigatableFeature\n ) => Position[]\n}\n\ntype FindPathOnAreaOptions = {\n obstacles: FeatureCollection<Polygon>\n resolution: number\n properties?: any\n}\n\nexport const createStepPathUtils = (options: GetNavigateClientOptions & { resolution: number }): StepPathUtils => {\n\n const resolution = options.resolution ?? 0.00088\n const { units, kiosks, fixtures } = options.data\n const possibleObstacleFeatures = [...units, ...kiosks, ...fixtures]\n\n const filterObstaclesByOrdinal = (levelId: string): ObstacleFeature[] => {\n return possibleObstacleFeatures\n .filter(({ feature_type, properties, geometry }) => {\n return properties.level_id === levelId \n && [\"Polygon\", \"MultiPolygon\"].includes(geometry.type)\n && (OBSTACLE_FEATURE_TYPES.includes(feature_type)\n || \"category\" in properties && OBSTACLE_CATEGORIES.includes(properties.category))\n })\n }\n\n const findObstaclesFromWalkway = (intermediaryUnit: UnitFeature, exceptionIds: string[] = []): FeatureCollection<Polygon> => {\n const result = featureCollection<Polygon>([])\n\n if (!intermediaryUnit) return result\n\n const walkwayLevelId = intermediaryUnit.properties.level_id\n const obstacleOnLevel = filterObstaclesByOrdinal(walkwayLevelId).filter(\n (obstacle) => !exceptionIds.includes(obstacle.id)\n )\n\n const relatedObstacleWithIntermediary = obstacleOnLevel.reduce(\n (obstacles, feature) => {\n if (\n // Prevent detecting itself as an obstacle\n // Ex. Unable to draw a line to amenity located with in a room as room is also consider as obstacle\n feature.id !== intermediaryUnit.id &&\n (booleanOverlap(intermediaryUnit, feature) ||\n booleanIntersects(intermediaryUnit, feature))\n ) {\n const polygons = getType(feature) === 'Polygon' \n ? [polygon(feature.geometry.coordinates as Position[][], { id: feature.id })]\n : feature.geometry.coordinates.map(ring => polygon(ring as Position[][], { id: feature.id }))\n obstacles.push(...polygons)\n }\n return obstacles\n },\n []\n )\n\n const intermediaryExtends = envelope(intermediaryUnit)\n const walkwayPerimeter = difference(\n featureCollection([intermediaryExtends, intermediaryUnit])\n ) as Feature<Polygon>\n\n result.features.push(...relatedObstacleWithIntermediary, walkwayPerimeter)\n return result\n }\n\n const findPathOnArea = (originPoint, destinationPoint, options?: FindPathOnAreaOptions) => {\n const { obstacles = featureCollection([]), resolution, properties } = options || {}\n const stepPath = shortestPath(originPoint, destinationPoint, {\n obstacles,\n smoothenPath: false,\n resolution,\n })\n \n stepPath.properties = properties\n\n return stepPath\n }\n\n const findStepPath = (\n from: Position,\n to: Position,\n intermediaries: UnitFeature[],\n ): Position[] => {\n const t0 = performance.now();\n\n // find the walkway relates the step's opening\n const relatedWalkablePlatform = intermediaries.find((feature) =>\n WALKABLE_CATEGORY.includes(feature.properties.category)\n )\n // TODO: Temporary solution as an urgent fix may be this should be fix later\n const exceptionFeatureIds = []\n \n // find obstacles from the unit relates the walkway and the kiosk on target level\n const obstacles = findObstaclesFromWalkway(\n relatedWalkablePlatform,\n _.compact(exceptionFeatureIds)\n )\n\n const line = findPathOnArea(from, to, {\n resolution,\n obstacles,\n })\n\n // find path and return LineString\n return line.geometry.coordinates\n }\n\n return {\n findStepPath\n }\n}","export const ESCALATOR_DISTANCE = 200\nexport const RAMP_DISTANCE = 200\nexport const ELEVATOR_DISTANCE = 500\nexport const STAIR_DISTANCE = 999999\nexport const STAIR_EMERGENCYEXIT_DISTANCE = 1000000\nexport const BASE_POI_DISTANCE = 9999999\n\nexport const OBSTACLE_FEATURE_TYPES = [\"kiosk\" /* , \"fixture\" */]\nexport const OBSTACLE_CATEGORIES = [\n \"fixture.water\",\n \"fixture.stage\",\n \"nonpublic\",\n \"opentobelow\",\n \"elevator\",\n \"escalator\",\n \"stairs\",\n \"stairs.emergencyexit\",\n \"room\",\n \"unspecified\",\n \"structure\",\n \"brick\",\n \"concrete\",\n \"drywall\",\n \"glass\",\n \"wood\",\n \"column\",\n]\n// Walkable category should be further update in the future\nexport const WALKABLE_CATEGORY = [\n \"walkway\",\n \"parking\",\n \"room\",\n \"terrace\",\n \"unenclosedarea\",\n \"vegetation\",\n \"unspecified\",\n]\n\n\nexport const VERTICAL_TRAVERSAL_CATEGORY = [\n \"elevator\",\n \"escalator\",\n \"stairs\",\n \"stairs.emergencyexit\",\n \"ramp\",\n]","import {\n BBox,\n Feature,\n FeatureCollection,\n Geometry,\n GeometryCollection,\n GeometryObject,\n LineString,\n MultiLineString,\n MultiPoint,\n MultiPolygon,\n Point,\n Polygon,\n Position,\n GeoJsonProperties,\n} from \"geojson\";\n\nimport { Id } from \"./lib/geojson.js\";\nexport * from \"./lib/geojson.js\";\n\n/**\n * @module helpers\n */\n\n// TurfJS Combined Types\nexport type Coord = Feature<Point> | Point | Position;\n\n/**\n * Linear measurement units.\n *\n * ⚠️ Warning. Be aware of the implications of using radian or degree units to\n * measure distance. The distance represented by a degree of longitude *varies*\n * depending on latitude.\n *\n * See https://www.thoughtco.com/degree-of-latitude-and-longitude-distance-4070616\n * for an illustration of this behaviour.\n *\n * @typedef\n */\nexport type Units =\n | \"meters\"\n | \"metres\"\n | \"millimeters\"\n | \"millimetres\"\n | \"centimeters\"\n | \"centimetres\"\n | \"kilometers\"\n | \"kilometres\"\n | \"miles\"\n | \"nauticalmiles\"\n | \"inches\"\n | \"yards\"\n | \"feet\"\n | \"radians\"\n | \"degrees\";\n\n/**\n * Area measurement units.\n *\n * @typedef\n */\nexport type AreaUnits =\n | Exclude<Units, \"radians\" | \"degrees\">\n | \"acres\"\n | \"hectares\";\n\n/**\n * Grid types.\n *\n * @typedef\n */\nexport type Grid = \"point\" | \"square\" | \"hex\" | \"triangle\";\n\n/**\n * Shorthand corner identifiers.\n *\n * @typedef\n */\nexport type Corners = \"sw\" | \"se\" | \"nw\" | \"ne\" | \"center\" | \"centroid\";\n\n/**\n * Geometries made up of lines i.e. lines and polygons.\n *\n * @typedef\n */\nexport type Lines = LineString | MultiLineString | Polygon | MultiPolygon;\n\n/**\n * Convenience type for all possible GeoJSON.\n *\n * @typedef\n */\nexport type AllGeoJSON =\n | Feature\n | FeatureCollection\n | Geometry\n | GeometryCollection;\n\n/**\n * The Earth radius in meters. Used by Turf modules that model the Earth as a sphere. The {@link https://en.wikipedia.org/wiki/Earth_radius#Arithmetic_mean_radius mean radius} was selected because it is {@link https://rosettacode.org/wiki/Haversine_formula#:~:text=This%20value%20is%20recommended recommended } by the Haversine formula (used by turf/distance) to reduce error.\n *\n * @constant\n */\nexport const earthRadius = 6371008.8;\n\n/**\n * Unit of measurement factors based on earthRadius.\n *\n * Keys are the name of the unit, values are the number of that unit in a single radian\n *\n * @constant\n */\nexport const factors: Record<Units, number> = {\n centimeters: earthRadius * 100,\n centimetres: earthRadius * 100,\n degrees: 360 / (2 * Math.PI),\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/**\n\n * Area of measurement factors based on 1 square meter.\n *\n * @constant\n */\nexport const areaFactors: Record<AreaUnits, number> = {\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 nauticalmiles: 2.9155334959812285e-7,\n millimeters: 1000000,\n millimetres: 1000000,\n yards: 1.195990046,\n};\n\n/**\n * Wraps a GeoJSON {@link Geometry} in a GeoJSON {@link Feature}.\n *\n * @function\n * @param {GeometryObject} geometry input geometry\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryObject, GeoJsonProperties>} 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<\n G extends GeometryObject = Geometry,\n P extends GeoJsonProperties = GeoJsonProperties,\n>(\n geom: G | null,\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<G, P> {\n const feat: any = { 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/**\n * Creates a GeoJSON {@link Geometry} from a Geometry string type & coordinates.\n * For GeometryCollection type use `helpers.geometryCollection`\n *\n * @function\n * @param {(\"Point\" | \"LineString\" | \"Polygon\" | \"MultiPoint\" | \"MultiLineString\" | \"MultiPolygon\")} 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<\n T extends\n | \"Point\"\n | \"LineString\"\n | \"Polygon\"\n | \"MultiPoint\"\n | \"MultiLineString\"\n | \"MultiPolygon\",\n>(\n type: T,\n coordinates: any[],\n _options: Record<string, never> = {}\n): Extract<Geometry, { type: T }> {\n switch (type) {\n case \"Point\":\n return point(coordinates).geometry as Extract<Geometry, { type: T }>;\n case \"LineString\":\n return lineString(coordinates).geometry as Extract<Geometry, { type: T }>;\n case \"Polygon\":\n return polygon(coordinates).geometry as Extract<Geometry, { type: T }>;\n case \"MultiPoint\":\n return multiPoint(coordinates).geometry as Extract<Geometry, { type: T }>;\n case \"MultiLineString\":\n return multiLineString(coordinates).geometry as Extract<\n Geometry,\n { type: T }\n >;\n case \"MultiPolygon\":\n return multiPolygon(coordinates).geometry as Extract<\n Geometry,\n { type: T }\n >;\n default:\n throw new Error(type + \" is invalid\");\n }\n}\n\n/**\n * Creates a {@link Point} {@link Feature} from a Position.\n *\n * @function\n * @param {Position} coordinates longitude, latitude position (each in decimal degrees)\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<Point, GeoJsonProperties>} a Point feature\n * @example\n * var point = turf.point([-75.343, 39.984]);\n *\n * //=point\n */\nexport function point<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position,\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<Point, P> {\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\n const geom: Point = {\n type: \"Point\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a {@link Point} {@link FeatureCollection} from an Array of Point coordinates.\n *\n * @function\n * @param {Position[]} coordinates an array of Points\n * @param {GeoJsonProperties} [properties={}] Translate these properties to each Feature\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {Id} [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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): FeatureCollection<Point, P> {\n return featureCollection(\n coordinates.map((coords) => {\n return point(coords, properties);\n }),\n options\n );\n}\n\n/**\n * Creates a {@link Polygon} {@link Feature} from an Array of LinearRings.\n *\n * @function\n * @param {Position[][]} coordinates an array of LinearRings\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<Polygon, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[][],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<Polygon, P> {\n for (const ring of coordinates) {\n if (ring.length < 4) {\n throw new Error(\n \"Each LinearRing of a Polygon must have 4 or more Positions.\"\n );\n }\n\n if (ring[ring.length - 1].length !== ring[0].length) {\n throw new Error(\"First and last Position are not equivalent.\");\n }\n\n for (let 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 const geom: Polygon = {\n type: \"Polygon\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a {@link Polygon} {@link FeatureCollection} from an Array of Polygon coordinates.\n *\n * @function\n * @param {Position[][][]} coordinates an array of Polygon coordinates\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<Polygon, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[][][],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): FeatureCollection<Polygon, P> {\n return featureCollection(\n coordinates.map((coords) => {\n return polygon(coords, properties);\n }),\n options\n );\n}\n\n/**\n * Creates a {@link LineString} {@link Feature} from an Array of Positions.\n *\n * @function\n * @param {Position[]} coordinates an array of Positions\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<LineString, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<LineString, P> {\n if (coordinates.length < 2) {\n throw new Error(\"coordinates must be an array of two or more positions\");\n }\n const geom: LineString = {\n type: \"LineString\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a {@link LineString} {@link FeatureCollection} from an Array of LineString coordinates.\n *\n * @function\n * @param {Position[][]} coordinates an array of LinearRings\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north]\n * associated with the FeatureCollection\n * @param {Id} [options.id] Identifier associated with the FeatureCollection\n * @returns {FeatureCollection<LineString, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[][],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): FeatureCollection<LineString, P> {\n return featureCollection(\n coordinates.map((coords) => {\n return lineString(coords, properties);\n }),\n options\n );\n}\n\n/**\n * Takes one or more {@link Feature|Features} and creates a {@link FeatureCollection}.\n *\n * @function\n * @param {Array<Feature<GeometryObject, GeoJsonProperties>>} features input features\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {FeatureCollection<GeometryObject, GeoJsonProperties>} 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<\n G extends GeometryObject = Geometry,\n P extends GeoJsonProperties = GeoJsonProperties,\n>(\n features: Array<Feature<G, P>>,\n options: { bbox?: BBox; id?: Id } = {}\n): FeatureCollection<G, P> {\n const fc: any = { 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/**\n * Creates a {@link Feature}<{@link MultiLineString}> based on a\n * coordinate array. Properties can be added optionally.\n *\n * @function\n * @param {Position[][]} coordinates an array of LineStrings\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiLineString, GeoJsonProperties>} 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<\n P extends GeoJsonProperties = GeoJsonProperties,\n>(\n coordinates: Position[][],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<MultiLineString, P> {\n const geom: MultiLineString = {\n type: \"MultiLineString\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a {@link Feature}<{@link MultiPoint}> based on a\n * coordinate array. Properties can be added optionally.\n *\n * @function\n * @param {Position[]} coordinates an array of Positions\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPoint, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<MultiPoint, P> {\n const geom: MultiPoint = {\n type: \"MultiPoint\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a {@link Feature}<{@link MultiPolygon}> based on a\n * coordinate array. Properties can be added optionally.\n *\n * @function\n * @param {Position[][][]} coordinates an array of Polygons\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<MultiPolygon, GeoJsonProperties>} 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<P extends GeoJsonProperties = GeoJsonProperties>(\n coordinates: Position[][][],\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<MultiPolygon, P> {\n const geom: MultiPolygon = {\n type: \"MultiPolygon\",\n coordinates,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Creates a Feature<GeometryCollection> based on a\n * coordinate array. Properties can be added optionally.\n *\n * @function\n * @param {Array<Point | LineString | Polygon | MultiPoint | MultiLineString | MultiPolygon>} geometries an array of GeoJSON Geometries\n * @param {GeoJsonProperties} [properties={}] an Object of key-value pairs to add as properties\n * @param {Object} [options={}] Optional Parameters\n * @param {BBox} [options.bbox] Bounding Box Array [west, south, east, north] associated with the Feature\n * @param {Id} [options.id] Identifier associated with the Feature\n * @returns {Feature<GeometryCollection, GeoJsonProperties>} 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<\n G extends\n | Point\n | LineString\n | Polygon\n | MultiPoint\n | MultiLineString\n | MultiPolygon,\n P extends GeoJsonProperties = GeoJsonProperties,\n>(\n geometries: Array<G>,\n properties?: P,\n options: { bbox?: BBox; id?: Id } = {}\n): Feature<GeometryCollection<G>, P> {\n const geom: GeometryCollection<G> = {\n type: \"GeometryCollection\",\n geometries,\n };\n return feature(geom, properties, options);\n}\n\n/**\n * Round number to precision\n *\n * @function\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: number, precision = 0): number {\n if (precision && !(precision >= 0)) {\n throw new Error(\"precision must be a positive number\");\n }\n const 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 * @function\n * @param {number} radians in radians across the sphere\n * @param {Units} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} distance\n */\nexport function radiansToLength(\n radians: number,\n units: Units = \"kilometers\"\n): number {\n const factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\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 * @function\n * @param {number} distance in real units\n * @param {Units} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} radians\n */\nexport function lengthToRadians(\n distance: number,\n units: Units = \"kilometers\"\n): number {\n const factor = factors[units];\n if (!factor) {\n throw new Error(units + \" units is invalid\");\n }\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 * @function\n * @param {number} distance in real units\n * @param {Units} [units=\"kilometers\"] can be degrees, radians, miles, inches, yards, metres,\n * meters, kilometres, kilometers.\n * @returns {number} degrees\n */\nexport function lengthToDegrees(distance: number, units?: Units): number {\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 * @function\n * @param {number} bearing angle, between -180 and +180 degrees\n * @returns {number} angle between 0 and 360 degrees\n */\nexport function bearingToAzimuth(bearing: number): number {\n let angle = bearing % 360;\n if (angle < 0) {\n angle += 360;\n }\n return angle;\n}\n\n/**\n * Converts any azimuth angle from the north line direction (positive clockwise)\n * and returns an angle between -180 and +180 degrees (positive clockwise), 0 being the north line\n *\n * @function\n * @param {number} angle between 0 and 360 degrees\n * @returns {number} bearing between -180 and +180 degrees\n */\nexport function azimuthToBearing(angle: number): number {\n // Ignore full revolutions (multiples of 360)\n angle = angle % 360;\n\n if (angle > 180) {\n return angle - 360;\n } else if (angle < -180) {\n return angle + 360;\n }\n\n return angle;\n}\n\n/**\n * Converts an angle in radians to degrees\n *\n * @function\n * @param {number} radians angle in radians\n * @returns {number} degrees between 0 and 360 degrees\n */\nexport function radiansToDegrees(radians: number): number {\n // % (2 * Math.PI) radians in case someone passes value > 2π\n const normalisedRadians = radians % (2 * Math.PI);\n return (normalisedRadians * 180) / Math.PI;\n}\n\n/**\n * Converts an angle in degrees to radians\n *\n * @function\n * @param {number} degrees angle between 0 and 360 degrees\n * @returns {number} angle in radians\n */\nexport function degreesToRadians(degrees: number): number {\n // % 360 degrees in case someone passes value > 360\n const normalisedDegrees = degrees % 360;\n return (normalisedDegrees * Math.PI) / 180;\n}\n\n/**\n * Converts a length from one unit to another.\n *\n * @function\n * @param {number} length Length to be converted\n * @param {Units} [originalUnit=\"kilometers\"] Input length unit\n * @param {Units} [finalUnit=\"kilometers\"] Returned length unit\n * @returns {number} The converted length\n */\nexport function convertLength(\n length: number,\n originalUnit: Units = \"kilometers\",\n finalUnit: Units = \"kilometers\"\n): number {\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/**\n * Converts an area from one unit to another.\n *\n * @function\n * @param {number} area Area to be converted\n * @param {AreaUnits} [originalUnit=\"meters\"] Input area unit\n * @param {AreaUnits} [finalUnit=\"kilometers\"] Returned area unit\n * @returns {number} The converted length\n */\nexport function convertArea(\n area: number,\n originalUnit: AreaUnits = \"meters\",\n finalUnit: AreaUnits = \"kilometers\"\n): number {\n if (!(area >= 0)) {\n throw new Error(\"area must be a positive number\");\n }\n\n const startFactor = areaFactors[originalUnit];\n if (!startFactor) {\n throw new Error(\"invalid original units\");\n }\n\n const finalFactor = areaFactors[finalUnit];\n if (!finalFactor) {\n throw new Error(\"invalid final units\");\n }\n\n return (area / startFactor) * finalFactor;\n}\n\n/**\n * isNumber\n *\n * @function\n * @param {any} 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: any): boolean {\n return !isNaN(num) && num !== null && !Array.isArray(num);\n}\n\n/**\n * isObject\n *\n * @function\n * @param {any} input variable to validate\n * @returns {boolean} true/false, including false for Arrays and Functions\n * @example\n * turf.isObject({elevation: 10})\n * //=true\n * turf.isObject('foo')\n * //=false\n */\nexport function isObject(input: any): boolean {\n return input !== null && typeof input === \"object\" && !Array.isArray(input);\n}\n\n/**\n * Validate BBox\n *\n * @private\n * @param {any} 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: any): void {\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((num) => {\n if (!isNumber(num)) {\n throw new Error(\"bbox must only contain numbers\");\n }\n });\n}\n\n/**\n * Validate Id\n *\n * @private\n * @param {any} 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: any): void {\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","import {\n Feature,\n FeatureCollection,\n Geometry,\n LineString,\n MultiPoint,\n MultiLineString,\n MultiPolygon,\n Point,\n Polygon,\n} from \"geojson\";\nimport { isNumber } from \"@turf/helpers\";\n\n/**\n * Unwrap a coordinate from a Point Feature, Geometry or a single coordinate.\n *\n * @function\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: Feature<Point> | Point | number[]): number[] {\n if (!coord) {\n throw new Error(\"coord is required\");\n }\n\n if (!Array.isArray(coord)) {\n if (\n coord.type === \"Feature\" &&\n coord.geometry !== null &&\n coord.geometry.type === \"Point\"\n ) {\n return [...coord.geometry.coordinates];\n }\n if (coord.type === \"Point\") {\n return [...coord.coordinates];\n }\n }\n if (\n Array.isArray(coord) &&\n coord.length >= 2 &&\n !Array.isArray(coord[0]) &&\n !Array.isArray(coord[1])\n ) {\n return [...coord];\n }\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 * @function\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<\n G extends\n | Point\n | LineString\n | Polygon\n | MultiPoint\n | MultiLineString\n | MultiPolygon,\n>(coords: any[] | Feature<G> | G): any[] {\n if (Array.isArray(coords)) {\n return coords;\n }\n\n // Feature\n if (coords.type === \"Feature\") {\n if (coords.geometry !== null) {\n return coords.geometry.coordinates;\n }\n } else {\n // Geometry\n if (coords.coordinates) {\n return coords.coordinates;\n }\n }\n\n throw new Error(\n \"coords must be GeoJSON Feature, Geometry Object or an Array\"\n );\n}\n\n/**\n * Checks if coordinates contains a number\n *\n * @function\n * @param {Array<any>} coordinates GeoJSON Coordinates\n * @returns {boolean} true if Array contains a number\n */\nfunction containsNumber(coordinates: any[]): boolean {\n if (\n coordinates.length > 1 &&\n isNumber(coordinates[0]) &&\n isNumber(coordinates[1])\n ) {\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 * @function\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: any, type: string, name: string): void {\n if (!type || !name) {\n throw new Error(\"type and name required\");\n }\n\n if (!value || value.type !== type) {\n throw new Error(\n \"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n value.type\n );\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 * @function\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: Feature<any>, type: string, name: string): void {\n if (!feature) {\n throw new Error(\"No feature passed\");\n }\n if (!name) {\n throw new Error(\".featureOf() requires a name\");\n }\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\n throw new Error(\n \"Invalid input to \" + name + \", Feature with geometry required\"\n );\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error(\n \"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n feature.geometry.type\n );\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 * @function\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(\n featureCollection: FeatureCollection<any>,\n type: string,\n name: string\n) {\n if (!featureCollection) {\n throw new Error(\"No featureCollection passed\");\n }\n if (!name) {\n throw new Error(\".collectionOf() requires a name\");\n }\n if (!featureCollection || featureCollection.type !== \"FeatureCollection\") {\n throw new Error(\n \"Invalid input to \" + name + \", FeatureCollection required\"\n );\n }\n for (const feature of featureCollection.features) {\n if (!feature || feature.type !== \"Feature\" || !feature.geometry) {\n throw new Error(\n \"Invalid input to \" + name + \", Feature with geometry required\"\n );\n }\n if (!feature.geometry || feature.geometry.type !== type) {\n throw new Error(\n \"Invalid input to \" +\n name +\n \": must be a \" +\n type +\n \", given \" +\n feature.geometry.type\n );\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<G extends Geometry>(geojson: Feature<G> | G): G {\n if (geojson.type === \"Feature\") {\n return geojson.geometry;\n }\n return geojson;\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 (unused)\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(\n geojson: Feature<any> | FeatureCollection<any> | Geometry,\n _name?: string\n): string {\n if (geojson.type === \"FeatureCollection\") {\n return \"FeatureCollection\";\n }\n if (geojson.type === \"GeometryCollection\") {\n return \"GeometryCollection\";\n }\n if (geojson.type === \"Feature\" && geojson.geometry !== null) {\n return geojson.geometry.type;\n }\n return geojson.type;\n}\n\nexport {\n getCoord,\n getCoords,\n containsNumber,\n geojsonType,\n featureOf,\n collectionOf,\n getGeom,\n getType,\n};\n// No default export!\n","import { feature, point, lineString, isObject } from \"@turf/helpers\";\n\n/**\n * Callback for coordEach\n *\n * @callback coordEachCallback\n * @param {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 * @returns {void}\n */\n\n/**\n * Iterate over coordinates in any GeoJSON object, similar to Array.forEach()\n *\n * @function\n * @param {AllGeoJSON} geojson any GeoJSON object\n * @param {coordEachCallback} 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,\n k,\n l,\n geometry,\n stopG,\n 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\n ? geojson.features[featureIndex].geometry\n : isFeature\n ? geojson.geometry\n : geojson;\n isGeometryCollection = geometryMaybeCollection\n ? geometryMaybeCollection.type === \"GeometryCollection\"\n : false;\n stopG = isGeometryCollection\n ? geometryMaybeCollection.geometries.length\n : 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]\n : 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 =\n excludeWrapCoord &&\n (geomType === \"Polygon\" || geomType === \"MultiPolygon\")\n ? 1\n : 0;\n\n switch (geomType) {\n case null:\n break;\n case \"Point\":\n if (\n callback(\n coords,\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n return false;\n coordIndex++;\n multiFeatureIndex++;\n break;\n case \"LineString\":\n case \"MultiPoint\":\n for (j = 0; j < coords.length; j++) {\n if (\n callback(\n coords[j],\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n 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 (\n callback(\n coords[j][k],\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n 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 geometryIndex = 0;\n for (k = 0; k < coords[j].length; k++) {\n for (l = 0; l < coords[j][k].length - wrapShrink; l++) {\n if (\n callback(\n coords[j][k][l],\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n 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 (\n coordEach(geometry.geometries[j], callback, excludeWrapCoord) ===\n false\n )\n 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 {Reducer} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {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 * @returns {Reducer}\n */\n\n/**\n * Reduce coordinates in any GeoJSON object, similar to Array.reduce()\n *\n * @function\n * @param {AllGeoJSON} geojson any GeoJSON object\n * @param {coordReduceCallback} callback a method that takes (previousValue, currentCoord, coordIndex)\n * @param {Reducer} [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 {Reducer} 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(\n geojson,\n function (\n currentCoord,\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) {\n if (coordIndex === 0 && initialValue === undefined)\n previousValue = currentCoord;\n else\n previousValue = callback(\n previousValue,\n currentCoord,\n coordIndex,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n );\n },\n excludeWrapCoord\n );\n return previousValue;\n}\n\n/**\n * Callback for propEach\n *\n * @callback propEachCallback\n * @param {GeoJsonProperties} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @returns {void}\n */\n\n/**\n * Iterate over properties in any GeoJSON object, similar to Array.forEach()\n *\n * @function\n * @param {FeatureCollection|Feature} geojson any GeoJSON object\n * @param {propEachCallback} 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 * 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 {Reducer} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {GeoJsonProperties} currentProperties The current Properties being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @returns {Reducer}\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 * @function\n * @param {FeatureCollection|Feature|Geometry} geojson any GeoJSON object\n * @param {propReduceCallback} callback a method that takes (previousValue, currentProperties, featureIndex)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer} 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)\n previousValue = currentProperties;\n else\n 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 * @returns {void}\n */\n\n/**\n * Iterate over features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @function\n * @param {FeatureCollection|Feature|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {featureEachCallback} 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 {Reducer} 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 * @returns {Reducer}\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @function\n * @param {FeatureCollection|Feature|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {featureReduceCallback} callback a method that takes (previousValue, currentFeature, featureIndex)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer} 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)\n 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 * @function\n * @param {AllGeoJSON} 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 {GeometryObject} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {GeoJsonProperties} featureProperties The current Feature Properties being processed.\n * @param {BBox} featureBBox The current Feature BBox being processed.\n * @param {Id} featureId The current Feature Id being processed.\n * @returns {void}\n */\n\n/**\n * Iterate over each geometry in any GeoJSON object, similar to Array.forEach()\n *\n * @function\n * @param {FeatureCollection|Feature|Geometry|GeometryObject|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {geomEachCallback} 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,\n j,\n g,\n geometry,\n 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 geometryMaybeCollection = isFeatureCollection\n ? geojson.features[i].geometry\n : isFeature\n ? geojson.geometry\n : geojson;\n featureProperties = isFeatureCollection\n ? geojson.features[i].properties\n : isFeature\n ? geojson.properties\n : {};\n featureBBox = isFeatureCollection\n ? geojson.features[i].bbox\n : isFeature\n ? geojson.bbox\n : undefined;\n featureId = isFeatureCollection\n ? geojson.features[i].id\n : isFeature\n ? geojson.id\n : undefined;\n isGeometryCollection = geometryMaybeCollection\n ? geometryMaybeCollection.type === \"GeometryCollection\"\n : false;\n stopG = isGeometryCollection\n ? geometryMaybeCollection.geometries.length\n : 1;\n\n for (g = 0; g < stopG; g++) {\n geometry = isGeometryCollection\n ? geometryMaybeCollection.geometries[g]\n : geometryMaybeCollection;\n\n // Handle null Geometry\n if (geometry === null) {\n if (\n callback(\n null,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) === false\n )\n 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 (\n callback(\n geometry,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) === false\n )\n return false;\n break;\n }\n case \"GeometryCollection\": {\n for (j = 0; j < geometry.geometries.length; j++) {\n if (\n callback(\n geometry.geometries[j],\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) === false\n )\n 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 {Reducer} previousValue The accumulated value previously returned in the last invocation\n * of the callback, or initialValue, if supplied.\n * @param {GeometryObject} currentGeometry The current Geometry being processed.\n * @param {number} featureIndex The current index of the Feature being processed.\n * @param {GeoJsonProperties} featureProperties The current Feature Properties being processed.\n * @param {BBox} featureBBox The current Feature BBox being processed.\n * @param {Id} featureId The current Feature Id being processed.\n * @returns {Reducer}\n */\n\n/**\n * Reduce geometry in any GeoJSON object, similar to Array.reduce().\n *\n * @function\n * @param {FeatureCollection|Feature|GeometryObject|GeometryCollection|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {geomReduceCallback} callback a method that takes (previousValue, currentGeometry, featureIndex, featureProperties, featureBBox, featureId)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer} 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(\n geojson,\n function (\n currentGeometry,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n ) {\n if (featureIndex === 0 && initialValue === undefined)\n previousValue = currentGeometry;\n else\n previousValue = callback(\n previousValue,\n currentGeometry,\n featureIndex,\n featureProperties,\n featureBBox,\n featureId\n );\n }\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 * @returns {void}\n */\n\n/**\n * Iterate over flattened features in any GeoJSON object, similar to\n * Array.forEach.\n *\n * @function\n * @param {FeatureCollection|Feature|GeometryObject|GeometryCollection|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {flattenEachCallback} callback a method that takes (currentFeature, featureIndex, multiFeatureIndex)\n * @returns {void}\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 (\n callback(\n feature(geometry, properties, { bbox: bbox, id: id }),\n featureIndex,\n 0\n ) === false\n )\n 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 (\n var multiFeatureIndex = 0;\n multiFeatureIndex < geometry.coordinates.length;\n multiFeatureIndex++\n ) {\n var coordinate = geometry.coordinates[multiFeatureIndex];\n var geom = {\n type: geomType,\n coordinates: coordinate,\n };\n if (\n callback(feature(geom, properties), featureIndex, multiFeatureIndex) ===\n false\n )\n 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 {Reducer} 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 * @returns {Reducer}\n */\n\n/**\n * Reduce flattened features in any GeoJSON object, similar to Array.reduce().\n *\n * @function\n * @param {FeatureCollection|Feature|GeometryObject|GeometryCollection|Feature<GeometryCollection>} geojson any GeoJSON object\n * @param {flattenReduceCallback} callback a method that takes (previousValue, currentFeature, featureIndex, multiFeatureIndex)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer} 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(\n geojson,\n function (currentFeature, featureIndex, multiFeatureIndex) {\n if (\n featureIndex === 0 &&\n multiFeatureIndex === 0 &&\n initialValue === undefined\n )\n previousValue = currentFeature;\n else\n previousValue = callback(\n previousValue,\n currentFeature,\n featureIndex,\n multiFeatureIndex\n );\n }\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 {AllGeoJSON} geojson any GeoJSON\n * @param {segmentEachCallback} 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, featureIndex, multiFeatureIndex) {\n var segmentIndex = 0;\n\n // Exclude null Geometries\n if (!feature.geometry) return;\n // (Multi)Point geometries do not contain segments therefore they are ignored during this operation.\n var type = feature.geometry.type;\n if (type === \"Point\" || type === \"MultiPoint\") return;\n\n // Generate 2-vertex line segments\n var previousCoords;\n var previousFeatureIndex = 0;\n var previousMultiIndex = 0;\n var prevGeomIndex = 0;\n if (\n coordEach(\n feature,\n function (\n currentCoord,\n coordIndex,\n featureIndexCoord,\n multiPartIndexCoord,\n geometryIndex\n ) {\n // Simulating a meta.coordReduce() since `reduce` operations cannot be stopped by returning `false`\n if (\n previousCoords === undefined ||\n featureIndex > previousFeatureIndex ||\n multiPartIndexCoord > previousMultiIndex ||\n geometryIndex > prevGeomIndex\n ) {\n previousCoords = currentCoord;\n previousFeatureIndex = featureIndex;\n previousMultiIndex = multiPartIndexCoord;\n prevGeomIndex = geometryIndex;\n segmentIndex = 0;\n return;\n }\n var currentSegment = lineString(\n [previousCoords, currentCoord],\n feature.properties\n );\n if (\n callback(\n currentSegment,\n featureIndex,\n multiFeatureIndex,\n geometryIndex,\n segmentIndex\n ) === false\n )\n return false;\n segmentIndex++;\n previousCoords = currentCoord;\n }\n ) === false\n )\n 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 {Reducer} 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 * @returns {Reducer}\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 {segmentReduceCallback} callback a method that takes (previousValue, currentSegment, currentIndex)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer}\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 * //= segmentIndex\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(\n geojson,\n function (\n currentSegment,\n featureIndex,\n multiFeatureIndex,\n geometryIndex,\n segmentIndex\n ) {\n if (started === false && initialValue === undefined)\n previousValue = currentSegment;\n else\n previousValue = callback(\n previousValue,\n currentSegment,\n featureIndex,\n multiFeatureIndex,\n geometryIndex,\n segmentIndex\n );\n started = true;\n }\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 * @returns {void}\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 * @function\n * @param {FeatureCollection<Lines>|Feature<Lines>|Lines|Feature<GeometryCollection>|GeometryCollection} geojson object\n * @param {lineEachCallback} callback a method that takes (currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @returns {void}\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, featureIndex, multiFeatureIndex) {\n if (feature.geometry === null) return;\n var type = feature.geometry.type;\n var coords = feature.geometry.coordinates;\n switch (type) {\n case \"LineString\":\n if (callback(feature, featureIndex, multiFeatureIndex, 0, 0) === false)\n return false;\n break;\n case \"Polygon\":\n for (\n var geometryIndex = 0;\n geometryIndex < coords.length;\n geometryIndex++\n ) {\n if (\n callback(\n lineString(coords[geometryIndex], feature.properties),\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n ) === false\n )\n 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 {Reducer} 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 * @returns {Reducer}\n */\n\n/**\n * Reduce features in any GeoJSON object, similar to Array.reduce().\n *\n * @function\n * @param {FeatureCollection<Lines>|Feature<Lines>|Lines|Feature<GeometryCollection>|GeometryCollection} geojson object\n * @param {Function} callback a method that takes (previousValue, currentLine, featureIndex, multiFeatureIndex, geometryIndex)\n * @param {Reducer} [initialValue] Value to use as the first argument to the first call of the callback.\n * @returns {Reducer} 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(\n geojson,\n function (currentLine, featureIndex, multiFeatureIndex, geometryIndex) {\n if (featureIndex === 0 && initialValue === undefined)\n previousValue = currentLine;\n else\n previousValue = callback(\n previousValue,\n currentLine,\n featureIndex,\n multiFeatureIndex,\n geometryIndex\n );\n }\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)\n 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(\n [coords[segmentIndex], coords[segmentIndex + 1]],\n properties,\n options\n );\n case \"Polygon\":\n if (geometryIndex < 0) geometryIndex = coords.length + geometryIndex;\n if (segmentIndex < 0)\n segmentIndex = coords[geometryIndex].length + segmentIndex - 1;\n return lineString(\n [\n coords[geometryIndex][segmentIndex],\n coords[geometryIndex][segmentIndex + 1],\n ],\n properties,\n options\n );\n case \"MultiLineString\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (segmentIndex < 0)\n segmentIndex = coords[multiFeatureIndex].length + segmentIndex - 1;\n return lineString(\n [\n coords[multiFeatureIndex][segmentIndex],\n coords[multiFeatureIndex][segmentIndex + 1],\n ],\n properties,\n options\n );\n case \"MultiPolygon\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0)\n geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (segmentIndex < 0)\n segmentIndex =\n coords[multiFeatureIndex][geometryIndex].length - segmentIndex - 1;\n return lineString(\n [\n coords[multiFeatureIndex][geometryIndex][segmentIndex],\n coords[multiFeatureIndex][geometryIndex][segmentIndex + 1],\n ],\n properties,\n options\n );\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)\n 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)\n 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)\n coordIndex = coords[geometryIndex].length + coordIndex;\n return point(coords[geometryIndex][coordIndex], properties, options);\n case \"MultiLineString\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (coordIndex < 0)\n coordIndex = coords[multiFeatureIndex].length + coordIndex;\n return point(coords[multiFeatureIndex][coordIndex], properties, options);\n case \"MultiPolygon\":\n if (multiFeatureIndex < 0)\n multiFeatureIndex = coords.length + multiFeatureIndex;\n if (geometryIndex < 0)\n geometryIndex = coords[multiFeatureIndex].length + geometryIndex;\n if (coordIndex < 0)\n coordIndex =\n coords[multiFeatureIndex][geometryIndex].length - coordIndex;\n return point(\n coords[multiFeatureIndex][geometryIndex][coordIndex],\n properties,\n options\n );\n }\n throw new Error(\"geojson is invalid\");\n}\n\nexport {\n coordReduce,\n coordEach,\n propEach,\n propReduce,\n featureReduce,\n featureEach,\n coordAll,\n geomReduce,\n geomEach,\n flattenReduce,\n flattenEach,\n segmentReduce,\n segmentEach,\n lineReduce,\n lineEach,\n findSegment,\n findPoint,\n};\n","import { BBox } from \"geojson\";\nimport { AllGeoJSON } from \"@turf/helpers\";\nimport { coordEach } from \"@turf/meta\";\n\n/**\n * Calculates the bounding box for any GeoJSON object, including FeatureCollection.\n * Uses geojson.bbox if available and options.recompute is not set.\n *\n * @function\n * @param {GeoJSON} geojson any GeoJSON object\n * @param {Object} [options={}] Optional parameters\n * @param {boolean} [options.recompute] Whether to ignore an existing bbox property on geojson\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(\n geojson: AllGeoJSON,\n options: {\n recompute?: boolean;\n } = {}\n): BBox {\n if (geojson.bbox != null && true !== options.recompute) {\n return geojson.bbox;\n }\n const result: BBox = [Infinity, Infinity, -Infinity, -Infinity];\n coordEach(geojson, (coord) => {\n if (result[0] > coord[0]) {\n result[0] = coord[0];\n }\n if (result[1] > coord[1]) {\n result[1] = coord[1];\n }\n if (result[2] < coord[0]) {\n result[2] = coord[0];\n }\n if (result[3] < coord[1]) {\n result[3] = coord[1];\n }\n });\n return result;\n}\n\nexport { bbox };\nexport default bbox;\n","/**\n * @Srouce: https://github.com/Turfjs/turf/tree/master/packages/turf-shortest-path\n **/\nimport bbox from \"@turf/bbox\"\nimport booleanPointInPolygon from \"@turf/boolean-point-in-polygon\"\nimport distance from \"@turf/distance\"\nimport scale from \"@turf/transform-scale\"\nimport union from \"@turf/union\"\nimport bboxPolygon from \"@turf/bbox-polygon\"\nimport { cleanCoords } from \"@turf/clean-coords\";\nimport { getCoord, getType, getGeom } from \"@turf/invariant\"\nimport {\n point,\n isNumber,\n lineString,\n isObject,\n featureCollection,\n feature,\n} from \"@turf/helpers\"\nimport PF from \"pathfinding\"\nimport set from \"lodash/set\"\nimport { stringPull } from \"./stringPull\"\nimport { trace } from \"../../../../utils/trace\"\nimport { pruneSmallAngles } from \"./pruneSmallAngle\"\nimport { pruneShortSegments } from \"./pruneShortSegments\"\nimport { buildClearanceGrid, centerlineSnapPath } from \"./clearance\"\n/**\n * Returns the shortest {@link LineString|path} from {@link Point|start} to {@link Point|end} without colliding with\n * any {@link Feature} in {@link FeatureCollection<Polygon>| obstacles}\n *\n * @name shortestPath\n * @param {Coord} start point\n * @param {Coord} end point\n * @param {Object} [options={}] optional parameters\n * @param {Geometry|Feature|FeatureCollection<Polygon>} [options.obstacles] areas which path cannot travel\n * @param {number} [options.minDistance] minimum distance between shortest path and obstacles\n * @param {string} [options.units='kilometers'] unit in which resolution & minimum distance will be expressed in; it can be degrees, radians, miles, kilometers, ...\n * @param {number} [options.resolution=100] distance between matrix points on which the path will be calculated\n * @returns {Feature<LineString>} shortest path between start and end\n * @example\n * const start = [-5, -6];\n * const end = [9, -6];\n * const options = {\n * obstacles: turf.polygon([[[0, -7], [5, -7], [5, -3], [0, -3], [0, -7]]])\n * };\n *\n * const path = turf.shortestPath(start, end, options);\n *\n * //addToMap\n * const addToMap = [start, end, options.obstacles, path];\n */\nfunction shortestPath(start, end, options) {\n // Optional parameters\n options = options || {}\n if (!isObject(options)) throw new Error(\"options is invalid\")\n let resolution = options.resolution\n const smoothenPath = options.smoothenPath\n let obstacles = options.obstacles || featureCollection([])\n\n // validation\n if (!start) throw new Error(\"start is required\")\n if (!end) throw new Error(\"end is required\")\n if ((resolution && !isNumber(resolution)) || resolution <= 0)\n throw new Error(\"options.resolution must be a number, greater than 0\")\n\n // Normalize Inputs\n const startCoord = getCoord(start)\n const endCoord = getCoord(end)\n start = point(startCoord)\n end = point(endCoord)\n\n // Handle obstacles\n switch (getType(obstacles)) {\n case \"FeatureCollection\":\n if (obstacles.features.length === 0)\n return lineString([startCoord, endCoord])\n break\n case \"Polygon\":\n obstacles = featureCollection([feature(getGeom(obstacles))])\n break\n default:\n throw new Error(\"invalid obstacles\")\n }\n\n // define path grid area\n const collection = obstacles\n collection.features.push(start, end)\n const box = bbox(scale(bboxPolygon(bbox(collection)), 1.15)) // extend 15%\n if (!resolution) {\n // Calculate resolution from bbox width distance if config undefined.\n const width = distance([box[0], box[1]], [box[2], box[1]], options)\n resolution = width / 100\n }\n\n collection.features.pop()\n collection.features.pop()\n\n const [west, south, east, north] = box\n const xFraction = resolution / distance([west, south], [east, south], options)\n const cellWidth = xFraction * (east - west)\n const yFraction = resolution / distance([west, south], [west, north], options)\n const cellHeight = yFraction * (north - south)\n\n const bboxHorizontalSide = east - west\n const bboxVerticalSide = north - south\n const columns = Math.floor(bboxHorizontalSide / cellWidth)\n const rows = Math.floor(bboxVerticalSide / cellHeight)\n // adjust origin of the grid\n const deltaX = (bboxHorizontalSide - columns * cellWidth) / 2\n const deltaY = (bboxVerticalSide - rows * cellHeight) / 2\n\n // loop through points only once to speed up process\n // define matrix grid for A-star algorithm\n let closestToStart = null,\n closestToEnd = null,\n minDistStart = Infinity,\n minDistEnd = Infinity,\n currentY = north - deltaY,\n currentX = west + deltaX,\n row = 0,\n column = 0,\n distStart,\n distEnd,\n pt,\n isInsideObstacle\n\n const roundLoopY = Math.ceil((currentY - south) / cellHeight)\n const roundLoopX = Math.ceil((east - currentX) / cellWidth)\n let totalRounds = roundLoopX * roundLoopY\n const pointMatrix = []\n const matrix = []\n\n /**\n * Combine obstacle polygons\n */\n\n const obstacleTotal = collection.features.length\n const obstacleFeatures = collection.features\n let combinedObstacle = obstacleFeatures[0]\n let obstacleIndex = 0\n for (obstacleIndex = 0; obstacleIndex < obstacleTotal; obstacleIndex++) {\n const nextObstacleFeature = obstacleFeatures[obstacleIndex + 1]\n\n if (!nextObstacleFeature) continue\n\n // TODO: Some obstacle fails to \"union\"\n // We should find out which one and then fix this properly\n try {\n combinedObstacle = union(\n featureCollection([combinedObstacle, nextObstacleFeature])\n )\n } catch (e) {\n console.log(e)\n }\n }\n\n /*\n * Optimize the loop for faster creation of a matrix grid.\n * Original Source: https://github.com/Turfjs/turf/blob/88dfdbb2617b70c833e30923590400dc0189e601/packages/turf-shortest-path/index.js#L119\n */\n while (totalRounds--) {\n pt = point([currentX, currentY])\n isInsideObstacle = booleanPointInPolygon(pt, combinedObstacle)\n // feed obstacles matrix\n set(matrix, `[${row}][${column}]`, isInsideObstacle ? 1 : 0)\n\n // map point's coords\n set(pointMatrix, `[${row}][${column}]`, `${currentX}|${currentY}`)\n\n // set closest points\n distStart = distance(pt, start)\n // if (distStart < minDistStart) {\n if (!isInsideObstacle && distStart < minDistStart) {\n minDistStart = distStart\n closestToStart = { x: column, y: row }\n }\n\n distEnd = distance(pt, end)\n if (!isInsideObstacle && distEnd < minDistEnd) {\n minDistEnd = distEnd\n closestToEnd = { x: column, y: row }\n }\n\n if (column < roundLoopX) {\n currentX += cellWidth\n column++\n continue\n }\n\n if (row < roundLoopY) {\n currentY -= cellHeight\n currentX = west + deltaX\n column = 0\n row++\n }\n }\n\n // javascript PathFinding ----------------------\n // @Ref https://github.com/qiao/PathFinding.js\n const finder = new PF.AStarFinder({\n allowDiagonal: true,\n dontCrossCorners: true,\n heuristic: PF.Heuristic.euclidean\n })\n const grid = new PF.Grid(matrix)\n\n const startOnMatrix = [closestToStart.x, closestToStart.y]\n const endOnMatrix = [closestToEnd.x, closestToEnd.y]\n let result = finder.findPath(...startOnMatrix, ...endOnMatrix, grid)\n // if (smoothenPath && result.length > 0) {\n // try {\n // result = PF.Util.smoothenPath(grid, result)\n // } catch (err) {\n // // Github issue is still open, maybe no-one is maintaining\n // // https://github.com/qiao/PathFinding.js/issues/149\n // console.warn(`. Fail to PF.Util.smoothenPath`)\n\n // }\n // }\n\n // Post process path\n if (result.length > 0) {\n // const t0 = performance.now()\n result = stringPull(grid, result)\n // const t1 = performance.now()\n // trace('name', 'stringPull', t1 - t0)\n\n const clearanceGrid = buildClearanceGrid(matrix)\n const isWalkable = (x: number, y: number) => grid.isInside(x, y) && grid.isWalkableAt(x, y)\n result = centerlineSnapPath(result, clearanceGrid, isWalkable) \n\n // StringPull again\n result = stringPull(grid, result)\n\n // prune tiny angles / short segments\n result = pruneSmallAngles(result)\n result = pruneShortSegments(result)\n }\n\n // Remove first and last coordinates to remove unusual curve path which cause from first and last coordinate\n // Which will be too close to startCoord and endCoord and create a curved path between first and startCoord\n result.pop()\n result.shift()\n\n const path = [startCoord]\n result.forEach((coord) => {\n const coords = pointMatrix[coord[1]][coord[0]].split(\"|\")\n path.push([+coords[0], +coords[1]]) // make sure coords are numbers\n })\n path.push(endCoord)\n return cleanCoords(lineString(path))\n // return lineString(path)\n}\n\nexport default shortestPath\n","import { Position } from \"geojson\"\n\n\nexport function stringPull(grid, path: Position[]): Position[] {\n\n // helpers\n const isWalkable = (x: number, y: number) =>\n grid.isInside(x, y) && grid.isWalkableAt(x, y)\n\n /**\n * Line-of-sight check between two grid cells.\n * Compatible with PathFinding.js A*:\n * - allowDiagonal: true\n * - dontCrossCorners: true\n */\n function hasLOS(a: Position, b: Position): boolean {\n let x0 = a[0], y0 = a[1]\n const x1 = b[0], y1 = b[1]\n\n if (!isWalkable(x0, y0) || !isWalkable(x1, y1)) return false\n\n const dx = Math.abs(x1 - x0)\n const dy = Math.abs(y1 - y0)\n const sx = x0 < x1 ? 1 : -1\n const sy = y0 < y1 ? 1 : -1\n\n let err = dx - dy\n\n while (true) {\n if (!isWalkable(x0, y0)) return false\n if (x0 === x1 && y0 === y1) break\n\n const e2 = err * 2\n let nx = x0\n let ny = y0\n let movedX = false\n let movedY = false\n\n if (e2 > -dy) {\n err -= dy\n nx += sx\n movedX = true\n }\n if (e2 < dx) {\n err += dx\n ny += sy\n movedY = true\n }\n\n // prevent corner-cutting (dontCrossCorners)\n if (movedX && movedY) {\n if (!isWalkable(nx, y0) || !isWalkable(x0, ny)) return false\n }\n\n x0 = nx\n y0 = ny\n }\n\n return true\n }\n\n\n if (path.length <= 2) return path\n\n const out: Position[] = [path[0]]\n let i = 0\n\n while (i < path.length - 1) {\n let best = i + 1\n\n // Find the farthest visible point from path[i]\n for (let j = i + 2; j < path.length; j++) {\n if (hasLOS(path[i], path[j])) best = j\n else break // ok when path is a contiguous A* route\n }\n\n out.push(path[best])\n i = best\n }\n\n return out\n\n}","import { Position } from \"geojson\"\n\n\nexport function pruneSmallAngles(path: Position[], minDeg = 10): Position[] {\n if (path.length <= 2) return path\n\n const out: Position[] = [path[0]]\n\n for (let i = 1; i < path.length - 1; i++) {\n const a = out[out.length - 1]\n const b = path[i]\n const c = path[i + 1]\n\n const abx = b[0] - a[0], aby = b[1] - a[1]\n const bcx = c[0] - b[0], bcy = c[1] - b[1]\n\n const dot = abx * bcx + aby * bcy\n const ab = Math.hypot(abx, aby)\n const bc = Math.hypot(bcx, bcy)\n const angle = Math.acos(dot / (ab * bc)) * 180 / Math.PI\n\n if (angle > minDeg) out.push(b)\n }\n\n out.push(path[path.length - 1])\n return out\n}","import { Position } from \"geojson\"\n\nexport function pruneShortSegments(path: Position[], minLen = 5): Position[] {\n const out: Position[] = [path[0]]\n\n for (let i = 1; i < path.length; i++) {\n const [x0, y0] = out[out.length - 1]\n const [x1, y1] = path[i]\n if (Math.hypot(x1 - x0, y1 - y0) >= minLen) {\n out.push(path[i])\n }\n }\n\n return out\n}","type P = [number, number]\n\nexport function buildClearanceGrid(matrix: number[][]) {\n const h = matrix.length\n const w = matrix[0].length\n const INF = 1e9\n\n const dist = Array.from({ length: h }, () => Array(w).fill(INF))\n const q: P[] = []\n\n // seed queue with obstacles (distance 0)\n for (let y = 0; y < h; y++) {\n for (let x = 0; x < w; x++) {\n if (matrix[y][x] === 1) {\n dist[y][x] = 0\n q.push([x, y])\n }\n }\n }\n\n // 8-neighbor BFS gives a decent “clearance-ish” field\n const dirs: P[] = [\n [1,0],[-1,0],[0,1],[0,-1],\n [1,1],[1,-1],[-1,1],[-1,-1],\n ]\n\n let qi = 0\n while (qi < q.length) {\n const [x, y] = q[qi++]\n const d0 = dist[y][x]\n for (const [dx, dy] of dirs) {\n const nx = x + dx, ny = y + dy\n if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue\n const nd = d0 + 1\n if (nd < dist[ny][nx]) {\n dist[ny][nx] = nd\n q.push([nx, ny])\n }\n }\n }\n\n return dist // higher = more centered / more clearance\n}\n\nexport function snapPointToClearancePeak(\n p: P,\n clearance: number[][],\n isWalkableCell: (x: number, y: number) => boolean,\n radius = 4\n): P {\n const [px, py] = p\n let best: P = p\n let bestScore = clearance[py]?.[px] ?? -Infinity\n\n for (let dy = -radius; dy <= radius; dy++) {\n for (let dx = -radius; dx <= radius; dx++) {\n const x = px + dx\n const y = py + dy\n if (!isWalkableCell(x, y)) continue\n\n const score = clearance[y][x]\n // prefer higher clearance; tiny tie-breaker toward staying close\n const penalty = Math.hypot(dx, dy) * 0.005\n const finalScore = score - penalty\n\n if (finalScore > bestScore) {\n bestScore = finalScore\n best = [x, y]\n }\n }\n }\n\n return best\n}\n\nexport function centerlineSnapPath(\n path: P[],\n clearance: number[][],\n isWalkableCell: (x: number, y: number) => boolean,\n radius = 4\n): P[] {\n const snapped = path.map(p => snapPointToClearancePeak(p, clearance, isWalkableCell, radius))\n return snapped\n}","import { center } from '@turf/center'\nimport distance from '@turf/distance'\nimport { Landmark } from './type';\nimport { Point, Position } from 'geojson';\nimport { OccupantFeature } from '../../types';\nimport { FindByIdSync, GetNavigateClientOptions } from '../type';\n\nexport type CreateLandmarkUtilsOptions = GetNavigateClientOptions & { findByIdSync: FindByIdSync }\n\nexport type LandmarkUtils = {\n findNearbyLandmarks: (point: Point|Position|null, levelId: string) => Landmark[]\n findNearestLandmark: (point: Point|Position|null, levelId: string) => Landmark\n}\n\nconst NEARBY_DISTANCE = 30 // 30 meter\n\nexport const createLandmarkUtils = (options: CreateLandmarkUtilsOptions): LandmarkUtils => {\n\n const { data, findByIdSync } = options\n const { occupants } = data\n /** Create set of Landmarks from data\n * 1. Occupants where is_landmark = true\n * 2. ???\n */\n const occupantToLandmark = (occupant: OccupantFeature): Landmark => {\n const locationType: \"unit\" | \"kiosk\" = occupant.properties.unit_id ? \"unit\" : \"kiosk\"\n const locationId: string = locationType === \"unit\" ? occupant.properties.unit_id : occupant.properties.kiosk_id\n const location = locationType === \"unit\" ? findByIdSync<\"unit\">(locationId) : findByIdSync<\"kiosk\">(locationId)\n const level = findByIdSync<\"level\">(location.properties.level_id)\n return {\n name: occupant.properties.name,\n point: center(location.geometry).geometry.coordinates,\n level_id: location.properties.level_id,\n is_priority: occupant.properties.is_landmark,\n ordinal: level.properties.ordinal,\n }\n }\n\n /** Use all occupants as Landmarks */\n const landmarks: Landmark[] = [\n ...occupants.map(occupantToLandmark),\n ]\n\n const findNearbyLandmarks = (point: Point|Position|null, levelId: string|null): Landmark[] => {\n if (point === null || levelId === null) return []\n return landmarks\n .map(landmark => {\n const landmarkAndDistance = {\n landmark,\n d: distance(point, landmark.point, { units: 'meters' }),\n }\n return landmarkAndDistance\n })\n .filter(({ landmark, d }) => d <= NEARBY_DISTANCE && landmark.level_id === levelId)\n .sort((a, b) => {\n // 1) landmark priority\n const aPriority = a.landmark.is_priority ? 0 : 1\n const bPriority = b.landmark.is_priority ? 0 : 1\n if (aPriority !== bPriority) return aPriority - bPriority\n\n // 2) distance\n return a.d - b.d\n })\n .map(({ landmark }) => landmark)\n }\n\n const findNearestLandmark = (point: Point|Position|null, levelId: string|null): Landmark|null => {\n const nearbyLandmarks = findNearbyLandmarks(point, levelId)\n const nearestLandmark = nearbyLandmarks.length > 0 ? nearbyLandmarks[0] : null\n return nearestLandmark\n }\n\n return { findNearbyLandmarks, findNearestLandmark }\n}","import { center } from \"@turf/center\"\nimport { Waypoint } from \"../type\"\nimport { isOccupant, isOpening, isUnit, isKiosk } from \"./featureIdGuard\"\nimport { isCoordinateOrdinalString } from \"../../type-guard\"\nimport { parseOrdinalCoordinate } from \"../../parsers\"\nimport { CoordinateOrdinalString } from \"../../type\"\nimport { CreateStepUtilsOptions } from \"../createStepUtils\"\n\nexport const extractStartPoint = (path: string[], options: CreateStepUtilsOptions): [Waypoint|null, string[]] => {\n const { findByIdSync } = options\n const [a, b, c] = path\n\n // opening → unit → occupant \n if (isOccupant(a) && isUnit(b) && isOpening(c)) {\n const occ = findByIdSync<\"occupant\">(a)\n const opening = findByIdSync<\"opening\">(c)\n const level = findByIdSync<\"level\">(opening.properties.level_id)\n return [\n {\n id: occ.id,\n type: 'start',\n name: occ.properties.name,\n point: center(opening).geometry.coordinates,\n levelId: opening.properties.level_id,\n ordinal: level.properties.ordinal,\n source: { type: \"opening\", id: opening.id }\n },\n path.slice(3)\n ]\n }\n\n // occupant → kiosk\n if (isOccupant(a) && isKiosk(b)) {\n const occ = findByIdSync<\"occupant\">(a)\n const kiosk = findByIdSync<\"kiosk\">(c)\n const level = findByIdSync<\"level\">(kiosk.properties.level_id)\n return [\n {\n id: occ.id,\n type: 'start',\n name: occ.properties.name,\n point: center(kiosk).geometry.coordinates,\n levelId: kiosk.properties.level_id,\n ordinal: level.properties.ordinal,\n source: { type: \"kiosk\", id: kiosk.id }\n },\n path.slice(2)\n ]\n }\n\n // coordinate+ordinal → opening\n if (isCoordinateOrdinalString(a) && isOpening(b)) {\n const [lat, lng, ordinal] = parseOrdinalCoordinate(a as CoordinateOrdinalString)\n const opening = findByIdSync<\"opening\">(b)\n return [\n {\n id: a,\n type: 'start',\n name: { en: `Your location`},\n point: [lng, lat],\n levelId: opening.properties.level_id,\n ordinal,\n source: { type: \"opening\", id: opening.id }\n },\n path.slice(1)\n ]\n }\n return [null, path]\n}","export const isOccupant = (id?: string) => !!id && id.startsWith(\"occupant-\")\nexport const isUnit = (id?: string) => !!id && id.startsWith(\"unit-\")\nexport const isKiosk = (id?: string) => !!id && id.startsWith(\"kiosk-\")\nexport const isOpening = (id?: string) => !!id && id.startsWith(\"opening-\")\n","import type { FeatureId, CoordinateOrdinalString } from './type'\n\nexport function isFeatureId(id: string): id is FeatureId {\n return new RegExp(`^(occupant|unit|amenity|anchor|kiosk|unit|section|opening)-\\\\d+$`).test(id)\n}\n\nexport function isCoordinateOrdinalString(\n id: string\n): id is CoordinateOrdinalString {\n return /^-?\\d+(\\.\\d+)?,-?\\d+(\\.\\d+)?,-?\\d+(\\.\\d+)?o$/.test(id)\n}","import { center } from \"@turf/center\"\nimport { Waypoint } from \"../type\"\nimport { isOccupant, isOpening, isUnit, isKiosk } from \"./featureIdGuard\"\nimport { isCoordinateOrdinalString } from \"../../type-guard\"\nimport { parseOrdinalCoordinate } from \"../../parsers\"\nimport { CoordinateOrdinalString } from \"../../type\"\nimport { CreateStepUtilsOptions } from \"../createStepUtils\"\n\nexport const extractEndPoint = (path: string[], options: CreateStepUtilsOptions): [Waypoint|null, string[]] => {\n const { findByIdSync } = options\n const [c, b, a] = path.slice(-3)\n\n // opening → unit → occupant \n if (isOccupant(a) && isUnit(b) && isOpening(c)) {\n const occ = findByIdSync<\"occupant\">(a)\n const opening = findByIdSync<\"opening\">(c)\n const level = findByIdSync<\"level\">(opening.properties.level_id)\n return [\n {\n id: occ.id,\n type: 'end',\n name: occ.properties.name,\n point: center(opening).geometry.coordinates,\n levelId: opening.properties.level_id,\n ordinal: level.properties.ordinal,\n source: { type: \"opening\", id: opening.id }\n },\n path.slice(0, -3)\n ]\n }\n\n // kiosk → occupant\n if (isOccupant(a) && isKiosk(b)) {\n const occ = findByIdSync<\"occupant\">(a)\n const kiosk = findByIdSync<\"kiosk\">(c)\n const level = findByIdSync<\"level\">(kiosk.properties.level_id)\n return [\n {\n id: occ.id,\n type: 'end',\n name: occ.properties.name,\n point: center(kiosk).geometry.coordinates,\n levelId: kiosk.properties.level_id,\n ordinal: level.properties.ordinal,\n source: { type: \"kiosk\", id: kiosk.id }\n },\n path.slice(0, -2)\n ]\n }\n\n // opening → oordinate+ordinal\n if (isCoordinateOrdinalString(a)) {\n const [lat, lng, ordinal] = parseOrdinalCoordinate(a as CoordinateOrdinalString)\n const opening = findByIdSync<\"opening\">(b)\n return [\n {\n id: a,\n type: 'end',\n name: { en: `Your location`},\n point: [lng, lat],\n levelId: opening.properties.level_id,\n ordinal,\n source: { type: \"opening\", id: opening.id }\n },\n path.slice(0, -2)\n ]\n }\n return [null, path]\n}","import uniq from \"lodash/uniq\";\nimport { Step } from \"../type\";\n\nexport const combineWalkwaySteps = (steps: Step[]) => {\n let result: Step[] = []\n\n for (let i = 0; i < steps.length; i++) {\n const thisStep: Step = steps[i]\n if (i === steps.length - 1) {\n result.push(thisStep)\n continue\n }\n\n const nextStep: Step = steps[i + 1]\n if (\n thisStep.intermediaryCategory === \"walkway\"\n && nextStep.intermediaryCategory === \"walkway\" \n && thisStep.from.source.type === \"opening\"\n && nextStep.from.source.type === \"opening\"\n ) {\n console.log({ i, len: steps.length, thisStep, nextStep })\n result.push({\n from: thisStep.from,\n to: nextStep.to,\n levelIds: uniq([...thisStep.levelIds, ...nextStep.levelIds]),\n ordinals: uniq([...thisStep.ordinals, ...nextStep.ordinals]),\n intermediaryCategory: \"walkway\",\n description: nextStep.description,\n path: [\n ...thisStep.path,\n ...nextStep.path\n ]\n })\n \n i++ // Skip one step\n } else {\n result.push(thisStep)\n }\n }\n return result\n}","import calculateLength from \"@turf/length\"\nimport { lineString } from '@turf/helpers'\nimport { Step } from \"../steps\"\nimport { Feature, LineString } from \"geojson\"\n\nconst WALKING_SPEED = 1.4 // meters per min\n\nexport const calculatePathLength = (feature: Feature<LineString>) =>\n calculateLength(feature, { units: \"kilometers\" }) * 1000 // length in meters\n\nexport const calculateTravelingDuration = (distance) => {\n const duration = distance / WALKING_SPEED // duration in seconds\n const minutes = Math.round(duration / 60)\n return minutes > 0 ? minutes : 1\n}\n\nexport const calculateTotalDistance = (steps: Step[] = []) => {\n return steps.reduce((acc, { path }) => acc + calculatePathLength(lineString(path)), 0)\n}\n\nexport const calculateRoundedDistance = (distance) => {\n return Math.round(distance - (distance % 25))\n}\n","import { FeatureResponseMap, FeatureType, ImdfFeature } from \"../../types\";\nimport { FindByIdSync, GetNavigateClientOptions } from \"../type\";\n\nexport const createFindByIdSync = (data: GetNavigateClientOptions[\"data\"]) => {\n const { amenities = [], anchors = [], fixtures = [], levels = [], kiosks = [], relationships = [], occupants = [], openings = [], units } = data\n const featureById: Map<string, ImdfFeature> = new Map()\n const entries = [\n ...amenities,\n ...anchors,\n ...fixtures,\n ...levels,\n ...kiosks,\n ...relationships,\n ...occupants,\n ...openings,\n ...units\n ]\n for (const f of entries) featureById.set(f.id, f)\n const findByIdSync: FindByIdSync = <T extends FeatureType = FeatureType>(id: string): FeatureResponseMap[T] => {\n return featureById.get(id) as FeatureResponseMap[T]\n } \n return { findByIdSync }\n}","import {\n ui,\n Map,\n TileLayer,\n VectorLayer,\n LineString,\n Geometry,\n Coordinate,\n OverlayLayer,\n GroupGLLayer,\n GLTFLayer,\n} from \"maptalks-gl\"\nimport '@maptalks/transcoders.draco';\n\nimport { GeoJsonProperties, LineString as LineStringType, Feature } from \"geojson\"\nimport TWEEN from \"@tweenjs/tween.js\"\nimport _ from \"lodash\"\nimport {\n feature as turfFeature,\n lineString,\n point,\n} from \"@turf/helpers\"\nimport turfDistance from \"@turf/distance\"\nimport turfCenter from \"@turf/center\"\nimport { featureCollection } from '@turf/helpers';\n\nimport { PerspectiveCamera } from \"three\"\nimport { ThreeLayer } from \"maptalks.three\"\n\nimport {\n LAYERS,\n LAYER_OPTIONS,\n LAYER_FEATURE_TYPE_OBJ,\n HIGHLIGHT_LAYER_NAME,\n USER_LOCATION_LAYER_NAME,\n ORIGIN_MARKER_ID,\n DESTINATION_MARKER_ID,\n USER_LOCATION_ELEMENT_ID,\n LAST_USER_LOCATION_ELEMENT_ID_PREFIX,\n LOCALE_SYMBOL_KEY,\n DEFAULT_LOCALE,\n VENUE_EVENTS,\n} from \"./constants\"\n\nimport {\n styledFeatureGenerator,\n getExtrudeConfigByFeature,\n} from \"./utils/createElements\"\n\nimport { getBearingBetweenPoints } from \"./utils/math\"\n\nimport {\n NavigationPath,\n} from \"./object3d\"\nimport {\n IMapConfig,\n IndoorMapOptions,\n} from \"./types\"\n\nimport { CameraManager } from \"./camera/CameraManager\"\nimport { RendererManager } from \"./renderer\"\nimport { VenueDataClient } from \"../data\"\n\nconst INITIAL_CENTER = [100.5017051, 13.7572619] // just placeholder\nconst INITIAL_ZOOM = 18.5\nconst CLICK_TOLERANCE = 20\n\nconst defaultOptions: Partial<IndoorMapOptions> = {\n pixelRatio: 1,\n interactions: true,\n locale: DEFAULT_LOCALE,\n}\n\nconst parseMaptalksOptions = (options: IndoorMapOptions) => {\n return {\n centerCross: (options.centerCross ?? false),\n ...(options.interactions === false ? ({\n draggable: false,\n dragPan: false,\n dragRotate: false,\n dragPitch: false,\n scrollWheelZoom: false,\n touchZoom: false,\n doubleClickZoom: false\n }) : {}),\n }\n}\n\nexport class IndoorMap extends EventTarget {\n options: IndoorMapOptions\n //TODO: refac functions; let them do only 1 thing in a function\n\n /** Note: \"#\" means private variables */\n #styler = null\n #featuresInitted = false\n #elementsLoaded = false\n #elements: Record<string, any> = {}\n #features = []\n #markers = []\n #venues = []\n #venueInView: string | null = null\n #ordinals = []\n #mapTheme = {}\n #billboards = []\n #billboardObjects = []\n #spriteMarkerObjects = []\n #mapDecorations = []\n #groundObjects = []\n #navigationGeometries: Record<string, NavigationPath> = {}\n #venueObjects = []\n #glbObjects = []\n #objects = []\n #object3ds = []\n #isClicked = false\n #highlightElementIds = []\n #highlightObjectIds = []\n #highlightObjectControllers = []\n #userLocationGeometry = null\n #userLocationElement = null\n #mapConfig: IMapConfig = {}\n #locale: string = defaultOptions.locale\n #lastUserLocationGeometries = []\n #lastUserLocationElements = []\n\n #isLayersFadingOnZoom = false\n\n #touchStartTarget = null\n #touchStartPoint = null\n\n #onClickElement = (e) => {}\n #animationsToRun = []\n\n map: Map | null = null\n #dataClient: VenueDataClient\n camera: CameraManager\n rendererManager: RendererManager\n\n showVenueObject = false\n threeLayer: ThreeLayer | null = null\n\n onMapReady = () => {}\n onMapLoading = () => {}\n\n constructor(elementId, options: IndoorMapOptions) {\n super()\n const combinedOptions = _.merge({}, defaultOptions, options)\n this.options = combinedOptions\n const {\n onMapReady,\n onMapLoading,\n pixelRatio,\n locale,\n } = combinedOptions\n\n const maptalksOptions = parseMaptalksOptions(combinedOptions)\n\n this.map = new Map(elementId, {\n attribution: false,\n // Temporart set, not really default view\n // Default view is set in camera manager\n center: INITIAL_CENTER,\n zoom: INITIAL_ZOOM,\n clickTimeThreshold: 600,\n ...maptalksOptions,\n baseLayer: new TileLayer(\"base\", {\n urlTemplate:\n \"https://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png\",\n subdomains: [\"a\", \"b\", \"c\", \"d\"],\n opacity: 1.0,\n attribution: \"\",\n hitDetect: false,\n decodeImageInWorker: true,\n errorUrl: \"/assets/img/tile-placeholder.png\",\n }),\n layers: [],\n })\n\n const groupLayer = new GroupGLLayer('group', [], {}).addTo(this.map);\n\n const threeLayer = new ThreeLayer(\"three\", {\n forceRenderOnMoving: true,\n forceRenderOnRotating: true,\n })\n groupLayer.addLayer(threeLayer)\n\n const gltfLayer = new GLTFLayer('gltf');\n groupLayer.addLayer(gltfLayer);\n\n /** Manage create elements from imdf features */\n this.rendererManager = new RendererManager(this.map, options.dataClient, options.renderer)\n\n /** Manage zoom, bearing, pitch, flyTo, moveCamera to position */\n this.camera = new CameraManager(this.map, options.camera)\n \n this.locale = locale\n this.pixelRatio = pixelRatio\n\n this.onMapReady = onMapReady\n this.onMapLoading = onMapLoading\n this.showVenueObject = false\n\n // Bind events\n // @ts-expect-error\n this.map.on(\"click\", this.handleMapClick)\n\n this.dataClient = options.dataClient\n }\n\n setOptions(options) {\n const combinedOptions = _.merge({}, defaultOptions, options)\n this.options = combinedOptions\n\n const maptalksOptions = parseMaptalksOptions(combinedOptions)\n this.map.setOptions(maptalksOptions)\n }\n\n set dataClient(value) {\n this.#dataClient = value\n \n // If no defaultView is set, get center from dataClient and move map to center\n if (!this.options.camera?.defaultView?.center) {\n this.#dataClient.filterByType(\"venue\")\n .then(venues => {\n\n /** Store for later use */\n this.#venues = venues;\n\n /** Find Venue's center */\n const venueCenters = turfCenter(featureCollection(venues));\n const [x, y] = venueCenters.geometry.coordinates\n const center = new Coordinate(x, y)\n\n /** Move Map to center */\n this.camera.setView({ center, pitch: 60, zoom: 19 })\n })\n }\n }\n\n \n\n /**\n * Events\n */\n on(eventName: string, handler) {\n this.map.on(eventName, handler)\n }\n\n handleMapClick = ({ coordinate }) => {\n const { x, y } = coordinate\n console.log(\n `[Coordinates]: x: ${_.round(x, 8)} y: ${_.round(\n y,\n 8\n )}, [Bearing]: ${this.map.getBearing()}, [Pitch]: ${this.map.getPitch()}`\n )\n }\n\n handleMapTouchEnd = ({ containerPoint }) => {\n const { x, y } = containerPoint\n const { x: touchStartX, y: touchStartY } = this.#touchStartPoint\n\n const dis = Math.hypot(x - touchStartX, y - touchStartY)\n // @ts-expect-error \n this.map.off(\"touchend\", this.handleMapTouchEnd)\n\n if (dis > 0 && dis < CLICK_TOLERANCE) {\n console.log(\"Forgiving click\", this.#touchStartTarget.properties.id)\n this.handleClickElement({ target: this.#touchStartTarget })\n }\n\n this.#touchStartTarget = null\n this.#touchStartPoint = null\n }\n\n /**\n * Getters & Setters\n */\n get elementsLoaded() {\n return this.#elementsLoaded\n }\n\n get pixelRatio() {\n return this.map.getDevicePixelRatio()\n }\n\n get locale() {\n return this.#locale\n }\n\n set mapTheme(value) {\n this.#mapTheme = value\n this.#styler = styledFeatureGenerator(this.#mapTheme)\n }\n\n get venues() {\n return this.#venues || []\n }\n\n #findAndSetVenueInView = () => {\n const venueInViewWithDistance = this.findVenueInView()\n if (\n venueInViewWithDistance &&\n (!this.#venueInView ||\n venueInViewWithDistance.venueId !== this.#venueInView)\n ) {\n this.#venueInView = venueInViewWithDistance.venueId\n this.map.fire(VENUE_EVENTS.VENUE_MOVEINTOVIEW, venueInViewWithDistance)\n }\n }\n\n set detectVenueInView(value) {\n if (value) {\n // Set initial venueInView\n this.#findAndSetVenueInView()\n this.map.on(\"moveend\", this.#findAndSetVenueInView)\n } else {\n this.map.off(\"moveend\", this.#findAndSetVenueInView)\n }\n }\n\n set billboards(value) {\n this.#billboards = value\n }\n\n set mapDecorations(value) {\n this.#mapDecorations = value\n }\n\n set pixelRatio(value: number) {\n this.map.setDevicePixelRatio(value)\n }\n\n set onClickElement(func) {\n this.rendererManager.onClickElement = func\n }\n\n set locale(value: string) {\n this.#locale = value || defaultOptions.locale\n\n // Update elements affected by locale changes.\n this.updateUserLocationSymbolByLocale(this.#locale)\n }\n\n /**\n * Private internal methods\n */\n\n #clearElements() {\n LAYERS.forEach((layerKey) => {\n this.#clearAllElementOnLayerByName(layerKey)\n })\n const scene = this.threeLayer.getScene()\n if (scene) {\n scene.children = scene.children.filter(\n (children) => children instanceof PerspectiveCamera\n )\n }\n }\n\n handleClickElement = (e) => {\n if (this.#isClicked) return\n this.#isClicked = true\n const onClickElement = this.#onClickElement\n if (!_.isFunction(onClickElement)) return\n this.#onClickElement(e)\n this.#isClicked = false\n }\n\n async #legacy_createElements() {\n const {\n // 2D\n createOpening,\n createSection,\n createDecoration,\n // 3D\n create3DBillboard,\n create3DAmenityMarker,\n create3DOpeningMarker,\n } = this.#styler\n\n let elements = {}\n let object3ds = []\n\n for (const feature of this.#features) {\n try {\n const { feature_type: featureType, properties, id } = feature\n const layerName = _.get(\n LAYER_FEATURE_TYPE_OBJ,\n featureType,\n featureType\n )\n const layer = this.map.getLayer(layerName)\n let geometry\n const category = _.get(feature, \"properties.category\")\n\n const extrudeConfig = _.get(this.#mapConfig, \"extrude\")\n const textMarkerType = _.get(\n this.#mapConfig,\n \"text_marker_type\",\n \"ui-marker\"\n )\n const featureExtrudeConfig = getExtrudeConfigByFeature(\n extrudeConfig,\n feature\n )\n\n switch (featureType) {\n \n case \"amenity\": {\n if (feature.properties.is_featured) {\n const billboardObj = create3DBillboard(feature, this.threeLayer)\n billboardObj?.on(\"click\", this.handleClickElement)\n this.#billboardObjects.push(billboardObj)\n this.#spriteMarkerObjects.push(billboardObj)\n object3ds.push(billboardObj)\n break\n }\n const marker3d = create3DAmenityMarker(\n feature,\n this.threeLayer,\n extrudeConfig\n )\n marker3d?.on(\"click\", this.handleClickElement)\n this.#spriteMarkerObjects.push(marker3d)\n object3ds.push(marker3d)\n break\n }\n case \"opening\": {\n switch (category) {\n case \"emergencyexit\":\n const { geometry } = turfCenter(feature)\n const markerFeature = {\n ...feature,\n geometry,\n }\n const marker3d = create3DOpeningMarker(\n markerFeature,\n this.threeLayer,\n extrudeConfig\n )?.on(\"click\", this.handleClickElement)\n object3ds.push(marker3d)\n break\n default:\n }\n geometry = createOpening(feature)\n ?.on(\"click\", this.handleClickElement)\n .addTo(layer)\n break\n }\n case \"section\": {\n geometry = createSection(feature)?.addTo(layer)\n break\n }\n \n default:\n break\n }\n if (!id) throw new Error(`Property is missing ID, ${id}`)\n elements[id] = { geometry, properties, featureType, feature }\n } catch (err) {\n console.warn(`Cannot create ${feature.id}: ${err.message}`)\n }\n }\n\n this.#mapDecorations.forEach((decoration) => {\n const { id, geometry, properties } = decoration\n const geometryType = decoration?.geometry?.type\n try {\n switch (geometryType) {\n case \"Point\":\n const createdBillboard = create3DBillboard(\n decoration,\n this.threeLayer\n )\n this.#billboardObjects.push(createdBillboard)\n object3ds.push(createdBillboard)\n break\n default:\n const decorationLayer = this.map.getLayer(`base`)\n const createdDecoration = createDecoration(geometry, {\n id,\n ...properties,\n }).addTo(decorationLayer)\n elements[id] = {\n geometry: createdDecoration,\n properties,\n featureType: \"decoration\",\n }\n break\n }\n } catch (error) {\n console.log(\n \"error creating decoration for \",\n decoration.properties.name\n )\n }\n })\n\n // Initiate Canvas render\n this.#elements = elements\n this.#elementsLoaded = true\n this.#featuresInitted = true\n this.#object3ds = object3ds\n if (typeof this.onMapReady === \"function\") this.onMapReady()\n }\n\n #clearAllElementOnLayerByName = (layerName: string) => {\n const layer = this.map.getLayer(layerName) as VectorLayer\n if (layer) layer.clear()\n }\n\n /**\n * Change Level & animate to path / geometry / view / etc.\n * ================================== */\n changeLevelByOrdinal(ordinal: null | number | number[]): void {\n this.rendererManager.changeLevelByOrdinal(ordinal)\n }\n\n findVenueInView = (): { venueId: string; distance: number } => {\n const mapCenter = this.map.getCenter()\n const result = this.#venues.reduce<{\n venueId: string\n distance: number\n } | null>((closest, venue) => {\n const { display_point: displayPoint } = venue.properties\n const distance = turfDistance(displayPoint, [mapCenter.x, mapCenter.y])\n if (!closest || distance < closest.distance) {\n return { venueId: venue.id, distance }\n }\n return closest\n }, null)\n return result\n }\n\n getLineStringBearing = (feature) => {\n const { geometry } = feature\n const path = new LineString(geometry.coordinates)\n return getBearingBetweenPoints(\n path.getFirstCoordinate(),\n path.getLastCoordinate()\n )\n }\n\n //map animation\n addAnimations(animation: { id: string; callback: () => void }) {\n this.#animationsToRun.push(animation)\n }\n\n removeAnimationById(id: string) {\n this.#animationsToRun = this.#animationsToRun.filter(\n (animation) => animation.id !== id\n )\n }\n\n clearAnimations() {\n this.#animationsToRun = []\n }\n\n /**\n * User Location\n ****************************/\n // TODO: To consider if we should use setter `set userLocation` instead?\n\n addUserLocation(value) {\n const { createUserLocationMarker } = this.#styler\n\n this.#userLocationGeometry = value\n\n const { properties, feature_type } = value\n\n // If UserLocationGeometry not exists, create one.\n\n const markerLayer = this.map.getLayer(USER_LOCATION_LAYER_NAME)\n\n if (!this.#userLocationElement?.geometry && markerLayer) {\n const geometry = createUserLocationMarker(value)\n geometry.addTo(markerLayer)\n\n // Add marker to this.#elements\n const element = {\n geometry,\n properties,\n featureType: feature_type,\n feature: value,\n }\n this.#elements[USER_LOCATION_ELEMENT_ID] = element\n this.#userLocationElement = element\n\n this.updateUserLocationSymbolByLocale(this.locale)\n }\n }\n\n updateUserLocationSymbolByLocale(locale: string) {\n const userLocationGeometry = _.get(\n this.#elements,\n `${USER_LOCATION_ELEMENT_ID}.geometry`\n )\n\n if (!userLocationGeometry) return\n\n const currentSymbol = userLocationGeometry.getSymbol()\n\n /**\n * Localized user location marker example.\n * Supports locale-based marker files.\n *\n * Example:\n * {\n * \"markerFile\": \"logo_url\", // Default marker\n * \"locale_symbol\": { \"th\": { \"markerFile\": \"logo_url\" }, \"default\": { \"markerFile\": \"logo_url\" } }\n * }\n */\n const localeSymbolToUpdate = currentSymbol.map((symbol) => {\n const localeSymbol =\n _.get(symbol, `${LOCALE_SYMBOL_KEY}.${locale}`) ||\n _.get(symbol, `${LOCALE_SYMBOL_KEY}.default`)\n if (!_.isPlainObject(localeSymbol)) return symbol\n\n return {\n ...symbol,\n ...localeSymbol,\n }\n })\n userLocationGeometry?.updateSymbol(localeSymbolToUpdate)\n }\n\n removeUserLocation() {\n this.#userLocationGeometry = null\n if (this.#userLocationElement) {\n const { geometry } = this.#userLocationElement\n if (geometry) geometry.remove()\n\n this.#userLocationElement = null\n this.#elements[USER_LOCATION_ELEMENT_ID] = null\n }\n }\n\n showUserLocationMarker() {\n this.#userLocationElement?.geometry.show()\n }\n\n hideUserLocationMarker() {\n this.#userLocationElement?.geometry.hide()\n }\n\n addLastUserLocation(value) {\n const newLastLocationId = value?.id\n // If the last location ID is undefined or exists, no new marker will be added.\n const isExists =\n this.#lastUserLocationGeometries.findIndex(\n ({ feature }) => feature?.id === newLastLocationId\n ) >= 0\n\n if (!newLastLocationId || isExists) return\n\n const { createLastUserLocationMarker } = this.#styler\n\n this.#lastUserLocationGeometries = [\n ...this.#lastUserLocationGeometries,\n value,\n ]\n\n const { properties, feature_type, id } = value\n\n const markerLayer = this.map.getLayer(USER_LOCATION_LAYER_NAME)\n\n const geometry = createLastUserLocationMarker(value)\n if (!geometry) return\n geometry.addTo(markerLayer)\n\n // Add marker to this.#elements\n const element = {\n geometry,\n properties,\n featureType: feature_type,\n feature: value,\n }\n this.#elements[`${LAST_USER_LOCATION_ELEMENT_ID_PREFIX}${id}`] = element\n this.#lastUserLocationElements = [\n ...this.#lastUserLocationElements,\n element,\n ]\n }\n\n removeLastUserLocation() {\n this.#lastUserLocationGeometries = []\n if (\n this.#lastUserLocationElements &&\n this.#lastUserLocationElements.length > 0\n ) {\n for (const lastUserLocationElem of this.#lastUserLocationElements) {\n const { geometry, properties = {} } = lastUserLocationElem\n if (geometry) {\n geometry.remove()\n delete this.#elements[`last_user_location-${properties?.id}`]\n }\n }\n this.#lastUserLocationElements = []\n }\n }\n\n hideLastUserLocationMarker() {\n for (const lastUserLocationElem of this.#lastUserLocationElements) {\n const { geometry } = lastUserLocationElem\n if (geometry) geometry.hide()\n }\n }\n\n /**\n * END of User Location\n ****************************/\n\n showGeometryByElementId = (elementId): void => {\n const geometry: Geometry | undefined = _.get(\n this.#elements,\n `${elementId}.geometry`\n )\n if (geometry) geometry.show()\n }\n\n hideGeometryByElementId = (elementId): void => {\n const geometry: Geometry = _.get(this.#elements, `${elementId}.geometry`)\n if (geometry) geometry.hide()\n }\n\n setSpriteMarkersOpacity = (opacity: number = 1): void => {\n const spriteMarkerObjects = this.#spriteMarkerObjects\n spriteMarkerObjects?.forEach((baseObject) => {\n baseObject.getObject3d().traverse((child) => {\n if (child.isLine || child.isSprite) {\n child.material.opacity = opacity\n }\n })\n })\n }\n\n setFeatureObject3DsOpacity = (opacity: number = 1): void => {\n const objects = this.#object3ds\n objects?.forEach((baseObject) => {\n if (baseObject instanceof NavigationPath) return\n baseObject.getObject3d().traverse((child) => {\n if (child.isMesh === true) {\n child.material.opacity = opacity\n }\n })\n })\n }\n\n /*\n * Enable or disable the fading effect based on the zoom level for all layers except the Venue Model.\n * This function applies when extruded units exceed the edges of the Venue Model while zooming out.\n * It can be enabled only when the Venue Model is present.\n */\n disableLayersFadingOnZoom = (): void => {\n this.#isLayersFadingOnZoom = false\n }\n\n enableLayersFadingOnZoom = (): void => {\n this.#isLayersFadingOnZoom = this.#venueObjects.length !== 0\n }\n\n /**\n * Navigation\n ****************************/\n combineNearbyLineStrings(\n lineStrings: Feature<LineStringType, GeoJsonProperties>[],\n options: {\n properties?: GeoJsonProperties\n distance?: number\n } = { properties: {}, distance: 0.0003 }\n // 0.0003 = 30cm\n ) {\n const { properties = {}, distance = 0.0003 } = options || {}\n const combinedLineStrings = []\n const accLine = []\n if (lineStrings.length === 1) return lineStrings\n\n for (let i = 0; i < lineStrings.length; i++) {\n const line = lineStrings[i]\n const coords = line.geometry.coordinates\n const prevLine = lineStrings[i - 1]\n const firstCoord = _.first(coords)\n const isFirstLine = i === 0\n\n if (isFirstLine) {\n accLine.push(...coords)\n continue\n }\n\n const prevLastCoord = _.last(prevLine.geometry.coordinates)\n const isNearby =\n turfDistance(point(firstCoord), point(prevLastCoord)) < distance\n\n if (!isNearby) {\n const remainingLines = lineStrings.slice(i)\n const res = this.combineNearbyLineStrings(remainingLines, properties)\n combinedLineStrings.push(...res)\n break\n }\n accLine.push(...coords)\n }\n combinedLineStrings.push(lineString(accLine, properties))\n return combinedLineStrings\n }\n\n createNavigationGeometries = (stepGeometries, destinationFeature) => {\n const {\n createOriginMarker,\n createDestinationPinMarker,\n createDestinationLogoMarker,\n create3DStepPath,\n } = this.#styler\n const routeMarkerLayer = this.map.getLayer(HIGHLIGHT_LAYER_NAME)\n\n const linesByOrdinal = _(stepGeometries)\n .filter(({ geometry }) => geometry.type === \"LineString\")\n .groupBy(\"properties.ordinal\")\n .value()\n\n const joinedLines = _(linesByOrdinal).reduce((acc, lines, key) => {\n const joined = this.combineNearbyLineStrings(lines, {\n properties: { ordinal: +key },\n })\n return [...acc, ...joined]\n }, [])\n\n joinedLines.forEach((line, index) => {\n try {\n const navPath: NavigationPath = create3DStepPath(line, this.threeLayer)\n this.threeLayer.addMesh([navPath])\n this.#navigationGeometries[`line-${index}`] = navPath\n this.#object3ds.push(navPath)\n } catch (err) {\n console.log(err)\n }\n })\n\n stepGeometries.forEach((stepGeometry) => {\n const { geometry, properties, feature_type = null } = stepGeometry\n let stepElement\n try {\n switch (geometry.type) {\n // Create a destination marker and route path\n case \"Point\":\n switch (feature_type) {\n case \"origin-marker\":\n stepElement =\n createOriginMarker(stepGeometry).addTo(routeMarkerLayer)\n break\n case \"destination-marker\":\n const extrudeConfig = _.get(this.#mapConfig, \"extrude\")\n if (destinationFeature.feature_type === \"occupant\") {\n const stepId = _.get(stepGeometry, \"id\")\n // !Update step ID to occupant destination feature ID to prevent unexpected clearing of occupant element from map\n const normalizedDestinationFeature = {\n ...destinationFeature,\n id: stepId,\n }\n const logoUrl = _.get(\n normalizedDestinationFeature,\n \"properties.logo.url\"\n )\n const createOccupantDestinationMarkerFn = logoUrl\n ? createDestinationLogoMarker\n : createDestinationPinMarker\n stepElement = createOccupantDestinationMarkerFn(\n normalizedDestinationFeature,\n { extrudeConfig }\n ).addTo(routeMarkerLayer)\n break\n }\n stepElement = createDestinationPinMarker(destinationFeature, {\n extrudeConfig,\n }).addTo(routeMarkerLayer)\n break\n default:\n this.#navigationGeometries[stepGeometry.id] = stepElement\n break\n }\n break\n default:\n break\n }\n if (stepElement) {\n const { id, feature_type: featureType } = stepGeometry\n // Add tot Elements object\n this.#elements[id] = {\n geometry: stepElement,\n featureType,\n properties: { ...stepGeometry, ...properties },\n }\n //\n }\n } catch (err) {\n // console.log(err, {\n // index: index,\n // stepGeometries,\n // })\n // throw err;\n console.log(err)\n }\n })\n }\n\n createOverviewStepPathByOrdinal = (stepGeometries, viewingOrdinal) => {\n const { createLineStringFromGeometries } = this.#styler\n const initialStepGeometries = stepGeometries\n .filter(({ properties }) => properties.ordinal === viewingOrdinal)\n .map(({ geometry }) => geometry)\n return createLineStringFromGeometries(initialStepGeometries)\n }\n\n clearNavigationGeometries(): void {\n // Remove origin and destination markers from the highlight layer\n const routeMarkerLayer = this.map.getLayer(\n HIGHLIGHT_LAYER_NAME\n ) as OverlayLayer\n const originMarkerGeometry = _.get(\n this.#elements,\n `${ORIGIN_MARKER_ID}.geometry`\n )\n const destinationMarkerGeometry = _.get(\n this.#elements,\n `${DESTINATION_MARKER_ID}.geometry`\n )\n const geometriesToRemove = _.compact([\n originMarkerGeometry,\n destinationMarkerGeometry,\n ])\n\n routeMarkerLayer.removeGeometry(geometriesToRemove)\n\n this.#elements[ORIGIN_MARKER_ID] = null\n this.#elements[DESTINATION_MARKER_ID] = null\n\n // Filter out NavigationPath objects from the global this.#object3ds list\n this.#object3ds = this.#object3ds.filter(\n (obj) => !(obj instanceof NavigationPath)\n )\n\n // Remove related navigation geometry objects\n const objects = this.#navigationGeometries || {}\n _.forEach(objects, (obj) => {\n if (!obj) return\n this.#navigationGeometries[obj.properties.id] = null\n obj.remove()\n })\n }\n /**\n * END of Navigation\n ****************************/\n\n /**\n * hide/show venue 3dmodel\n **/\n\n hideVenueObjects = () => {\n this.showVenueObject = false\n }\n showVenueObjects = () => {\n this.showVenueObject = true\n }\n\n /**\n * Other functions\n */\n\n enableClick = () => this.map.config({ geometryEvents: true })\n disableClick = () => this.map.config({ geometryEvents: false })\n\n freeze = () => this.map.config({ zoomable: false, draggable: false })\n unfreeze = () => this.map.config({ zoomable: true, draggable: true })\n\n /**\n * render (frame)\n */\n \n render() {\n // TODO: Update User Location marker position\n const view = this.map.getView()\n const currBearing = view.bearing\n this.threeLayer._needsUpdate = !this.threeLayer._needsUpdate\n if (this.threeLayer._needsUpdate) {\n // @ts-ignore\n this.threeLayer.redraw()\n }\n\n if (this.threeLayer) {\n const currentView = this.camera.getView()\n const objectOpacity = _.clamp(38 - 2 * currentView.zoom, 0, 1)\n\n this.#objects.forEach((object) => {\n object.getObject3d().traverse((child) => {\n if (child.isMesh) child.material.opacity = objectOpacity\n //TODO: recheck this line if it actually works\n /** set Mesh visible = false when opacity is 0\n * and true when opacity > 0\n */\n child.visible = !!objectOpacity\n })\n object.getObject3d().visible = !!objectOpacity\n })\n\n if (this.#billboardObjects) {\n this.#billboardObjects.forEach((object) => {\n const objectScale = _.clamp(\n 20 - 1 * currentView.zoom,\n 1,\n 1.05\n )\n object.getObject3d().scale.set(objectScale, objectScale, 1)\n })\n }\n\n /*\n * The layer appears while zooming in and disappears when zooming out,\n * fully vanishing when the Venue Model is visible (opacity: 1).\n */\n if (this.#isLayersFadingOnZoom) {\n const layerOpacity = _.clamp(1 - objectOpacity, 0, 1)\n // Fading 2D layers.\n LAYERS.forEach((layerKey) => {\n const layer = this.map.getLayer(layerKey)\n if (layer) layer.setOpacity(layerOpacity)\n })\n\n // Fading 3D units, such as extruded units.\n this.setFeatureObject3DsOpacity(layerOpacity)\n\n // Fading sprite markers, such as billboards and amenity markers.\n this.setSpriteMarkersOpacity(layerOpacity)\n }\n\n this.#venueObjects.forEach((object) => {\n object.getObject3d().traverse((child) => {\n if (child.isMesh) child.material.opacity = objectOpacity\n /** set Mesh visible = false when opacity is 0\n * and true when opacity > 0\n */\n child.visible = this.showVenueObject && objectOpacity > 0.4\n })\n })\n\n // // Update bearing to each GroundLabel to determine if text should flip or not\n // this.#groundObjects.forEach((gLabel) => {\n // gLabel.bearing = currBearing\n // })\n }\n\n this.#animationsToRun.forEach(({ callback }) => callback(this))\n\n //update TWEEN.js animaton\n TWEEN.update()\n\n requestAnimationFrame(this.render.bind(this))\n }\n}\n","import { IHighlightOptions, ISetHighlight2DElementIdsOptions } from \"./types\"\n\nconst defaultLayerOption = { enableAltitude: true }\n\nconst VENUE = \"venue\"\nconst LEVEL = \"level\"\nconst UNIT = \"unit\"\nconst FIXTURE = \"fixture\"\nconst KIOSK = \"kiosk\"\nconst OPENING = \"opening\"\nconst SECTION = \"section\"\nconst FOOTPRINT = \"footprint\"\n\nconst AMENITY = \"amenity\"\nconst OCCUPANT = \"occupant\"\n\nconst GEOLOCATION = \"geolocation\"\nconst ORIGIN_MARKER = \"origin-marker\"\nconst DESTINATION_MARKER = \"destination-marker\"\n\nconst DECORATION = \"decoration\"\n\nexport const BASE_LAYER_NAME = \"base\"\nexport const POI_MARKER_LAYER_NAME = \"poi\"\nexport const MARKER_LAYER_NAME = \"marker\"\nexport const HIGHLIGHT_LAYER_NAME = \"highlight\"\nexport const USER_LOCATION_LAYER_NAME = \"user_location\"\n\nexport const ORIGIN_MARKER_ID = \"master-origin-marker\"\nexport const DESTINATION_MARKER_ID = \"master-destination-marker\"\nexport const USER_LOCATION_ELEMENT_ID = \"user_location\"\nexport const LAST_USER_LOCATION_ELEMENT_ID_PREFIX = \"last_user_location-\"\n\nexport const LOCALE_SYMBOL_KEY = \"locale_symbol\"\nexport const DEFAULT_LOCALE = \"en\"\n\nexport const LAYERS = [\n BASE_LAYER_NAME,\n POI_MARKER_LAYER_NAME,\n HIGHLIGHT_LAYER_NAME,\n USER_LOCATION_LAYER_NAME,\n]\n\nexport const LAYER_OPTIONS = {\n [BASE_LAYER_NAME]: {\n ...defaultLayerOption,\n forceRenderOnMoving: true,\n forceRenderOnRotating: true,\n forceRenderOnZooming: true,\n },\n [POI_MARKER_LAYER_NAME]: {\n ...defaultLayerOption,\n forceRenderOnMoving: true,\n forceRenderOnRotating: true,\n forceRenderOnZooming: true,\n zIndex: 10,\n collision: true,\n collisionDelay: 1200,\n },\n [MARKER_LAYER_NAME]: { ...defaultLayerOption },\n [HIGHLIGHT_LAYER_NAME]: { ...defaultLayerOption, zIndex: 98 },\n [USER_LOCATION_LAYER_NAME]: { ...defaultLayerOption, zIndex: 99 },\n}\n\nexport const LAYER_FEATURE_TYPE_OBJ = {\n [VENUE]: BASE_LAYER_NAME,\n [LEVEL]: BASE_LAYER_NAME,\n [UNIT]: BASE_LAYER_NAME,\n [FIXTURE]: BASE_LAYER_NAME,\n [KIOSK]: BASE_LAYER_NAME,\n [OPENING]: BASE_LAYER_NAME,\n [SECTION]: BASE_LAYER_NAME,\n [FOOTPRINT]: BASE_LAYER_NAME,\n [AMENITY]: MARKER_LAYER_NAME,\n [OCCUPANT]: POI_MARKER_LAYER_NAME,\n [GEOLOCATION]: USER_LOCATION_LAYER_NAME,\n [ORIGIN_MARKER]: HIGHLIGHT_LAYER_NAME,\n [DESTINATION_MARKER]: HIGHLIGHT_LAYER_NAME,\n [DECORATION]: BASE_LAYER_NAME,\n}\n\n/** Custom Venue Platform Events. Prefix with \"venue:\" to avoid collision */\nexport const VENUE_EVENTS = {\n VENUE_MOVEINTOVIEW: \"venue:venuemoveintoview\", // When a map is moved and a venue moved into a viewport\n}\n","import _ from \"lodash\"\nimport {\n Polygon,\n MultiPolygon,\n LineString,\n Marker,\n Coordinate,\n MultiLineString,\n ui,\n} from \"maptalks\"\nimport turfCenter from \"@turf/center\"\nimport turfBuffer from \"@turf/buffer\"\n\nimport {\n TextureLoader,\n SpriteMaterial,\n MeshLambertMaterial,\n} from \"three\"\n\nimport {\n SpriteMarker,\n Billboard,\n NavigationPath,\n} from \"../object3d\"\nimport { getCenterFromGeometry, createPolygonFromLineString } from \"./geometry\"\nimport { createSVGPathFromMarkerSymbol, svgToPng } from \"./svg\"\n\nconst GeometryType = {\n Polygon,\n MultiPolygon,\n}\n\nconst ORDINAL_HEIGHT = 0 // in version 3D change ORDINAL_HEIGHT for set altitude of geometry\n\nconst VENUE_Z_INDEX = 0\n\nconst LEVEL_Z_INDEX = 2\nconst UNIT_Z_INDEX = 3\nconst FIXTURE_Z_INDEX = 4\nconst DECORATION_Z_INDEX = 4\nconst KIOSK_Z_INDEX = 5\nconst OPENING_Z_INDEX = 3\nconst SECTION_Z_INDEX = 6\nconst USER_LOCATION_Z_INDEX = 99\nconst LAST_LOCATION_Z_INDEX = USER_LOCATION_Z_INDEX - 1\n\nconst PREFIX_HIGHLIGHTED_SYMBOL_KEY = \"highlighted\"\nconst SPRITE_MARKER_FEATURE = [\n \"amenity-atm\",\n \"amenity-babychanging\",\n \"amenity-strollerrental\",\n \"amenity-boardinggate.ferry\",\n \"amenity-elevator\",\n \"amenity-escalator\",\n \"amenity-stairs\",\n \"amenity-information\",\n \"amenity-information.transit\",\n \"amenity-wheelchair\",\n \"amenity-restroom\",\n \"amenity-restroom.male\",\n \"amenity-restroom.female\",\n \"amenity-restroom.wheelchair\",\n \"amenity-restroom.family\",\n \"amenity-restroom.unisex\",\n \"amenity-taxi\",\n \"amenity-groundtransportation\",\n \"amenity-bus\",\n \"amenity-bus.muni\",\n \"amenity-shuttle\",\n \"amenity-parking\",\n \"amenity-parking.shortterm\",\n \"amenity-parking.longterm\",\n \"amenity-parking.waitingarea\",\n \"amenity-parking.compact\",\n \"amenity-parking.ev\",\n \"amenity-parking.bicycle\",\n \"amenity-parking.motorcycle\",\n \"amenity-privatelounge\",\n \"amenity-rideshare\",\n \"amenity-valet\",\n \"amenity-landmark\",\n \"amenity-rail.muni\",\n \"amenity-service\",\n \"amenity-smokingarea\",\n \"amenity-ticketing\",\n \"amenity-meetingpoint\",\n \"amenity-prayerroom\",\n \"amenity-firstaid\",\n \"amenity-ticketing.rail\",\n \"amenity-exhibit\",\n \"amenity-mothersroom\",\n \"amenity-checkin.desk\",\n \"amenity-baggagestorage\",\n \"amenity-baggagecarts\",\n \"amenity-library\",\n \"amenity-coinlocker\",\n \"amenity-powerchargingstation\",\n \"amenity-wheelchairassit\",\n \"amenity-lostandfound\",\n \"amenity-foodservice\",\n \"amenity-businesscenter\",\n \"amenity-guestservices\",\n \"amenity-emergencyshelter\",\n \"amenity-prayerroom.buddhism\",\n \"amenity-defibrillator\",\n \"amenity-drinkingfountain\",\n \"amenity-handsanitizerstation\",\n \"amenity-unspecified\",\n \"amenity-entry\",\n \"amenity-fireextinguisher\",\n \"amenity-security\",\n \"amenity-seating\",\n \"amenity-copymachine\",\n \"amenity-fieldofplay\",\n \"amenity-fieldofplay.soccer\",\n \"amenity-amphitheater\",\n \"amenity-hoteling\",\n \"occupant-currencyexchange\",\n \"occupant-donationcenter\",\n \"occupant-bank\",\n \"occupant-books\",\n \"occupant-postoffice\",\n \"opening-emergencyexit\",\n]\n\nconst SPRITE_HIGHLIGHT_MARKER_FEATURE = SPRITE_MARKER_FEATURE.map(\n (featCate) =>\n `${PREFIX_HIGHLIGHTED_SYMBOL_KEY}-${featCate.split(\"-\").join(\".\")}`\n)\n\nconst OCCUPANT_TEXT_MARKER_CLASSNAME = \"mtk-occupant-text-marker\"\n\nconst getAltitude = (properties) =>\n Math.max(0, properties.ordinal * ORDINAL_HEIGHT || 0)\n\n\nconst createWaterFixture = (feature, style, options = {}) => {\n const { geometry, properties } = feature\n const { allowOverride, inheritFillColorToLine, zIndex } = options\n const symbolStyle = { ...style }\n\n if (allowOverride) _.merge(symbolStyle, properties.style)\n if (inheritFillColorToLine) symbolStyle.lineColor = symbolStyle.polygonFill\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: {\n ...style,\n },\n zIndex,\n })\n}\n\nconst createVegetationFixture = (feature, style, options = {}) => {\n const { geometry, properties } = feature\n const { allowOverride, inheritFillColorToLine, zIndex } = options\n const symbolStyle = { ...style }\n\n if (allowOverride) _.merge(symbolStyle, properties.style)\n if (inheritFillColorToLine) symbolStyle.lineColor = symbolStyle.polygonFill\n\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: {\n ...symbolStyle,\n },\n zIndex,\n })\n}\n\nconst createObstructionalFixture = (feature, style = {}, options = {}) => {\n const { geometry, properties = {} } = feature\n const { model3d } = properties\n const { allowOverride, inheritFillColorToLine, zIndex } = options\n const symbolStyle = { ...style }\n if (!_.isEmpty(model3d)) return\n if (allowOverride) _.merge(symbolStyle, properties.style)\n if (inheritFillColorToLine) symbolStyle.lineColor = symbolStyle.polygonFill\n //create polygon with line-offset if geometry is lineString\n if (geometry.type === \"LineString\") {\n const polygon = createPolygonFromLineString(geometry)\n return new GeometryType[\"Polygon\"](polygon, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: symbolStyle,\n defaultSymbol: symbolStyle,\n zIndex,\n })\n }\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: symbolStyle,\n defaultSymbol: symbolStyle,\n zIndex,\n })\n}\n\nconst createVegetationSection = (feature, symbol = {}) => {\n const { geometry, properties } = feature\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol,\n zIndex: SECTION_Z_INDEX,\n })\n}\n\nconst creatingSeatingSection = (feature, symbol = {}) => {\n const { geometry, properties } = feature\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol,\n zIndex: SECTION_Z_INDEX,\n })\n}\n\nconst creatingDefaultSection = (feature, symbol = {}) => {\n const { geometry, properties } = feature\n try {\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol,\n zIndex: SECTION_Z_INDEX,\n })\n } catch (error) {\n console.warn(`Error creatingDefaultSection`, geometry.type)\n }\n}\n\nconst createEatingDrinkingSection = (feature, symbol = {}) => {\n const { geometry, properties } = feature\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol,\n zIndex: SECTION_Z_INDEX,\n })\n}\n\nconst createPrincipalOpening = (feature, style, options = {}) => {\n const { geometry, properties } = feature\n const { allowOverride, zIndex } = options\n const symbolStyle = { ...style }\n if (allowOverride) _.merge(symbolStyle, properties.style)\n\n try {\n return new LineString(geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: symbolStyle,\n zIndex,\n })\n } catch (error) {\n console.log(`error creating pedestrian principal opening:`, feature)\n }\n}\n\nconst createEmergencyExitOpening = (feature, style, options = {}) => {\n const { geometry, properties } = feature\n const { allowOverride, zIndex } = options\n const symbolStyle = { ...style }\n if (allowOverride) _.merge(symbolStyle, properties.style)\n\n try {\n return new LineString(geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: symbolStyle,\n zIndex,\n })\n } catch (error) {\n console.log(`error creating emergency exit opening:`, feature)\n }\n}\nconst createPedestrianOpening = (feature, style, options = {}) => {\n const { geometry, properties, id } = feature\n const { allowOverride, zIndex } = options\n const symbolStyle = { ...style }\n\n if (allowOverride) _.merge(symbolStyle, properties.style)\n\n try {\n return new LineString(geometry.coordinates, {\n properties: {\n id,\n feature_type: \"opening\",\n category: properties.category,\n altitude: getAltitude(properties),\n },\n symbol: symbolStyle,\n zIndex,\n })\n } catch (error) {\n console.log(`error creating pedestrian opening:`, feature)\n }\n}\n\nconst createExtrudePolygon = (\n geometry,\n threeLayer,\n material,\n height,\n properties = {},\n options\n) => {\n const { offset = 0, altitude = 0 } = options\n const offsetGeometry = turfBuffer(geometry, offset, { units: \"meters\" })\n const object = threeLayer.toExtrudePolygon(\n offsetGeometry,\n { height, async: true, altitude },\n material\n )\n object.properties = properties\n return object\n}\n\nconst create3DMarker = (\n coordinates,\n options,\n material,\n threeLayer,\n markerProperties\n) => {\n return new SpriteMarker(\n coordinates,\n options,\n material,\n threeLayer,\n markerProperties\n )\n}\n\n/**\n * Retrieves the extrude configuration for a feature.\n *\n * @param {Object} baseExtrudeConfig - The default extrude configuration defined in the map settings within the app config content type.\n * @param {Object} feature - The target feature object for which the extrude value is required.\n * @returns {Object|undefined} - The extrude value from the feature's `properties` field, or the base extrude configuration as a fallback if not defined.\n */\nexport const getExtrudeConfigByFeature = (baseExtrudeConfig, feature = {}) => {\n const { feature_type: featureType } = feature\n // Retrieve extrude configuration from the extrude field in the feature's properties\n const featureExtrudeConfig = _.get(feature, \"properties.extrude\")\n\n // Retrieve extrude configuration from the base extrude settings. (Map Config)\n const featureCategory = _.get(feature, \"properties.category\")\n const baseFeatureExtrudeConfig = _.get(\n baseExtrudeConfig,\n `${featureType}.${featureCategory || featureType}`\n )\n\n // Fallback to base extrude configuration if the feature's extrude field is not defined.\n return featureExtrudeConfig ?? baseFeatureExtrudeConfig\n}\n\nconst getFeatureMarkerConfig = (feature, mapConfig = {}) => {\n const { textMarkerType, extrudeConfig = {}, symbol } = mapConfig\n\n const location = getLocationByFeature(feature)\n const featureExtrudeConfig = getExtrudeConfigByFeature(\n extrudeConfig,\n location\n )\n\n return {\n markerSymbol: symbol,\n textMarkerType,\n featureExtrudeConfig,\n }\n}\n\nexport const createSpriteMaterialByLabelSymbol = (labelSymbol = []) => {\n const material = new SpriteMaterial()\n try {\n const [base, icon] = labelSymbol\n const { markerWidth: baseWidth = 24 } = base\n const { markerWidth: iconWidth = 24 } = icon\n const viewBoxDimension = Math.max(baseWidth, iconWidth)\n\n const baseSVG = createSVGPathFromMarkerSymbol(base)\n const iconSVG = createSVGPathFromMarkerSymbol(icon)\n const svg = `<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${viewBoxDimension}\" height=\"${viewBoxDimension}\">${baseSVG}${iconSVG}</svg>`\n const textureLoader = new TextureLoader()\n const scaleFactor = 200 / 24 // Scale factor to upscale from 24px to 200px to ensure the resolution is high enough\n\n svgToPng(svg, scaleFactor).then((png) => {\n const texture = textureLoader.load(png, () => {\n material.map = texture\n material.needsUpdate = true\n })\n })\n } catch (error) {\n console.warn(`Error createSpriteMaterialByLabelSymbol: `, labelSymbol)\n }\n return material\n}\n\nexport const createStyledUIMarkerElement = ({\n style,\n textContent,\n className,\n}) => {\n const element = document.createElement(\"div\")\n for (const key in style) {\n element.style[key] = style[key]\n }\n element.className = className\n element.textContent = textContent\n //! Use outerHTML to return HTML string instead of element object to avoid DOM event warnings from Maptalks.js.\n return element.outerHTML\n}\n\nexport const styledFeatureGenerator = (mapTheme) => {\n const getElementSymbol = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeTheme = _.get(mapTheme, `${featureType}.geometry.symbol`)\n if (featureType === key) return featureTypeTheme\n const categoryTheme = _.get(mapTheme, `${key}.geometry.symbol`)\n return _.merge({}, featureTypeTheme, categoryTheme)\n }\n\n const getLabelSymbol = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeTheme = _.get(mapTheme, `${featureType}.label`)\n const categoryTheme = _.get(mapTheme, `${key}.label`)\n const mergedSymbol = _.merge({}, featureTypeTheme, categoryTheme)\n let symbols = _.values(_.map(mergedSymbol, \"symbol\"))\n const markerIndexToMove = symbols.findIndex(\n ({ elementType }) => elementType === \"label.marker\"\n )\n\n // Move the label.marker symbol to the last of array\n if (markerIndexToMove >= 0) {\n const markerSymbolToMove = _.pullAt(symbols, markerIndexToMove)[0]\n symbols.push(markerSymbolToMove)\n }\n\n return symbols\n }\n\n const getUIMarkerSymbol = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeTheme = _.get(mapTheme, `${featureType}.ui.marker`)\n const categoryTheme = _.get(mapTheme, `${key}.ui.marker`)\n const mergedSymbol = _.merge({}, featureTypeTheme, categoryTheme)\n const symbol = _.get(mergedSymbol, \"symbol\")\n return symbol\n }\n const getUIMarkerOptions = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeTheme = _.get(mapTheme, `${featureType}.ui.marker`)\n const categoryTheme = _.get(mapTheme, `${key}.ui.marker`)\n const mergedSymbol = _.merge({}, featureTypeTheme, categoryTheme)\n const options = _.get(mergedSymbol, \"options\")\n return options\n }\n\n const getLabelOptions = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeSymbol = _.get(mapTheme, `${featureType}.label`)\n const categorySymbol = _.get(mapTheme, `${key}.label`)\n const mergedSymbol = _.merge({}, featureTypeSymbol, categorySymbol)\n return _.reduce(\n mergedSymbol,\n (acc, symbol) => ({ ...acc, ..._.get(symbol, \"options\", {}) }),\n {}\n )\n }\n\n const generateSpriteMarkerMaterial = () => {\n return SPRITE_MARKER_FEATURE.reduce((acc, featCate) => {\n const [featureType, category] = featCate.split(\"-\")\n const key = `${featureType}.${category}`\n const labelSymbol = getLabelSymbol(key)\n const material = createSpriteMaterialByLabelSymbol(labelSymbol)\n return { ...acc, [key]: material }\n }, {})\n }\n\n const generateSpriteHighlightMarkerOption = () => {\n return SPRITE_HIGHLIGHT_MARKER_FEATURE.reduce((acc, featCate) => {\n const categoryKey = _.last(featCate.split(\"-\")) // Example: highlighted-amenity.atm -> amenity.atm\n const defaultLabelSymbol = getLabelSymbol(categoryKey)\n const highlightLabelSymbol = getLabelSymbol(featCate)\n const [defaultBase, defaultIcon] = defaultLabelSymbol\n const [highlightBase, highlightIcon] = highlightLabelSymbol\n const base = _.merge({}, defaultBase, highlightBase)\n const icon = _.merge({}, defaultIcon, highlightIcon)\n\n const material = createSpriteMaterialByLabelSymbol([base, icon])\n const options = getLabelOptions(featCate)\n return { ...acc, [featCate]: { material, options } }\n }, {})\n }\n\n const spriteMarkerMaterialObj = generateSpriteMarkerMaterial()\n const spriteHighlightMarkerOptionObj = generateSpriteHighlightMarkerOption()\n\n const getElementOptions = (key) => {\n const [featureType] = key.split(\".\")\n const featureTypeOptions = _.get(\n mapTheme,\n `${featureType}.geometry.options`\n )\n\n const categoryOptions = _.get(mapTheme, `${key}.geometry.options`)\n\n return _.merge({}, featureTypeOptions, categoryOptions)\n }\n\n const createOccupantMarker = (feature, locatedFeature, mapConfig) => {\n const { textMarkerType, featureExtrudeConfig } = getFeatureMarkerConfig(\n feature,\n mapConfig\n )\n const markerHeight = _.get(featureExtrudeConfig, \"height\", 0)\n const { properties, id, feature_type } = feature\n if (!properties.anchor) return\n\n /**\n * Prepare geometry for occupant marker positioning:\n * - Use anchor coordinates if the location feature is the main location\n * - Otherwise, use the center of the location feature\n */\n const mainLocationId =\n _.get(properties, \"unit.id\") || _.get(properties, \"kiosk.id\")\n const isMainLocationFeature = mainLocationId === locatedFeature?.id\n const { geometry: mainLocationGeometry } = properties?.anchor\n const geometry = isMainLocationFeature\n ? mainLocationGeometry\n : turfCenter(locatedFeature)?.geometry\n\n const baseProperties = {\n id,\n feature_type,\n category: properties.category,\n altitude: getAltitude(properties),\n }\n const occupantName = _.isEmpty(properties.short_name)\n ? properties.name\n : properties.short_name\n\n if (locatedFeature) {\n const { feature_type, properties } = locatedFeature\n const { category } = properties\n const locatedLabelOption =\n feature_type === \"kiosk\"\n ? getLabelOptions(`${feature_type}`)\n : getLabelOptions(`${feature_type}.${category}`)\n const { hidden = false } = locatedLabelOption || {}\n if (hidden) return\n }\n\n const getValidatedRenderType = (requestedType, logoUrl) => {\n // If requestType is \"Logo\" or \"Logo + Name\" and no logo, fallback to \"Name\"\n if (requestedType === \"Logo\" || requestedType === \"Logo + Name\") {\n return logoUrl ? requestedType : \"Name\"\n }\n return requestedType\n }\n\n const logoUrl = _.get(properties, \"logo.url\")\n const requestedRenderType = _.get(properties, \"render_type\", \"Name\")\n const renderType = getValidatedRenderType(requestedRenderType, logoUrl)\n if (renderType === \"Label\") return null\n\n const renderPriority = properties.render_priority || 3\n const labelSymbol = getLabelSymbol(`occupant-${_.toLower(renderType)}`)\n const markerSymbol = _.last(labelSymbol)\n\n const coordinates = _.get(geometry, \"coordinates\")\n\n const priorityLabelSymbol = getLabelSymbol(\n `occupant-${_.toLower(renderType)}-${renderPriority}`\n )\n const priorityMarkerSymbol = _.last(priorityLabelSymbol) || {}\n\n switch (renderType) {\n case \"Logo\":\n _.set(priorityMarkerSymbol, \"markerFile\", logoUrl)\n\n return new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties) + markerHeight,\n ...baseProperties,\n },\n symbol: priorityLabelSymbol,\n })\n\n case \"Logo + Name\":\n return new Marker(coordinates, {\n properties: {\n name: occupantName.en,\n altitude: getAltitude(properties) + markerHeight,\n ...baseProperties,\n },\n symbol: {\n textName: \"{name}\",\n markerFile: logoUrl,\n textHaloRadius: {\n stops: [\n [20, 1],\n [21, 2],\n ],\n },\n ...markerSymbol,\n ...priorityMarkerSymbol,\n },\n })\n case \"None\":\n return new ui.UIMarker(coordinates, {\n properties: { ...baseProperties },\n content: createStyledUIMarkerElement({\n style: { display: \"none\" },\n textContent: occupantName.en,\n }),\n altitude: getAltitude(properties) + markerHeight,\n })\n case \"Name\":\n default:\n if (textMarkerType === \"marker\") {\n return new Marker(coordinates, {\n properties: {\n name: occupantName.en,\n altitude: getAltitude(properties) + markerHeight,\n ...baseProperties,\n },\n symbol: {\n textName: \"{name}\",\n //TODO:: implement symbol scaler later\n textHaloRadius: {\n stops: [\n [20, 1],\n [21, 2],\n ],\n },\n ...markerSymbol,\n ...priorityMarkerSymbol,\n },\n })\n }\n\n const uiMarkerSymbol = getUIMarkerSymbol(\n `occupant-${_.toLower(renderType)}`\n )\n const uiMarkerPrioritySymbol = getUIMarkerSymbol(\n `occupant-${_.toLower(renderType)}-${renderPriority}`\n )\n const uiMarkerPriorityOptions = getUIMarkerOptions(\n `occupant-${_.toLower(renderType)}-${renderPriority}`\n )\n\n const style = { ...uiMarkerSymbol, ...uiMarkerPrioritySymbol }\n return new ui.UIMarker(coordinates, {\n properties: { ...baseProperties },\n content: createStyledUIMarkerElement({\n style,\n textContent: occupantName.en,\n className: OCCUPANT_TEXT_MARKER_CLASSNAME,\n }),\n collision: true,\n collisionFadeIn: true,\n altitude: getAltitude(properties) + markerHeight,\n ...uiMarkerPriorityOptions,\n })\n }\n }\n\n const getFeatureProperties = (feature) => {\n const { id, feature_type, properties } = feature\n const { category, ordinal, style = {} } = properties\n const elementStyle = getElementSymbol(`${feature_type}.${category}`)\n const { allowOverride } = getElementOptions(`${feature_type}.${category}`)\n if (allowOverride) _.merge(elementStyle, style)\n const { polygonFill: color } = elementStyle\n const featureProperty = {\n id,\n feature_type,\n category: category || feature_type,\n ordinal,\n defaultColor: color,\n }\n return featureProperty\n }\n\n return {\n getElementSymbol,\n getHilighPolygonalSymbol: (type) => {\n switch (type) {\n case \"MultiPolygon\":\n case \"Polygon\": {\n return getElementSymbol(\"hilight-polygonal\")\n }\n case \"Point\": {\n return getElementSymbol(\"hilight-marker\")\n }\n default:\n break\n }\n },\n getHighlightMarkerSymbol: () => {\n return getElementSymbol(\"highlighted-marker\")\n },\n createVenue: (feature) => {\n const { geometry, feature_type } = feature\n const symbolStyle = getElementSymbol(feature_type)\n return new GeometryType[geometry.type](geometry.coordinates, {\n symbol: {\n ...symbolStyle,\n },\n zIndex: VENUE_Z_INDEX,\n })\n },\n\n createLevel: (feature) => {\n const { geometry, properties, feature_type } = feature\n const { category } = properties\n\n const style = getElementSymbol(`${feature_type}.${category}`)\n // const options = getElementOptions(`${feature_type}.${category}`)\n\n return new GeometryType[geometry.type](geometry.coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: {\n ...style,\n },\n zIndex: LEVEL_Z_INDEX,\n })\n },\n\n\n createMarker: (feature) => {\n try {\n const { geometry, properties } = feature\n const coordinates = getCenterFromGeometry(geometry)\n const markerSymbol = getElementSymbol(\"pin-marker\")\n return new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n symbol: markerSymbol,\n })\n } catch (err) {\n console.log(`error creating marker:`, feature)\n }\n },\n createOriginMarker: (feature) => {\n const { id, geometry, properties } = feature\n const coordinates = getCenterFromGeometry(geometry)\n const markerSymbol = getElementSymbol(\"origin-marker\")\n try {\n return new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties),\n },\n id,\n symbol: markerSymbol,\n })\n } catch (error) {\n console.log(`error creating origin marker:`, feature)\n }\n },\n createDestinationPinMarker: (feature, mapConfig) => {\n const { featureExtrudeConfig } = getFeatureMarkerConfig(\n feature,\n mapConfig\n )\n const markerHeight = _.get(featureExtrudeConfig, \"height\")\n // Get Label from located unit / kiosk\n const { id, properties } = feature\n const geometry =\n _.get(feature, \"geometry\") ||\n _.get(feature, \"properties.anchor.geometry\")\n const coordinates = getCenterFromGeometry(geometry)\n const symbol = getElementSymbol(\"pin-marker\")\n try {\n return new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties) + markerHeight,\n },\n id,\n symbol,\n })\n } catch (error) {\n console.log(`error creating destination marker:`, feature)\n }\n },\n createDestinationLogoMarker: (feature, mapConfig = {}) => {\n const { featureExtrudeConfig } = getFeatureMarkerConfig(\n feature,\n mapConfig\n )\n const markerHeight = _.get(featureExtrudeConfig, \"height\", 0)\n\n // Get Label from located unit / kiosk\n const { properties, id } = feature\n const { geometry } = properties.anchor\n const logoUrl = _.get(properties, \"logo.url\")\n const coordinates = getCenterFromGeometry(geometry)\n const [markerBase, markerLabel] = getLabelSymbol(\n \"highlighted-logo-marker\"\n )\n try {\n return new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties) + markerHeight,\n },\n id,\n symbol: [markerBase, { ...markerLabel, markerFile: logoUrl }],\n })\n } catch (error) {\n console.log(`error creating destination marker:`, feature)\n }\n },\n\n createUserLocationMarker: (feature) => {\n try {\n const { geometry, properties } = feature\n const coordinates = getCenterFromGeometry(geometry)\n const symbolStyle = getElementSymbol(\"user-location\") || {}\n const marker = new Marker(coordinates, {\n properties: {\n altitude: getAltitude(properties),\n ordinal: properties.ordinal !== null ? properties.ordinal : null,\n },\n symbol: symbolStyle.start,\n zIndex: USER_LOCATION_Z_INDEX,\n })\n\n marker.animate(\n {\n symbol: symbolStyle.end,\n },\n {\n repeat: true,\n easing: \"upAndDown\",\n duration: 1500,\n }\n )\n return marker\n } catch (err) {\n console.log(`error creating marker:`, feature)\n }\n },\n\n createLastUserLocationMarker: (feature) => {\n try {\n const { geometry, properties } = feature\n const coordinates = getCenterFromGeometry(geometry)\n const symbolStyle = getElementSymbol(\"last-user-location\") || {}\n const options = getElementOptions(\"last-user-location\") || {}\n const marker = new Marker(coordinates, {\n properties: {\n ...options,\n altitude: getAltitude(properties),\n ordinal: properties.ordinal !== null ? properties.ordinal : null,\n },\n symbol: symbolStyle,\n zIndex: LAST_LOCATION_Z_INDEX,\n })\n\n return marker\n } catch (err) {\n console.log(`error creating marker:`, feature)\n }\n },\n\n createHighlightOccupantMarker: (feature, mapConfig) => {\n const { featureExtrudeConfig, markerSymbol } = getFeatureMarkerConfig(\n feature,\n mapConfig\n )\n const markerHeight = _.get(featureExtrudeConfig, \"height\")\n const { id, feature_type, properties } = feature\n\n if (!properties.anchor) return\n\n const markerProperties = {\n ...properties,\n id,\n feature_type,\n altitude: getAltitude(properties) + markerHeight,\n }\n\n const { geometry } = properties?.anchor\n const coordinates = _.get(geometry, \"coordinates\")\n const logoUrl = _.get(properties, \"logo.url\")\n\n // If the symbol option is defined, create a marker.\n if (markerSymbol) {\n return new Marker(coordinates, {\n properties: markerProperties,\n symbol: markerSymbol,\n })\n }\n\n //use pin-marker if no logo\n if (!logoUrl) {\n const symbol = getElementSymbol(\"pin-marker\")\n return new Marker(coordinates, {\n properties: markerProperties,\n symbol,\n })\n }\n\n const labelSymbol = getLabelSymbol(\"highlight-occupant-logo\")\n const priorityMarkerSymbol = _.last(labelSymbol) || {}\n _.set(priorityMarkerSymbol, \"markerFile\", logoUrl)\n return new Marker(coordinates, {\n properties: markerProperties,\n symbol: labelSymbol,\n })\n },\n createHighlight2DAmenityMarkerFrom3DMarker: (feature, mapConfig) => {\n const { coordinates, units, kiosk } = feature\n const amenityLocatedUnit = _.first(units)\n\n const unitConfig = getExtrudeConfigByFeature(\n mapConfig,\n amenityLocatedUnit\n )\n const unitHeight = _.get(unitConfig, \"height\", 0)\n const kioskConfig = getExtrudeConfigByFeature(mapConfig, kiosk)\n const kioskHeight = _.get(kioskConfig, \"height\", 0)\n\n const markerHeight = unitHeight + kioskHeight\n\n const symbol = getElementSymbol(\"highlight-amenity-marker\")\n return new Marker(coordinates, {\n properties: {\n ...feature,\n altitude: markerHeight,\n },\n symbol,\n })\n },\n\n createSection: (feature) => {\n const { properties, feature_type } = feature\n const { category } = properties\n const elementStyle = getElementSymbol(`${feature_type}.${category}`)\n switch (category) {\n case \"eatingdrinking\":\n return createEatingDrinkingSection(feature, elementStyle)\n case \"vegetation\":\n return createVegetationSection(feature, elementStyle)\n case \"seating\":\n return creatingSeatingSection(feature, elementStyle)\n default:\n return creatingDefaultSection(feature, elementStyle)\n }\n },\n\n createOccupant: (feature, location, mapConfig) => {\n return createOccupantMarker(feature, location, mapConfig)\n },\n\n createOpening: (feature) => {\n const {\n feature_type,\n properties: { category },\n } = feature\n const elementStyle = getElementSymbol(`${feature_type}.${category}`)\n const options = {\n ...getElementOptions(`${feature_type}.${category}`),\n zIndex: OPENING_Z_INDEX,\n }\n switch (feature.properties.category) {\n case \"pedestrian\":\n return createPedestrianOpening(feature, elementStyle, options)\n case \"pedestrian.principal\":\n return createPrincipalOpening(feature, elementStyle, options)\n case \"emergencyexit\":\n return createEmergencyExitOpening(feature, elementStyle, options)\n default:\n break\n }\n },\n\n createFixture: (feature) => {\n const {\n feature_type,\n properties: { category },\n } = feature\n const elementStyle = getElementSymbol(`${feature_type}.${category}`)\n const options = {\n ...getElementOptions(`${feature_type}.${category}`),\n zIndex: FIXTURE_Z_INDEX,\n }\n switch (feature.properties.category) {\n case \"water\":\n return createWaterFixture(feature, elementStyle, options)\n case \"vegetation\":\n return createVegetationFixture(feature, elementStyle, options)\n case \"equipment\":\n case \"obstruction\":\n case \"stage\":\n case \"desk\":\n case \"wall\":\n return createObstructionalFixture(feature, elementStyle, options)\n default:\n break\n }\n },\n\n createLineStringFromGeometries: (geometries) => {\n const mergedCoordinates = _(geometries)\n .map((geometry) => {\n switch (geometry.type) {\n case \"Point\":\n return [\n geometry?.getCoordinates\n ? geometry?.getCoordinates()\n : new Coordinate(geometry.coordinates),\n ]\n case \"Polygon\":\n return [\n geometry?.getCenter\n ? geometry?.getCenter()\n : new Polygon(geometry.coordinates).getCenter(),\n ]\n case \"MultiPolygon\":\n return [\n geometry?.getCenter\n ? geometry?.getCenter()\n : new MultiPolygon(geometry.coordinates).getCenter(),\n ]\n case \"LineString\":\n default:\n return geometry?.getCoordinates\n ? geometry?.getCoordinates()\n : new LineString(geometry.coordinates).getCoordinates()\n }\n })\n .flatten()\n .value()\n const stepPathLineSymbol = getElementSymbol(\"navigation-path\")\n const startPathSymbolMarker = getElementSymbol(\"navigation-path-start\")\n\n const line = new LineString(mergedCoordinates, {\n smoothness: 0.5,\n symbol: [...stepPathLineSymbol, startPathSymbolMarker],\n })\n\n return line\n },\n create3DStepPath: (feature, threeLayer, option = {}) => {\n const stepPathLineSymbol = getElementSymbol(\"navigation-path\")\n const pathLineSymbol = stepPathLineSymbol[1]\n const pathLineEffect = stepPathLineSymbol[0]\n const lineOptions = {\n color: pathLineSymbol?.lineColor,\n opacity: pathLineSymbol?.lineOpacity,\n }\n const outlineOptions = {\n color: pathLineEffect?.lineColor,\n opacity: pathLineEffect?.lineOpacity,\n }\n\n return new NavigationPath(\n feature,\n threeLayer,\n getFeatureProperties(feature),\n option,\n lineOptions,\n outlineOptions\n )\n },\n\n createDecoration: (decoration, options) => {\n const { type, coordinates } = decoration\n const { id, ordinal, symbol } = options\n const formattedProperties = {\n properties: {\n id,\n altitude: getAltitude(options),\n ordinal,\n },\n symbol,\n zIndex: DECORATION_Z_INDEX,\n }\n switch (type) {\n case \"Polygon\":\n return new Polygon(coordinates, formattedProperties)\n case \"MultiPolygon\":\n return new MultiPolygon(coordinates, formattedProperties)\n case \"LineString\":\n return new LineString(coordinates, formattedProperties)\n case \"MultiLineString\":\n return new MultiLineString(coordinates, formattedProperties)\n default:\n return null\n }\n },\n \n create3DBillboard: (billboard, threeLayer) => {\n const { id, feature_type, properties } = billboard\n const {\n logo,\n altitude,\n scale,\n alphaTest,\n legColor,\n showLeg,\n is_clickable,\n } = properties\n const coordinates = getCenterFromGeometry(billboard.geometry)\n const billboardProperties = {\n ...billboard.properties,\n id,\n feature_type,\n }\n\n const options = {\n altitude,\n scale,\n alphaTest,\n legColor,\n showLeg,\n interactive: is_clickable,\n }\n\n return new Billboard(\n coordinates,\n options,\n logo?.url,\n threeLayer,\n billboardProperties\n )\n },\n create3DAmenityMarker: (feature, threeLayer, config) => {\n const { geometry, properties, feature_type, id } = feature\n const { category, units, kiosk, is_clickable } = properties\n const amenityLocatedUnit = _.first(units)\n const isLocatedUnitModel3dAvailable = !_.isEmpty(\n amenityLocatedUnit?.properties?.model3d\n )\n const isLocatedKioskModel3dAvailable = !_.isEmpty(\n kiosk?.properties?.model3d\n )\n\n const unitConfig = getExtrudeConfigByFeature(config, amenityLocatedUnit)\n const unitHeight = isLocatedUnitModel3dAvailable\n ? 0\n : _.get(unitConfig, \"height\", 0)\n const kioskConfig = getExtrudeConfigByFeature(config, kiosk)\n const kioskHeight = isLocatedKioskModel3dAvailable\n ? 0\n : _.get(kioskConfig, \"height\", 0)\n\n const coordinates = _.get(geometry, \"coordinates\")\n\n const markerProperties = {\n ...properties,\n coordinates,\n id,\n feature_type,\n }\n\n const material = _.get(\n spriteMarkerMaterialObj,\n `${feature_type}.${category}`\n )\n\n const highlightOptions = _.get(\n spriteHighlightMarkerOptionObj,\n `${PREFIX_HIGHLIGHTED_SYMBOL_KEY}-${feature_type}.${category}`\n )\n\n const options = {\n scale: 0.05,\n altitude: unitHeight + kioskHeight,\n highlight: highlightOptions,\n interactive: is_clickable,\n }\n\n return create3DMarker(\n coordinates,\n options,\n material,\n threeLayer,\n markerProperties\n )\n },\n\n create3DOccupantAmenityMarker: (feature, threeLayer, config) => {\n const { geometry, properties, feature_type, id } = feature\n const { category, unit, kiosk } = properties\n const amenityLocation = kiosk || unit\n const locationConfig = getExtrudeConfigByFeature(config, amenityLocation)\n const coordinates = _.get(geometry, \"coordinates\")\n\n const markerProperties = {\n ...properties,\n coordinates,\n id,\n feature_type,\n }\n\n const material = _.get(\n spriteMarkerMaterialObj,\n `${feature_type}.${category}`\n )\n\n const highlightOptions = _.get(\n spriteHighlightMarkerOptionObj,\n `${PREFIX_HIGHLIGHTED_SYMBOL_KEY}-${feature_type}.${category}`\n )\n\n const options = {\n scale: 0.05,\n altitude: _.get(locationConfig, \"height\", 0),\n highlight: highlightOptions,\n }\n\n return create3DMarker(\n coordinates,\n options,\n material,\n threeLayer,\n markerProperties\n )\n },\n create3DOpeningMarker: (feature, threeLayer, config) => {\n const { geometry, properties, feature_type, id } = feature\n const { category, unit, kiosk } = properties\n const amenityLocation = kiosk || unit\n const locationConfig = getExtrudeConfigByFeature(config, amenityLocation)\n const coordinates = _.get(geometry, \"coordinates\")\n\n const markerProperties = {\n ...properties,\n coordinates,\n id,\n feature_type,\n }\n\n const material = _.get(\n spriteMarkerMaterialObj,\n `${feature_type}.${category}`\n )\n\n const highlightOptions = _.get(\n spriteHighlightMarkerOptionObj,\n `${PREFIX_HIGHLIGHTED_SYMBOL_KEY}-${feature_type}.${category}`\n )\n\n const options = {\n scale: 0.05,\n altitude: _.get(locationConfig, \"height\", 0),\n highlight: highlightOptions,\n }\n\n return create3DMarker(\n coordinates,\n options,\n material,\n threeLayer,\n markerProperties\n )\n },\n\n createExtrudedUnit: (unit, threeLayer, options) => {\n const extrudeHeight = _.get(options, \"height\")\n if (!extrudeHeight) return\n //NOTE: this is temporary condition that only extrude when the unit is \"room\"\n const unitProperty = getFeatureProperties(unit)\n //NOTE: offset will be dynamic in future improvement\n const options3d = {\n // TODO: Move to extrude config later\n offset: -0.1,\n altitude: _.get(options, \"altitude\", 0),\n }\n const color = unitProperty.defaultColor\n if (color === \"transparent\") return\n const material = new MeshLambertMaterial({\n color,\n transparent: true,\n })\n //create polygon with line-offset if geometry is lineString\n if (unit.geometry.type === \"LineString\") {\n const polygon = createPolygonFromLineString(unit.geometry)\n const geometry = {\n type: \"Polygon\",\n coordinates: polygon,\n }\n return createExtrudePolygon(\n geometry,\n threeLayer,\n material,\n extrudeHeight,\n unitProperty,\n options3d\n )\n }\n const object = createExtrudePolygon(\n unit.geometry,\n threeLayer,\n material,\n extrudeHeight,\n unitProperty,\n options3d\n )\n return object\n },\n }\n}\n\nconst EXCEPT_AMENITY_LOCATION_CATEGORIES = [\n \"walkway\",\n \"nonpublic\",\n \"parking\",\n \"opentobelow\",\n \"unspecified\",\n]\nexport const getLocationByAmenity = (feature) => {\n const unit = _.get(feature, \"properties.units[0]\", null)\n const unitCategory = _.get(unit, \"properties.category\")\n if (!unit) return feature.id\n return EXCEPT_AMENITY_LOCATION_CATEGORIES.includes(unitCategory)\n ? feature\n : unit\n}\n\nexport const getLocationByOccupant = (feature) => {\n const kiosk = _.get(feature, \"properties.kiosk\", null)\n const unit = _.get(feature, \"properties.anchor.properties.unit\", null)\n return kiosk || unit\n}\n\nexport const getLocationIdByFeature = (feature) => {\n switch (feature?.feature_type) {\n case \"kiosk\":\n case \"unit\":\n case \"opening\":\n return feature.id\n case \"amenity\":\n return getLocationByAmenity(feature)?.id\n case \"occupant\":\n return getLocationByOccupant(feature)?.id\n case \"promotion\":\n case \"event\":\n return feature.properties?.feature_id\n default:\n return\n }\n}\n\nexport const getFeatureByLocationId = (id, features = []) => {\n return features?.find((f) => {\n const mainLocationId = getLocationIdByFeature(f)\n const relatedLocationIds = getRelatedLocationIdsByFeature(f)\n return mainLocationId === id || relatedLocationIds.includes(id)\n })\n}\n\nexport const isClickableFeature = (feature) => {\n const isClickable = _.get(feature, \"properties.is_clickable\")\n switch (feature?.feature_type) {\n case \"amenity\":\n return _.isNull(isClickable) ? true : isClickable\n case \"occupant\":\n return true\n default:\n return\n }\n}\n\nexport const getLocationByFeature = (feature) => {\n switch (feature?.feature_type) {\n case \"amenity\":\n return getLocationByAmenity(feature)\n case \"occupant\":\n return getLocationByOccupant(feature)\n default:\n return\n }\n}\n\n/*\n * Utility functions to retrieve related locations for amenities and occupants.\n * - Used for highlighting on the floor plan.\n * - Displays location details.\n */\n\nexport const getRelatedLocationsByOccupant = (feature) => {\n const kiosks = _.get(feature, \"properties.kiosks\", [])\n const units = _.get(feature, \"properties.units\", [])\n return [...kiosks, ...units]\n}\n\nexport const getRelatedLocationsByAmenity = (feature) => {\n const units = _.get(feature, \"properties.units\", [])\n\n if (units.length === 0) return [feature]\n\n return units.filter((unit) => {\n const unitCategory = _.get(unit, \"properties.category\")\n return !EXCEPT_AMENITY_LOCATION_CATEGORIES.includes(unitCategory)\n })\n}\n\nexport const getRelatedLocationIdsByFeature = (feature) => {\n switch (feature?.feature_type) {\n case \"amenity\":\n return getRelatedLocationsByAmenity(feature).map((v) => v?.id)\n case \"occupant\":\n return getRelatedLocationsByOccupant(feature).map((v) => v?.id)\n default:\n return []\n }\n}\n\nexport const getRelatedLocationsByFeature = (feature) => {\n switch (feature?.feature_type) {\n case \"amenity\":\n return getRelatedLocationsByAmenity(feature)\n case \"occupant\":\n return getRelatedLocationsByOccupant(feature)\n default:\n return []\n }\n}\n\nexport const getOrdinalByLocationId = (locationId, feature) => {\n if (!feature) return null\n\n const mainUnit = _.get(feature, \"properties.unit\")\n const mainKiosk = _.get(feature, \"properties.kiosk\")\n const relatedLocations = getRelatedLocationsByFeature(feature)\n\n const allLocations = [mainUnit, mainKiosk, ...relatedLocations].filter(\n Boolean\n )\n const targetLocation = allLocations.find(\n (location) => location.id === locationId\n )\n\n return targetLocation\n ? _.get(targetLocation, \"properties.level.properties.ordinal\") ||\n _.get(targetLocation, \"properties.ordinal\")\n : null\n}\n","import * as maptalks from \"maptalks\"\nimport { BaseObject } from \"maptalks.three\"\nimport {\n LineBasicMaterial,\n BufferGeometry,\n Float32BufferAttribute,\n Line,\n TextureLoader,\n SpriteMaterial,\n Sprite,\n} from \"three\"\nimport _ from \"lodash\"\n\nconst OPTIONS = {\n altitude: 25,\n scale: 0.00015,\n alphaTest: 0.3,\n legColor: \"#ff0400\",\n showLeg: true,\n}\n\nconst getImgDimension = async (url) => {\n const img = new Image()\n img.src = url\n await img.decode()\n return { naturalWidth: img.naturalWidth, naturalHeight: img.naturalHeight }\n}\n\nexport class Billboard extends BaseObject {\n #layer = null\n constructor(coordinate, options, src, layer, properties) {\n options = maptalks.Util.extend({}, OPTIONS, options, {\n layer,\n coordinate,\n })\n super()\n //Initialize internal configuration\n this.#layer = layer\n this._initOptions(options)\n const {\n altitude = OPTIONS.altitude,\n scale = OPTIONS.scale,\n alphaTest = OPTIONS.alphaTest,\n legColor = OPTIONS.legColor,\n showLeg = OPTIONS.showLeg,\n } = options\n this.properties = { ...properties }\n this._createGroup()\n\n // Screen size / base mobile screen size ratio => 375\n const divider = _.clamp(window.innerWidth / 375 / 1.75, 1, 1.7)\n // Leg\n if (showLeg) {\n const lineMaterial = new LineBasicMaterial({\n color: legColor,\n transparent: true,\n })\n const lineHeight = layer.altitudeToVector3(altitude, altitude).x\n const lineGeometry = new BufferGeometry()\n const positions = [0, 0, 0, 0, 0, -lineHeight]\n lineGeometry.setAttribute(\n \"position\",\n new Float32BufferAttribute(positions, 3)\n )\n const line = new Line(lineGeometry, lineMaterial)\n this.getObject3d().add(line)\n }\n\n getImgDimension(src).then(({ naturalWidth, naturalHeight }) => {\n // Image\n const map = new TextureLoader().load(src)\n const material = new SpriteMaterial({\n map: map,\n color: 0xffffff,\n alphaTest: alphaTest,\n })\n material.needsUpdate = true\n const sprite = new Sprite(material)\n sprite.material.sizeAttenuation = false\n sprite.scale.set(\n (scale * naturalWidth) / divider,\n (scale * naturalHeight) / divider,\n 1\n )\n this.getObject3d().add(sprite)\n })\n\n // set object3d position\n const z = layer.altitudeToVector3(altitude, altitude).x\n const position = layer.coordinateToVector3(coordinate, z)\n _.set(this.properties, \"default.position\", position)\n _.set(this.properties, \"default.altitude\", altitude)\n _.set(this.properties, \"default.scale\", scale)\n this.getObject3d().position.copy(position)\n }\n\n setLineHeight(altitude) {\n const lineHeight = this.#layer.altitudeToVector3(altitude, altitude).x\n const geometry = this.getObject3d().children[0].geometry\n const positionAttribute = geometry.getAttribute(\"position\")\n positionAttribute.setZ(1, -lineHeight)\n positionAttribute.needsUpdate = true\n\n this.getObject3d().position.z = lineHeight\n }\n}\n","import { BaseObject, ThreeLayer } from \"maptalks.three\"\nimport { Sprite, SpriteMaterial } from \"three\"\nimport _ from \"lodash\"\n\nconst DEFAULT_SCALE = 0.05\nconst DEFAULT_ALTITUDE = 0\nconst DEFAULT_ALPHATEST = 0.3\nconst DEFAULT_OPTIONS = {\n scale: DEFAULT_SCALE,\n altitude: DEFAULT_ALTITUDE,\n alphaTest: DEFAULT_ALPHATEST,\n highlight: {\n options: {\n scale: DEFAULT_SCALE * 1.25,\n },\n material: null,\n },\n}\n\ninterface IOptions {\n scale: number\n altitude: number\n alphaTest?: number\n highlight?: {\n options: {\n altitude?: number\n scale?: number\n }\n material?: SpriteMaterial\n }\n}\n\nexport class SpriteMarker extends BaseObject {\n #default = null\n #highlight = null\n constructor(\n coordinate,\n options: IOptions,\n material: SpriteMaterial,\n layer: ThreeLayer,\n properties: object\n ) {\n super()\n //Initialize internal configuration\n this._initOptions(options)\n this._createGroup()\n const {\n altitude = DEFAULT_OPTIONS.altitude,\n scale = DEFAULT_OPTIONS.scale,\n highlight = DEFAULT_OPTIONS.highlight,\n alphaTest = DEFAULT_OPTIONS.alphaTest,\n } = options\n this.properties = { ...properties }\n\n const modifiedAltitude = altitude + 2\n\n this.#default = { options: { scale, altitude: modifiedAltitude }, material }\n this.#highlight = _.merge({}, DEFAULT_OPTIONS.highlight, highlight)\n\n /**\n * Add alphaTest to render only non-transparent pixels in PNG images.\n * [@Doc](https://threejs.org/docs/#api/en/materials/Material.alphaTest)\n */\n if (material && material instanceof SpriteMaterial)\n material.alphaTest = alphaTest\n\n const sprite = new Sprite(material)\n sprite.scale.set(scale, scale, scale) // Set sprite scale\n\n const obj3d = this.getObject3d()\n obj3d.add(sprite)\n // set object3d position\n const z = layer.altitudeToVector3(modifiedAltitude, modifiedAltitude).x\n const position = layer.coordinateToVector3(coordinate, z)\n _.set(this.properties, \"default.position\", position)\n this.getObject3d().position.copy(position)\n }\n\n // Different objects need to implement their own methods\n setSymbol(material: SpriteMaterial) {\n if (material && material instanceof SpriteMaterial) {\n const sprite = (this.getObject3d() as any).children[0]\n\n if (!sprite) return this\n\n sprite.material = material\n sprite.material.needsUpdate = true\n }\n return this\n }\n\n setScale(scaleX: number, scaleY: number = scaleX, scaleZ: number = scaleX) {\n const sprite = (this.getObject3d() as any).children[0]\n if (!sprite) return this\n\n sprite.scale.set(scaleX, scaleY, scaleZ)\n\n return this\n }\n\n // Different objects need to implement their own methods\n getSymbol(): SpriteMaterial {\n return (this.getObject3d() as any)?.children[0]?.material\n }\n\n highlight() {\n const { material, options } = this.#highlight\n if (material) this.setSymbol(material)\n if (options.scale) this.setScale(options.scale)\n if (options.altitude) this.setAltitude(options.altitude)\n return this\n }\n\n removeHighlight() {\n const { material, options } = this.#default\n if (material) this.setSymbol(material)\n if (options.scale) this.setScale(options.scale)\n if (options.altitude) this.setAltitude(options.altitude)\n return this\n }\n}\n","import * as maptalks from \"maptalks\"\nimport { BaseObject } from \"maptalks.three\"\nimport { MeshBasicMaterial, ShaderMaterial, Color } from \"three\"\n\nconst OPTIONS = {\n altitude: 0,\n}\n\nconst DEFAULT_LINE_OPTION = {\n color: \"#000\",\n opacity: 1,\n}\nconst DEFAULT_LINE_EFFECT_OPTION = {\n color: \"#000\",\n opacity: 1,\n}\n\n// In case we want to open/close this animation per project.\nconst ENABLE_ANIMATED_PATH = true\n\nexport class NavigationPath extends BaseObject {\n constructor(\n feature,\n layer,\n properties,\n options,\n lineOptions = DEFAULT_LINE_OPTION,\n outlineOption = DEFAULT_LINE_EFFECT_OPTION\n ) {\n options = maptalks.Util.extend({}, OPTIONS, options, {\n layer,\n })\n super()\n //Initialize internal configuration\n this._initOptions(options)\n const { altitude = OPTIONS.altitude } = options\n this.properties = { ...properties }\n this._createGroup()\n\n const { color: lineColor, opacity: lineOpacity } =\n lineOptions || DEFAULT_LINE_OPTION\n\n const staticMaterial = new MeshBasicMaterial({\n transparent: true,\n color: lineColor || \"#fff\",\n opacity: lineOpacity || 1,\n depthWrite: false,\n })\n\n const uniforms = {\n time: { value: 0 },\n color: { value: new Color(lineColor || \"#fff\") },\n opacity: { value: lineOpacity || 1 },\n }\n this._uniforms = uniforms\n this._t = 0 // Start time = 0\n\n /**\n * Animation formula\n * float dash = smoothstep(0.3, 0.7, abs(sin(vUv.x * 1.0 - time * 0.1)));\n * | vUv.x * 1.0 | controls dash length & frequency\n * | - time * 1.0 | animates motion to the right\n */\n const animatedMaterial = new ShaderMaterial({\n uniforms,\n transparent: true,\n depthWrite: false,\n vertexShader: `\n varying vec2 vUv;\n void main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n }\n `,\n fragmentShader: `\n uniform float time;\n uniform vec3 color;\n uniform float opacity;\n varying vec2 vUv;\n\n void main() {\n float dash = smoothstep(0.3, 0.7, abs(sin(vUv.x * 1.0 - time * 0.1)));\n gl_FragColor = vec4(color, opacity * dash);\n }\n `,\n })\n\n const pathGeometry = maptalks.GeoJSON.toGeometry(feature)\n const line = layer.toPath(\n pathGeometry,\n {\n interactive: false,\n cornerRadius: 2,\n width: 0.5,\n },\n ENABLE_ANIMATED_PATH ? animatedMaterial : staticMaterial\n )\n\n const { color: outlineColor, opacity: outlineOpacity } = outlineOption || {}\n const outlineMaterial = new MeshBasicMaterial({\n transparent: true,\n color: outlineColor || \"#fff\",\n opacity: outlineOpacity || 1,\n })\n\n const lineOutLine = layer.toPath(\n pathGeometry,\n {\n interactive: false,\n cornerRadius: 2,\n width: 1,\n },\n outlineMaterial\n )\n this.getObject3d().add(lineOutLine.getObject3d())\n this.getObject3d().add(line.getObject3d())\n\n // set object3d position\n const z = layer.altitudeToVector3(altitude + 0.25, altitude + 0.25).x\n const pos = this.getObject3d().position\n\n const position = layer.coordinateToVector3([pos.x, pos.y], z)\n // _.set(this.properties, \"default.position\", position)\n\n this.getObject3d().position.copy(position)\n }\n\n _animation() {\n this._t = this._t + 1\n this._uniforms.time.value = this._t\n }\n}\n","import center from \"@turf/center\"\nimport { Polygon, MultiPolygon, Point, LineString } from \"geojson\"\nimport _ from \"lodash\"\nimport turfLineOffset from \"@turf/line-offset\"\nimport { lineString as turfLineString } from \"@turf/helpers\"\n\n// Calculates the center point of a GeoJSON geometry and Return as a Coordinates.\nexport const getCenterFromGeometry = (geometry?: Polygon | MultiPolygon | Point | LineString): number[] | null => {\n try {\n const { type = null, coordinates = null } = geometry\n if (!type || !coordinates) return null\n const centerPoint = center(geometry)\n return _.get(centerPoint, \"geometry.coordinates\") // Coordinates\n } catch (error) {\n return null\n }\n}\n\nexport const createPolygonFromLineString = (geometry) => {\n const line = turfLineString(geometry.coordinates)\n const left = turfLineOffset(line, 0.3, { units: \"meters\" })\n const right = turfLineOffset(line, -0.3, { units: \"meters\" })\n const leftCoords = left.geometry.coordinates\n const rightCoords = right.geometry.coordinates.reverse()\n const polygon = [...leftCoords, ...rightCoords, leftCoords[0]]\n return [polygon]\n}\n","export const svgToPng = (svgString: string, scaleFactor: number = 1) => {\n const svgBlob = new Blob([svgString], { type: \"image/svg+xml\" })\n const url = URL.createObjectURL(svgBlob)\n const img = new Image()\n return new Promise((resolve, reject) => {\n img.onload = function () {\n // Calculate the new dimensions\n const newWidth = img.width * scaleFactor\n const newHeight = img.height * scaleFactor\n\n // Create a canvas with the new dimensions\n const canvas = document.createElement(\"canvas\")\n canvas.width = newWidth\n canvas.height = newHeight\n const ctx = canvas.getContext(\"2d\")\n\n // Draw the SVG image onto the canvas with the scaled dimensions\n ctx.drawImage(img, 0, 0, newWidth, newHeight)\n\n // Convert canvas to PNG\n const pngDataUrl = canvas.toDataURL(\"image/png\")\n\n // Resolve the Promise with the PNG data URL\n resolve(pngDataUrl)\n }\n\n // Handle image load errors\n img.onerror = function (error) {\n reject(error)\n }\n\n img.src = url\n })\n}\n\nexport const createSVGPathFromMarkerSymbol = (style) => {\n const {\n markerWidth = 24,\n markerDx = 0,\n markerDy = 0,\n markerFill,\n markerPath,\n } = style\n const scale = markerWidth / 24\n return `<path d=\"${markerPath}\" style=\"transform:translate(${markerDx}px, ${markerDy}px) scale(${scale})\" fill=\"${markerFill}\"/>`\n}\n","interface ICoordinate {\n x: number\n y: number\n z?: number\n}\n\ntype RadToDegree = (rad: number) => number\n\ntype GetBearingBetweenPoints = (\n origin: ICoordinate,\n destination: ICoordinate\n) => number\n\ntype GetSuitablyValueBetweenBearings = (\n newBearing: number,\n currentBearing: number\n) => number\n\nconst radToDegree: RadToDegree = (rad) => rad * (180 / Math.PI)\n\nexport const getBearingBetweenPoints: GetBearingBetweenPoints = (\n origin,\n destination\n) => {\n const twoPI = Math.PI * 2\n\n if (origin.x === destination.x && origin.y === destination.y) return\n let theta = Math.atan2(destination.x - origin.x, destination.y - origin.y)\n\n if (theta < 0.0) theta += twoPI\n\n return Math.floor(radToDegree(theta))\n}\n\nexport const getSuitablyValueBetweenBearings: GetSuitablyValueBetweenBearings =\n (newBearing, currentBearing) => {\n const difference = Math.abs(newBearing - currentBearing)\n\n // Adjust newBearing to ensure the shortest direction\n if (difference > 180)\n return newBearing > 0 ? newBearing - 360 : newBearing + 360\n\n return newBearing // Return as is if the difference is within limits\n }\n","import { Extent } from \"maptalks\"\nimport { Map } from \"maptalks-gl\"\nimport { MapAnimationOptionsType, MapPaddingType, MapViewType } from \"maptalks/dist/map/Map\"\nimport bbox from \"@turf/bbox\"\nimport scale from \"@turf/transform-scale\"\nimport bboxPolygon from \"@turf/bbox-polygon\"\n\nexport interface CameraManagerOptions {\n defaultView?: MapViewType\n}\n\nexport class CameraManager {\n map: Map\n\n constructor(map: Map, options?: CameraManagerOptions) {\n this.map = map\n\n if (options?.defaultView) {\n this.setView(options?.defaultView)\n }\n }\n\n /** Public methods */\n getView = (): MapViewType => {\n return this.map.getView()\n }\n \n setView = (value: MapViewType) => {\n if (this.map && Object.keys(value).length !== 0) {\n this.map.setView(value)\n }\n }\n\n animateTo = (view: MapViewType, options: MapAnimationOptionsType = {}, step?: (frame: any) => void) => {\n this.map.animateTo(view, options, step)\n }\n\n setMaxExtent(extent: Extent) {\n return this.map.setMaxExtent(extent)\n }\n\n getFeatureExtent = (feature, scaleFactor = 1) => {\n const [minX, minY, maxX, maxY] = bbox(\n scale(bboxPolygon(bbox(feature)), scaleFactor)\n )\n return new Extent(minX, minY, maxX, maxY)\n }\n\n getExtentZoom = (\n extent: Extent,\n options: { isFraction?: boolean; padding?: MapPaddingType } = {\n isFraction: false,\n padding: {\n paddingLeft: 0,\n paddingRight: 0,\n paddingTop: 0,\n paddingBottom: 0,\n },\n }\n ) => {\n const { isFraction = false, padding } = options\n return this.map.getFitZoom(extent, isFraction, padding)\n }\n\n set maxZoom(value: number) {\n this.map.setMaxZoom(value)\n const spatialReference = {\n projection: \"EPSG:3857\",\n resolutions: (function () {\n const resolutions = []\n const d = 2 * 6378137 * Math.PI\n for (let i = 0; i < value; i++) {\n resolutions[i] = d / (256 * Math.pow(2, i))\n }\n return resolutions\n })(),\n }\n this.map.setSpatialReference(spatialReference)\n }\n\n set minZoom(value: number) {\n this.map.setMinZoom(value)\n }\n\n}\n","import * as maptalks from \"maptalks-gl\"\nimport { min, compact, isFunction } from \"lodash\"\nimport { center as turfCenter } from \"@turf/center\"\nimport { polygon } from \"@turf/helpers\"\nimport { Position } from \"geojson\"\nimport { BaseObject, ThreeLayer } from \"maptalks.three\"\nimport * as THREE from \"three\"\n\nimport type { HighlightElementOptions, IHighlightController, MapElement, RendererManagerOptions } from \"./types\"\nimport { Element3DRenderer } from \"./3d/Element3DRenderer\"\nimport { Element2DRenderer } from \"./2d/Element2DRenderer\"\nimport { Marker2DRenderer } from \"./2d/Marker2DRenderer\"\nimport { AnyMarkerOptions, ImageMarkerOptions, Marker3DRenderer } from \"./3d/Marker3DRenderer\"\n\nimport {\n KioskFeaturePopulated,\n OpeningFeature,\n OpeningFeaturePopulated,\n UnitFeaturePopulated,\n VenueDataClient,\n} from \"../../data\"\nimport { angleBetweenLineStrings } from \"./utils/angleBetweenLineString\"\nimport { findUnitOnPoint } from \"./utils/findUnitOnPoint\"\nimport { TextMarkerOptions } from \"./3d/objects/TextSpriteMarker\"\nimport { Route } from \"src/data/navigate/type\"\n\nfunction delay(ms: number) {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\nexport class RendererManager extends EventTarget {\n map: maptalks.Map\n\n options: RendererManagerOptions\n\n // Client for fetching data\n #dataClient: VenueDataClient\n\n #isClicked = false\n #onClickElement = (e) => {}\n\n /** Elements: Responsible for converting feature info elements and add to map */\n private elementRenderer: Element2DRenderer | Element3DRenderer\n private markerRenderer: Marker2DRenderer | Marker3DRenderer\n\n private elementsMap: Map<string, MapElement>\n private elementsByOrdinal: Map<\n number,\n Array<MapElement>\n >\n\n private currentOrdinals: number | number[] | null\n\n private markersMap: Map<string, maptalks.ui.UIMarker | BaseObject>\n private markersByOrdinal: Map<\n number,\n Array<maptalks.ui.UIMarker> | Array<BaseObject>\n >\n\n private highlightControllers: IHighlightController[] = []\n\n constructor(map: maptalks.Map, dataClient: VenueDataClient, options: RendererManagerOptions) {\n super()\n this.map = map\n this.options = options\n this.elementsMap = new Map()\n this.elementsByOrdinal = new Map()\n\n this.markersMap = new Map()\n this.markersByOrdinal = new Map()\n\n this.#dataClient = dataClient\n \n const _this = this\n\n if (options.type === \"3D\") {\n const groupLayer = this.map.getLayer('group') as maptalks.GroupGLLayer\n const threeLayer = groupLayer.getLayer('three') as ThreeLayer\n\n threeLayer.prepareToDraw = function (gl, scene, camera) {\n \n function findBadMeshes(scene: THREE.Scene) {\n const bad: Array<{ mesh: THREE.Mesh; index: number; value: number }> = [];\n\n scene.traverse((obj: any) => {\n if (!obj?.isMesh) return;\n const geom = obj.geometry as THREE.BufferGeometry | undefined;\n const pos = geom?.attributes?.position?.array as Float32Array | undefined;\n if (!pos || pos.length === 0) return;\n\n for (let i = 0; i < pos.length; i++) {\n const v = pos[i];\n if (!Number.isFinite(v)) {\n bad.push({ mesh: obj, index: i, value: v });\n break;\n }\n }\n });\n\n if (bad.length) {\n console.group(`❌ Found ${bad.length} meshes with invalid positions`);\n for (const b of bad) {\n console.log({\n name: b.mesh.name,\n userData: b.mesh.userData,\n uuid: b.mesh.uuid,\n badIndex: b.index,\n badValue: b.value,\n });\n }\n console.groupEnd();\n } else {\n console.log(\"✅ No invalid meshes found\");\n }\n\n return bad;\n }\n\n const ambientLight = new THREE.AmbientLight(0xffffff, 0.3)\n scene.add(ambientLight)\n \n const dirColor = 0xffffff\n const dllight = new THREE.DirectionalLight(dirColor, 0.8)\n dllight.position.set(0, -10, 20).normalize()\n scene.add(dllight)\n \n // nice optional fill\n const hemi = new THREE.HemisphereLight(0xffffff, 0x444444, 0.4)\n scene.add(hemi)\n\n // Element renderer creates and owns the ThreeLayer\n _this.elementRenderer = new Element3DRenderer(map, options.elements)\n\n // Get the ThreeLayer from element renderer to share with marker renderer\n _this.markerRenderer = new Marker3DRenderer(map, {}, threeLayer)\n\n if (typeof options.onRendererReady === 'function') {\n options.onRendererReady()\n }\n\n _this.#createElements()\n\n _this.elementRenderer.createModel3d([100.54724407, 13.72699081], 'https://s3.venue.in.th/all_park_f95ac5be3c.gltf')\n\n setTimeout(() => {\n findBadMeshes(scene)\n }, 3000)\n }\n \n } else {\n // 2D doesn't need shared layer\n this.elementRenderer = new Element2DRenderer(map, options.elements)\n this.markerRenderer = new Marker2DRenderer(map)\n\n this.#createElements()\n }\n }\n\n set onClickElement(func) {\n this.#onClickElement = func\n }\n\n handleClickElement = (e) => {\n if (this.#isClicked) return\n this.#isClicked = true\n const onClickElement = this.#onClickElement\n if (!isFunction(onClickElement)) return\n this.#onClickElement(e)\n this.#isClicked = false\n }\n\n getElementsByOrdinal = (ordinal: number) => {\n const exist = this.elementsByOrdinal.get(ordinal)\n if (!exist) this.elementsByOrdinal.set(ordinal, [])\n return this.elementsByOrdinal.get(ordinal)\n }\n\n addElementsToManager = (id, elements, ordinal) => {\n // console.log(`addElementsToManager`, { id, elements })\n this.elementsMap.set(id, elements)\n elements.forEach((el) => {\n el.on('click', e => this.handleClickElement(id))\n this.getElementsByOrdinal(ordinal).push(el)\n })\n\n const inOrdinal = Array.isArray(this.currentOrdinals) ? this.currentOrdinals.includes(ordinal) : ordinal === this.currentOrdinals\n if (inOrdinal) {\n this.elementRenderer.showElements(elements as any, ordinal)\n } else {\n this.elementRenderer.hideElements(elements as any, ordinal)\n }\n }\n\n async #createElements() {\n\n // Add some delay to mitigate react re-renders multiple times\n await delay(this.options.delayBeforeCreateElements ?? 0)\n\n /** Levels */\n const levels = await this.#dataClient.filterByType(\"level\", {\n populate: true,\n })\n\n const openings = await this.#dataClient.filterByType(\"opening\", {\n populate: true,\n })\n\n const relationships = await this.#dataClient.filterByType('relationship')\n /** Fixtures */\n const fixtures = (await this.#dataClient.filterByType(\"fixture\", { populate: true }))\n fixtures\n .forEach((fixture) => {\n const element = this.elementRenderer.createGeometry(fixture)\n if (element) {\n const _elements = Array.isArray(element) ? element : [element]\n this.addElementsToManager(fixture.id, _elements, fixture.properties.level.properties.ordinal)\n }\n })\n\n /** Units */\n const units = (await this.#dataClient.filterByType<\"unit\">(\"unit\", {\n populate: true,\n })) as UnitFeaturePopulated[]\n\n units\n .filter(\n (u) => ![\"opentobelow\", \"escalator\", \"room\"].includes(u.properties.category)\n )\n .forEach((unit) => {\n const element = this.elementRenderer.createGeometry(unit)\n if (element) {\n const _elements = Array.isArray(element) ? element : [element]\n this.addElementsToManager(unit.id, _elements, unit.properties.level.properties.ordinal)\n }\n })\n\n units\n .filter(u => u.properties.category === \"room\")\n .forEach(unit => {\n const openingRelationships = relationships.filter(r => r.properties.origin?.id === unit.id || r.properties.destination?.id === unit.id)\n const roomOpenings = compact(openingRelationships.map(rel => {\n const openingId = rel?.properties.intermediary[0].id\n return openings.find(o => o.id === openingId)\n })) as OpeningFeature[]\n \n const innerElements = this.elementRenderer.createGeometry(unit)\n const wallElements = []\n // const wallElements = this.elementRenderer.createRoomWall(unit, roomOpenings)\n if (innerElements || wallElements) {\n const _innerElements = Array.isArray(innerElements) ? innerElements : [innerElements]\n const _wallElements = Array.isArray(wallElements) ? wallElements : [wallElements]\n const _elements = [..._innerElements, ..._wallElements]\n const ordinal = unit.properties.level.properties.ordinal\n this.addElementsToManager(unit.id, _elements, ordinal)\n }\n\n })\n\n /** Kiosks */\n const kiosks = (await this.#dataClient.filterByType<\"kiosk\">(\"kiosk\", {\n populate: true,\n })) as KioskFeaturePopulated[]\n kiosks.forEach((kiosk) => {\n const element = this.elementRenderer.createGeometry(kiosk)\n if (element) {\n const _elements = Array.isArray(element) ? element : [element]\n this.addElementsToManager(kiosk.id, _elements, kiosk.properties.level.properties.ordinal)\n }\n })\n\n /**\n * Escalators\n */\n const escalators = units.filter(u => u.properties.category === 'escalator')\n for (const escalator of escalators) {\n try {\n const escalatorRelationships = relationships.filter(r => (r.properties?.intermediary || []).some(inter => inter.id === escalator.id))\n if (escalatorRelationships.length === 0) {\n throw new Error('Cannot find escalator relationship')\n }\n if (escalatorRelationships.length > 1) {\n throw new Error('Found more than one relationship')\n }\n const thisOrdinal = escalator.properties.ordinal\n const relationship = escalatorRelationships[0]\n if (!relationship.properties.origin?.id) throw new Error(`relationship (id=${relationship.id}) - origin not exists`)\n if (!relationship.properties.destination?.id) throw new Error(`relationship (id=${relationship.id}) - destination not exists`)\n\n const bothOpeningIds = [relationship.properties.origin.id, relationship.properties.destination.id]\n const bothOpenings = await Promise.all(\n bothOpeningIds.map(id => this.#dataClient.findById('opening', id, { populate: true }))\n ) as OpeningFeaturePopulated[]\n const thisLevelOpening = bothOpenings.find(opening => opening.properties.ordinal === thisOrdinal)\n const thatLevelOpening = bothOpenings.find(opening => opening.properties.ordinal !== thisOrdinal)\n const angle = 180 * (1 / Math.PI) * angleBetweenLineStrings(thisLevelOpening.geometry.coordinates, thatLevelOpening.geometry.coordinates)\n const direction = thisOrdinal < thatLevelOpening.properties.ordinal ? 'up' : 'down'\n const escalatorEntryPoint = turfCenter(thisLevelOpening).geometry.coordinates\n const element = await this.elementRenderer.createEscalator(escalator, escalatorEntryPoint, { direction, angle })\n if (element) {\n const _elements = (Array.isArray(element)) ? element : [element]\n this.addElementsToManager(escalator.id, _elements, escalator.properties.ordinal)\n }\n } catch (err) {\n console.warn(`cannot create escalator`, err.message)\n }\n }\n\n /** \n * Ground Label \n */\n const groundLabels = await this.#dataClient.filterByType(\"label\")\n for (const label of groundLabels) {\n const center = turfCenter(polygon(label.geometry.coordinates)).geometry.coordinates\n const unit = findUnitOnPoint(units, center)\n if (unit) {\n const element = this.elementRenderer.createGroundLabel(label, unit)\n if (element) {\n const _elements = (Array.isArray(element)) ? element : [element]\n this.addElementsToManager(label.id, _elements, label.properties.ordinal)\n }\n }\n }\n\n // Call changeLevelByOrdinal again to show/hide elements\n this.changeLevelByOrdinal(this.currentOrdinals)\n\n this.dispatchEvent(new CustomEvent('renderermanager:elements_created'))\n\n }\n\n changeLevelByOrdinal(targetOrdinal: null | number | number[]): void {\n // if targetOrdinal = null, show all\n this.currentOrdinals = targetOrdinal\n\n if (targetOrdinal === null) {\n const baseOrdinal = 0\n for (const [ordinal, elements] of this.elementsByOrdinal) {\n this.elementRenderer.showElements(elements as any, ordinal - baseOrdinal)\n }\n\n for (const [ordinal, markers] of this.markersByOrdinal) {\n this.markerRenderer.showMarkers(markers as any, ordinal - baseOrdinal)\n }\n } else {\n // if targetOrdinal = number | number[], show target levels\n const baseOrdinal = Array.isArray(targetOrdinal) ? min(targetOrdinal) : targetOrdinal\n\n for (const [ordinal, elements] of this.elementsByOrdinal) {\n const inOrdinal = Array.isArray(targetOrdinal) ? targetOrdinal.includes(ordinal) : ordinal === targetOrdinal\n if (inOrdinal) {\n this.elementRenderer.showElements(elements as any, ordinal - baseOrdinal)\n } else {\n this.elementRenderer.hideElements(elements as any, ordinal - baseOrdinal)\n }\n }\n\n for (const [ordinal, markers] of this.markersByOrdinal) {\n const inOrdinal = Array.isArray(targetOrdinal) ? targetOrdinal.includes(ordinal) : ordinal === targetOrdinal\n if (inOrdinal) {\n this.markerRenderer.showMarkers(markers as any, ordinal - baseOrdinal)\n } else {\n this.markerRenderer.hideMarkers(markers as any, ordinal - baseOrdinal)\n }\n }\n }\n }\n\n highlightElements = (elemIds: string[], options?: HighlightElementOptions) => {\n const { reset = true } = options ?? {};\n\n if (reset) {\n this.clearHighlightElements()\n }\n\n const elements = elemIds.map(id => this.elementsMap.get(id)).flat()\n\n elements.forEach(element => {\n const controller: IHighlightController = this.elementRenderer.createHighlightController(element) \n if (controller && isFunction(controller.start)) {\n controller.start()\n this.highlightControllers.push(controller)\n }\n })\n }\n\n clearHighlightElements = () => {\n this.highlightControllers.forEach((controller) => {\n if (isFunction(controller?.clear)) controller.clear()\n })\n }\n\n /** \n * ========================================================================\n * Markers\n * ======================================================================== */\n _getMarkersByOrdinal = (ordinal: number) => {\n const exist = this.markersByOrdinal.get(ordinal)\n if (!exist) this.markersByOrdinal.set(ordinal, [])\n return this.markersByOrdinal.get(ordinal)\n }\n\n _addMarkersToManager = (id, markers, ordinal) => {\n this.markersMap.set(id, markers)\n markers.forEach((el) => {\n this._getMarkersByOrdinal(ordinal).push(el)\n })\n\n const inOrdinal = Array.isArray(this.currentOrdinals) ? this.currentOrdinals.includes(ordinal) : ordinal === this.currentOrdinals\n if (inOrdinal) {\n this.markerRenderer.showMarkers(markers, ordinal)\n } else {\n this.markerRenderer.hideMarkers(markers, ordinal)\n }\n }\n\n createMarker(type: 'text' | 'image', coordinate: Position, ordinal: number, textOrPath: string, options: AnyMarkerOptions) {\n\n const meshes = type === 'text' \n ? this.markerRenderer.createTextMarker(coordinate, textOrPath, options as TextMarkerOptions)\n : this.markerRenderer.createImageMarker(coordinate, textOrPath, options as ImageMarkerOptions)\n const markerId = `${this.markersMap.size + 1}`\n const markerMeshes = Array.isArray(meshes) ? meshes : [meshes]\n this._addMarkersToManager(markerId, markerMeshes, ordinal)\n }\n\n clearMarkers() {\n for (const [markerId, marker] of this.markersMap) {\n this.markerRenderer.removeMarker(marker as any)\n }\n }\n\n drawNavigation(route: Route) {\n this.elementRenderer.drawNavigation(route)\n }\n \n}\n","import * as maptalks from \"maptalks-gl\"\nimport { GeoJSONLineStringFeature, GeoJSONMultiPolygonFeature, GeoJSONPolygonFeature } from \"maptalks.three/dist/type\"\nimport * as THREE from \"three\"\nimport { BaseObject, ThreeLayer } from \"maptalks.three\"\nimport { Feature, LineString, Point, Polygon, Position } from \"geojson\"\nimport turfBuffer from \"@turf/buffer\"\nimport { cleanCoords } from \"@turf/clean-coords\";\nimport { point, multiPoint, polygon } from \"@turf/helpers\"\nimport { polygonToLine } from \"@turf/polygon-to-line\"\nimport { nearestPointOnLine } from \"@turf/nearest-point-on-line\";\nimport { length } from \"@turf/length\"\nimport { along } from \"@turf/along\";\nimport { pointToLineDistance } from \"@turf/point-to-line-distance\";\nimport { ImdfFeature, LabelFeature, OpeningFeature, UnitFeature } from \"../../../data\"\nimport {\n Element3DRendererOptions,\n IElementRenderer,\n IHighlightController,\n MapElement,\n} from \"../types\"\nimport { GroundLabel, GroundLabelOptions } from \"./objects/GroundLabel\"\nimport { get3DRendererOption } from \"./utils/get3DRendererOption\"\nimport lineSplit from \"@turf/line-split\"\nimport { Route } from \"../../../data/navigate/type\"\n\nexport const HEIGHT_METER = 4\nexport const MULTIORDINAL_HEIGHT_METER = 9\nexport const WALKWAY_HEIGHT = 0.5\n\nexport class Element3DRenderer\n extends EventTarget\n implements IElementRenderer\n{\n private options: Element3DRendererOptions\n private map: maptalks.Map\n private gltfLayer: maptalks.GLTFLayer\n public threeLayer: ThreeLayer\n public scene: THREE.Scene\n private lineMaterial: THREE.LineBasicMaterial\n private navigationLineMaterial: THREE.LineBasicMaterial | THREE.MeshBasicMaterial\n private materialByColorMap: Map<string, THREE.Material>\n\n // Renderer is Ready\n public isReady: boolean = false\n\n constructor(map: maptalks.Map, options: Element3DRendererOptions) {\n super()\n\n this.options = options\n this.map = map\n const groupLayer = this.map.getLayer('group') as maptalks.GroupGLLayer\n this.threeLayer = groupLayer.getLayer('three') as ThreeLayer\n this.gltfLayer = groupLayer.getLayer('gltf') as maptalks.GLTFLayer\n\n this.lineMaterial = new THREE.LineBasicMaterial({ color: \"#000\" })\n\n // const texture = new THREE.TextureLoader().load('https://maptalks.org/maptalks.three/demo/data/path_007_21.png');\n // texture.needsUpdate = true;\n // texture.wrapS = texture.wrapT = THREE.RepeatWrapping;\n // // texture.repeat.set(0.002, 0.002);\n // texture.repeat.set(0.01, 1);\n // this.navigationLineMaterial = new THREE.MeshBasicMaterial({\n // map: texture,\n // transparent: true,\n // color: '#fff'\n // });\n this.navigationLineMaterial = new THREE.LineBasicMaterial({ color: \"#f00\" })\n\n \n this.render()\n }\n\n animation() {\n // layer animation support Skipping frames\n this.threeLayer._needsUpdate = !this.threeLayer._needsUpdate\n if (this.threeLayer._needsUpdate) {\n this.threeLayer.redraw()\n }\n requestAnimationFrame(this.animation)\n }\n\n /** Materials */\n getOrCreateMaterialByColor(color) {\n if (!this.materialByColorMap) this.materialByColorMap = new Map()\n\n const existingMaterial = this.materialByColorMap.get(color)\n if (existingMaterial) return existingMaterial\n\n const created = new THREE.MeshLambertMaterial({ color, transparent: true })\n created.toneMapped = false\n this.materialByColorMap.set(color, created)\n return created\n }\n\n createGeometry = (feature: ImdfFeature): MapElement | MapElement[] => {\n const {\n offset = 0,\n height: heightOptions,\n bottomHeight: bottomHeightOptions,\n color: colorOptions,\n ...options\n } = get3DRendererOption(feature.feature_type, feature.properties.category, this.options)\n\n const _this = this\n\n /** Internal createPolygon function */\n const createPolygon = (geometry: Polygon, feature: GeoJSONPolygonFeature|GeoJSONMultiPolygonFeature) => {\n try {\n const [outerRing, ...innerRings] = geometry.coordinates\n const offsetFeature =\n offset !== 0\n ? turfBuffer(geometry, offset, { units: \"meters\" }) as GeoJSONPolygonFeature\n : feature\n const color =\n feature.properties.style.polygonFill ?? colorOptions ?? \"#ffffff\"\n if (color === \"transparent\") return\n const material = this.getOrCreateMaterialByColor(color)\n const altitude = 0\n const height = feature.properties.height ?? heightOptions ?? HEIGHT_METER\n const bottomHeight = feature.properties.bottomHeight ?? bottomHeightOptions ?? 0\n const extrudedPolygon = this.threeLayer.toExtrudePolygon(\n offsetFeature,\n { asynchronous: true, ...options, height, bottomHeight, altitude },\n material\n )\n\n // Create extra lines for visual clarity\n const topLineStrings = [\n new maptalks.LineString(outerRing),\n ...innerRings.map(innerRing => new maptalks.LineString(innerRing))\n ]\n const topLines = this.threeLayer.toLines(\n topLineStrings,\n { altitude, bottomHeight: bottomHeight + height + 0.001, interactive: false },\n this.lineMaterial\n )\n\n const bottomLineStrings = [\n new maptalks.LineString(outerRing),\n ...innerRings.map(innerRing => new maptalks.LineString(innerRing))\n ]\n const bottomLines = this.threeLayer.toLines(\n bottomLineStrings,\n { altitude: altitude, bottomHeight, interactive: false },\n this.lineMaterial\n )\n return [extrudedPolygon, topLines, bottomLines]\n } catch (err) {\n return []\n }\n }\n\n const createLineString = (geometry: LineString, feature: GeoJSONLineStringFeature) => {\n try {\n const color =\n feature.properties.style.polygonFill ?? colorOptions ?? \"#000000\"\n const material = this.getOrCreateMaterialByColor(color)\n const extrudedLine = this.threeLayer.toExtrudeLine(\n new maptalks.LineString(geometry.coordinates),\n { height: heightOptions, ...options },\n material\n )\n return [extrudedLine]\n } catch (err) {\n return []\n }\n }\n\n try {\n switch (feature.geometry.type) {\n case \"MultiPolygon\": {\n const { coordinates } = feature.geometry\n if (!coordinates) return []\n\n const multiMeshes = coordinates.flatMap(polygonCoordinates => {\n const meshes = createPolygon({ type: 'Polygon', coordinates: polygonCoordinates }, feature as GeoJSONMultiPolygonFeature)\n this.threeLayer.addMesh(meshes)\n return meshes\n })\n return multiMeshes\n }\n case \"Polygon\": {\n const { coordinates } = feature.geometry\n if (!coordinates) return []\n\n const meshes = createPolygon(feature.geometry, feature as GeoJSONPolygonFeature)\n this.threeLayer.addMesh(meshes)\n return meshes\n }\n\n case \"LineString\": {\n const { coordinates } = feature.geometry\n if (!coordinates) return []\n\n const meshes = createLineString(feature.geometry, feature as GeoJSONLineStringFeature)\n this.threeLayer.addMesh(meshes)\n return meshes\n }\n }\n } catch (err) {\n console.log(`error createGeometry`, err, { feature, options })\n }\n }\n\n createRoomWall(unit: UnitFeature, openings: OpeningFeature[] = []): MapElement | MapElement[] | null {\n\n const polygons = unit.geometry.type === 'Polygon' ? [unit.geometry.coordinates] : unit.geometry.coordinates\n return polygons.map(plg => {\n return plg.map(ring => {\n const roomWall = cleanCoords(polygonToLine(polygon([ring]))) as Feature<LineString>\n if (openings.length === 0) {\n const color = \"#ababab\"\n const material = this.getOrCreateMaterialByColor(color)\n const extrudedWall = this.threeLayer.toExtrudeLine(\n new maptalks.LineString(roomWall.geometry.coordinates),\n { height: 4, width: 1 },\n material\n )\n return extrudedWall\n }\n \n // Split ring with each opening\n let openingPoints = []\n openings.forEach(opening => {\n const doorCoords = opening?.geometry?.coordinates;\n \n const p0 = point(doorCoords[0]);\n const p1 = point(doorCoords[doorCoords.length - 1]);\n\n // 3) snap door endpoints to boundary\n const s0 = nearestPointOnLine(roomWall, p0, { units: \"meters\" });\n const s1 = nearestPointOnLine(roomWall, p1, { units: \"meters\" });\n\n // Optional sanity check: ensure the door is actually on the boundary (within tolerance)\n const d0 = s0.properties.dist as number;\n const d1 = s1.properties.dist as number;\n if (d0 > 1 || d1 > 1) {\n // Door endpoints are not on (or near) the roomWall. Increase tolerance or fix input.\");\n } else {\n openingPoints = openingPoints.concat([s0.geometry.coordinates, s1.geometry.coordinates])\n }\n })\n \n try {\n const split = lineSplit(roomWall, multiPoint(openingPoints))\n /** \n * Remove the segment that corresponds to the door:\n * use midpoint distance-to-door test (robust for angled doors)\n */\n \n const wallsOnly = split.features.filter((seg) => {\n const mid = along(seg, length(seg, { units: \"meters\" }) / 2, { units: \"meters\" });\n for (const opening of openings) {\n const dist = pointToLineDistance(mid, opening, { units: \"meters\" });\n if (dist < 0.05) return false\n }\n return true\n });\n\n const wallMeshes = wallsOnly.map((feature, i) => {\n const color = \"#ababab\"\n const material = this.getOrCreateMaterialByColor(color)\n \n const extrudedLine = this.threeLayer.toExtrudeLine(\n new maptalks.LineString(feature.geometry.coordinates),\n { height: 3, width: 0.4, id: unit.id },\n material\n )\n extrudedLine.getObject3d().userData = {\n unitId: unit.id,\n coords: feature.geometry.coordinates, \n }\n return extrudedLine\n }).flat()\n\n this.threeLayer.addMesh(wallMeshes)\n return wallMeshes\n } catch (e) {\n console.log(e.message, { unit, roomWall })\n return []\n }\n }).flat()\n }).flat()\n }\n\n async createEscalator(\n f: ImdfFeature,\n coordinate: Position,\n options: { angle: number; direction: 'up' | 'down' },\n ): Promise<MapElement | MapElement[] | null> {\n\n const model = {\n url: 'https://cdn.venue.in.th/static/glb/escalator.glb',\n size: 4.4, \n }\n \n const { direction: dir, angle } = options;\n const rotationZ = (dir === \"up\") ? (180 + angle) : angle\n var escalatorMarker = new maptalks.GLTFMarker(coordinate, {\n symbol: {\n url: model.url,\n rotationZ,\n translationX: dir === \"up\" ? 0 : model.size * Math.cos(Math.PI * rotationZ / 180),\n translationY: dir === \"up\" ? 0 : model.size * Math.sin(Math.PI * rotationZ / 180),\n translationZ: dir === \"up\" ? -0.05 * model.size : -0.5 * model.size,\n },\n });\n\n escalatorMarker.addTo(this.gltfLayer);\n return escalatorMarker\n }\n\n // Note: Move to another renderer and keep this file on Geometry only?\n createGroundLabel(f: LabelFeature, unit: UnitFeature): MapElement | MapElement[] | null {\n const text = f.properties.name\n const bound = f.geometry.coordinates[0]\n\n const { height: unitHeight } = get3DRendererOption('unit', unit.properties.category, this.options)\n const options: GroundLabelOptions = { bottomHeight: unitHeight + 0.005 }\n\n const groundLabel = new GroundLabel(bound, text, options, this.threeLayer)\n this.threeLayer.addMesh(groundLabel)\n return groundLabel\n }\n\n async createModel3d(center: number[], url: string): Promise<MapElement | MapElement[] | null> {\n const marker = new maptalks.GLTFMarker(center, {\n symbol: {\n url,\n },\n });\n\n marker.addTo(this.gltfLayer);\n return marker\n }\n\n async createBuilding(coordinate: Position, ordinal: number): Promise<MapElement | MapElement[] | null> {\n // const marker = new maptalks.GLTFMarker(coordinate, {\n // symbol: {\n // url: 'https://cdn.venue.in.th/static/glb/iconsiam.glb',\n // rotationZ: 4,\n // translationY: -10,\n // scaleX: 49,\n // scaleY: 49,\n // scaleZ: 49,\n // },\n // });\n // marker.on(\"zoom\", (e) => {\n // console.log(`zoom`, e)\n // })\n // marker.addTo(this.gltfLayer);\n // return marker\n return Promise.resolve(null)\n }\n \n createElement(f: ImdfFeature): MapElement[] | null {\n switch (f.feature_type) {\n default:\n return null\n }\n }\n\n showElements(elements: MapElement[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n element.setAltitude(ordinalDiff * MULTIORDINAL_HEIGHT_METER)\n element.show()\n })\n }\n\n hideElements(elements: MapElement[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n try { \n element.hide()\n } catch (err) {\n console.log(`cannot hide`, err, element)\n }\n })\n }\n\n createHighlightController(element: MapElement): IHighlightController {\n if (!(element instanceof BaseObject)) {\n return null; // not my responsibility\n }\n switch (element.type) {\n case 'ExtrudePolygon':\n case 'ExtrudeLine': {\n const mesh = element.getObject3d() as THREE.Mesh\n const originalMaterial = mesh.material;\n const highlightMaterial = this.getOrCreateMaterialByColor('#ff0000');\n\n return {\n start: () => {\n mesh.material = highlightMaterial;\n },\n clear: () => {\n mesh.material = originalMaterial;\n },\n };\n }\n\n default: {\n return {\n start() {},\n clear() {}\n }\n }\n } \n }\n\n drawNavigation = (route: Route) => {\n \n const lines = []\n route.steps.map(step => {\n const lineString = new maptalks.LineString(step.path);\n const line = this.threeLayer.toPath(lineString, { altitude: 0.2, cornerRadius: 1, width: 1, asynchronous: true }, this.navigationLineMaterial);\n lines.push(line)\n })\n\n this.threeLayer.addMesh(lines)\n \n }\n\n render() {\n this.threeLayer._needsUpdate = !this.threeLayer._needsUpdate\n if (this.threeLayer._needsUpdate) {\n // @ts-ignore\n this.threeLayer.redraw()\n }\n\n if (this.navigationLineMaterial?.map?.offset) {\n this.navigationLineMaterial.map.offset.x -= 0.002;\n }\n // this.#animationsToRun.forEach(({ callback }) => callback(this))\n\n //update TWEEN.js animaton\n // TWEEN.update()\n\n requestAnimationFrame(this.render.bind(this))\n }\n}\n\n\n/**\n * Legacy threejs way\n * async loadModel3d(model3d: LoadModel3dParameters) {\n const loader = new GLTFLoader()\n loader.setDRACOLoader(this.dracoLoader)\n\n const { url, properties: modelProperties } = model3d\n const gltf = await loader.loadAsync(url)\n \n const model = gltf.scene\n // จัดขนาด + scale ที่เหมาะสม\n model.rotation.x = modelProperties.rotation.x\n model.rotation.y = modelProperties.rotation.y\n\n model.position.x = modelProperties.position.x\n model.position.y = modelProperties.position.y\n model.position.z = modelProperties.position.z\n \n const scale = modelProperties.scale\n model.scale.set(scale, scale, scale)\n return model\n }\n\n * const model = await this.loadModel3d({\n url: 'https://dashboard.situm.com/uploads/3dmodels/demoaccount/new_escalator.glb',\n properties: {\n rotation: {\n x: 0.5 * Math.PI, // Rotate the model up (new_escalator.glb)\n y: 0,\n z: 0,\n },\n position: { x: 0, y: 0, z: 0 },\n scale: 0.01,\n },\n });\n\n // map heading\n model.rotation.y += (dir === \"up\") ? Math.PI + angle : angle;\n\n const box = new THREE.Box3().setFromObject(model);\n const pivotPoint =\n dir === 'up'\n ? new THREE.Vector3(0, 0, 0)\n : new THREE.Vector3(\n 1 * (box.min.x + box.max.x),\n 1 * (box.min.y + box.max.y),\n 0.60 * box.max.z,\n );\n\n const pivot = new THREE.Group();\n pivot.add(model);\n\n model.position.sub(pivotPoint);\n model.updateMatrixWorld(true);\n\n const altitude = f.properties.ordinal * HEIGHT_METER;\n\n const baseObjectModel = this.threeLayer.toModel(pivot, {\n coordinate,\n altitude,\n });\n\n this.threeLayer.addMesh(baseObjectModel);\n return baseObjectModel;\n */","import * as maptalks from \"maptalks-gl\"\nimport { BaseObject, ThreeLayer } from \"maptalks.three\"\nimport {\n Texture,\n Mesh,\n MeshPhongMaterial,\n PlaneGeometry,\n Material,\n} from \"three\"\nimport { largestRect } from \"d3plus-shape\"\nimport { max, merge, isNumber, isArray, range } from \"lodash\"\nimport { Position } from \"geojson\"\n\nexport type GroundLabelOptions = {\n bottomHeight?: number\n altitude?: number\n fontSize?: number\n fontWeight?: number\n fillStyle?: string\n textAlign?: string\n fontFamily?: string\n textBaseline?: string\n strokeStyle?: string\n lineWidth?: number\n lineHeight?: number\n margin?: number\n angle?: number[]\n scaleMin?: number\n scaleStep?: number\n maxFontScale?: number\n offsetX?: number\n offsetY?: number\n}\n\nconst OPTIONS = {\n // Allowing click through and prevent interaction\n interactive: false,\n altitude: 0,\n}\n\nconst defaultFlatLabelOptions: GroundLabelOptions = {\n fontSize: 14,\n fontFamily: \"Manrope\",\n fontWeight: 600,\n margin: 0,\n scaleMin: 0.5,\n lineHeight: 1.05,\n scaleStep: 0.05,\n textAlign: \"center\",\n textBaseline: \"middle\",\n fillStyle: \"#000\",\n}\n\nconst defaultRectAngleToCalc = range(-90, 92, 2)\n\nexport const getMaterial = (text, flatLabelOptions) => {\n const options = merge({}, defaultFlatLabelOptions, flatLabelOptions)\n\n const {\n fontSize: initialFontSize,\n fontFamily,\n fontWeight,\n margin,\n scaleMin,\n scaleStep,\n fillStyle,\n lineHeight,\n textAlign,\n strokeStyle,\n lineWidth,\n textBaseline,\n } = options\n\n const pixelMultiplier = 4\n const SIZE = 100 * pixelMultiplier\n const fontSize = initialFontSize * (pixelMultiplier * 1.25)\n const canvas = document.createElement(\"canvas\")\n canvas.width = canvas.height = SIZE\n const ctx = canvas.getContext(\"2d\")\n\n ctx.font = `${fontWeight} ${fontSize}px \"${fontFamily}\", Arial`\n ctx.textAlign = textAlign\n ctx.textBaseline = textBaseline\n ctx.fillStyle = fillStyle\n ctx.strokeStyle = strokeStyle\n ctx.lineWidth = lineWidth\n\n // Function to wrap text automatically\n const wrapText = (ctx, text, maxWidth) => {\n const words = text.trim().split(/\\s+/)\n if (words.length <= 1) return [text]\n\n const lines = []\n const MAX_LINES = 3\n let currentLine = words[0]\n\n for (let i = 1; i < words.length; i++) {\n const lineToMeasure = currentLine + \" \" + words[i]\n if (ctx.measureText(lineToMeasure).width > maxWidth) {\n lines.push(currentLine)\n currentLine = words[i]\n } else {\n currentLine = lineToMeasure\n }\n }\n lines.push(currentLine)\n return lines.slice(0, MAX_LINES) // Limit to 3 lines\n }\n\n /** Check if text contains manual line breaks */\n const hasManualBreaks = text.includes(\"\\n\")\n let texts\n\n if (hasManualBreaks) {\n // Use manual line breaks\n texts = text.split(/\\n/g)\n } else {\n // Auto-wrap text\n const maxWidth = SIZE - 2 * margin\n texts = wrapText(ctx, text, maxWidth)\n }\n\n /** Automatically recalculate font size to fit the bound */\n let textWidth: number = max(texts.map((text) => ctx.measureText(text).width))\n let scale = 1\n while (scale > 0 && textWidth + 2 * margin > SIZE) {\n scale -= scaleStep\n ctx.font = `${fontWeight} ${scale * fontSize}px \"${fontFamily}\", Arial`\n textWidth = max(texts.map((text) => ctx.measureText(text).width))\n }\n\n // If the text is larger than scaleMin, then render it\n const center = { x: 0.5 * SIZE, y: 0.5 * SIZE }\n\n if (scale > scaleMin) {\n const totalHeight = texts.length * (fontSize * scale * lineHeight)\n const startY =\n center.y - totalHeight / 2 + fontSize * scale * lineHeight * 0.5 // Adjust startY when offset multi text line\n\n texts.forEach((text, index) => {\n const yOffset = startY + index * (fontSize * scale * lineHeight)\n if (strokeStyle && lineWidth) {\n ctx.strokeText(text, center.x, yOffset) // Draw outlined text\n }\n ctx.fillText(text, center.x, yOffset)\n })\n }\n\n const texture = new Texture(canvas)\n texture.needsUpdate = true\n\n const material = new MeshPhongMaterial({\n map: texture,\n transparent: true,\n // @ref: https://threejs.org/docs/#api/en/materials/Material.alphaTest\n alphaTest: 0.3,\n })\n return material\n}\n\nexport class GroundLabel extends BaseObject {\n\n declare options: GroundLabelOptions;\n \n #angle = 0\n #bearing = 0\n #text = \"\"\n #offsetX = 0\n #offsetY = 0\n #originalPosition = null\n #layer: ThreeLayer = null\n\n constructor(bound: Position[], text: string, options: GroundLabelOptions, layer: ThreeLayer) {\n\n options = maptalks.Util.extend({}, OPTIONS, options, {\n layer,\n coordinate: bound,\n })\n\n const {\n altitude = 0,\n bottomHeight = 0,\n fontSize,\n fillStyle,\n textAlign,\n fontFamily,\n textBaseline,\n strokeStyle,\n lineWidth,\n angle = defaultRectAngleToCalc,\n maxFontScale,\n offsetX = 0,\n offsetY = 0,\n ...properties\n } = options\n\n super()\n this._initOptions(options)\n this.properties = properties\n\n this.#offsetX = offsetX\n this.#offsetY = offsetY\n this.#layer = layer\n\n const material = getMaterial(text, {\n fillStyle,\n fontSize,\n textAlign,\n textBaseline,\n fontFamily,\n strokeStyle,\n lineWidth,\n })\n\n // Convert angle to array if it's a single number\n const rectAngles = isArray(angle) ? angle : [angle]\n\n material.needsUpdate = true\n\n const rect = largestRect(bound, {\n cache: true,\n /**\n * Black magic here:\n * For some reason if we allow angle -90 or 90, some polygon will use that angle even if it's wrong angle to use.\n * So we remove -90 and 90 from choices, and use -85 & 85 instead.\n */\n angle: rectAngles,\n })\n\n const { cx, cy, width, angle: calculatedAngle } = rect\n this.#text = text\n this.#angle = calculatedAngle // Always use calculated angle from largestRect\n\n const geometry = new PlaneGeometry(1, 1)\n this._createMesh(geometry, material)\n\n // set object3d position\n const z = layer.altitudeToVector3(altitude + bottomHeight, altitude + bottomHeight).x\n const basePosition = layer.coordinateToVector3([cx, cy], z)\n\n this.#originalPosition = basePosition.clone()\n const finalPosition = this.#calculateFinalPosition(basePosition)\n\n const scale = width / 0.0006456122659\n // check if it has maxFontScaleLimit from option use maxFontScale\n const finalScale =\n maxFontScale && scale > maxFontScale ? maxFontScale : scale\n this.getObject3d().scale.set(finalScale, finalScale, finalScale)\n this.getObject3d().position.copy(finalPosition)\n this.getObject3d().rotation.z = (Math.PI / 180) * this.#angle\n }\n\n #calculateFinalPosition(basePosition) {\n if (this.#offsetX === 0 && this.#offsetY === 0) {\n return basePosition\n }\n\n const offsetCoordinate = [this.#offsetX, this.#offsetY]\n\n const z = this.#layer.altitudeToVector3(0, 0).x\n const offsetVector = this.#layer.coordinateToVector3(offsetCoordinate, z)\n const zeroVector = this.#layer.coordinateToVector3([0, 0], z)\n\n const worldOffsetX = offsetVector.x - zeroVector.x\n const worldOffsetY = offsetVector.y - zeroVector.y\n\n return {\n x: basePosition.x + worldOffsetX,\n y: basePosition.y + worldOffsetY,\n z: basePosition.z,\n }\n }\n\n #updatePosition() {\n if (this.#originalPosition && this.#layer) {\n const finalPosition = this.#calculateFinalPosition(this.#originalPosition)\n this.getObject3d().position.copy(finalPosition)\n }\n }\n\n set bearing(value) {\n this.#bearing = value\n const degree = this.#angle + this.#bearing\n const angle = degree > 90 || degree < -90 ? this.#angle + 180 : this.#angle\n this.getObject3d().rotation.z = (Math.PI / 180) * angle\n }\n\n get angle() {\n return this.#angle\n }\n\n get currentAngle() {\n return this.#angle\n }\n\n get text() {\n return this.#text\n }\n\n get offsetX() {\n return this.#offsetX\n }\n\n get offsetY() {\n return this.#offsetY\n }\n\n get offset() {\n return { x: this.#offsetX, y: this.#offsetY }\n }\n\n set offsetX(value) {\n if (isNumber(value)) {\n this.#offsetX = value\n this.#updatePosition()\n }\n }\n\n set offsetY(value) {\n if (isNumber(value)) {\n this.#offsetY = value\n this.#updatePosition()\n }\n }\n\n set angle(newAngle) {\n if (isNumber(newAngle)) {\n this.#angle = newAngle\n this.getObject3d().rotation.z = (Math.PI / 180) * this.#angle\n }\n }\n\n setOffset(offsetX, offsetY) {\n if (isNumber(offsetX) && isNumber(offsetY)) {\n this.#offsetX = offsetX\n this.#offsetY = offsetY\n this.#updatePosition()\n }\n }\n\n addOffset(deltaX, deltaY) {\n if (isNumber(deltaX) && isNumber(deltaY)) {\n this.#offsetX += deltaX\n this.#offsetY += deltaY\n this.#updatePosition()\n }\n }\n\n resetOffset() {\n this.#offsetX = 0\n this.#offsetY = 0\n this.#updatePosition()\n }\n\n moveToPosition(targetX, targetY) {\n if (this.#originalPosition && this.#layer) {\n const currentCenter = this.#layer.vector3ToCoordinate(\n this.#originalPosition\n )\n this.#offsetX = targetX - currentCenter.x\n this.#offsetY = targetY - currentCenter.y\n this.#updatePosition()\n }\n }\n\n updateText(newText, options: Record<string, unknown> = {}) {\n this.#text = newText\n\n const materialOptions = {\n fillStyle: options.fillStyle || this.properties.fillStyle,\n fontSize: options.fontSize || this.properties.fontSize,\n textAlign: options.textAlign || this.properties.textAlign,\n textBaseline: options.textBaseline || this.properties.textBaseline,\n fontFamily: options.fontFamily || this.properties.fontFamily,\n strokeStyle: options.strokeStyle || this.properties.strokeStyle,\n lineWidth: options.lineWidth || this.properties.lineWidth,\n }\n\n const newMaterial = getMaterial(newText, materialOptions) as Material\n ;(this.getObject3d() as Mesh).material = newMaterial\n newMaterial.needsUpdate = true\n }\n\n _animation() {\n // Flip text, if needed\n const map = this.getMap();\n if (!map) return;\n\n const bearing = map.getBearing();\n this.bearing = bearing\n }\n\n // Add bottomHeight to altitude as final altitude position\n setAltitude(altitude: number) {\n const bottomHeight = this.options.bottomHeight ?? 0\n return super.setAltitude(altitude + bottomHeight)\n }\n}\n","import { Element3DRendererOptions } from \"../types\";\n\n/**\n * minZoom, maxZoom = สำหรับระบุ zoom ที่จะให้ปรากฎตัว\n */\n\nexport const element3DRendererOptions: Element3DRendererOptions = {\n unit: {\n default: { color: \"#ffffff\", height: 0.2 },\n byCategory: {\n walkway: { color: \"#cccccc\", height: 0.1 },\n terrace: { color: \"#cccccc\", height: 0.1 },\n unenclosedarea: { color: \"#cccccc\", height: 0.2 },\n nonpublic: { color: \"#999999\", height: 0.3 },\n escalator: { height: 0.2 },\n parking: { color: \"#999999\", height: 0.1 },\n room: { color: \"#ffffff\", height: 0.5, bottomHeight: 0.12 }\n },\n },\n kiosk: {\n default: { color: \"#666666\", height: 0.6, bottomHeight: 0.12 },\n },\n fixture: {\n default: { color: \"#ffffff\", height: 0.5 },\n byCategory: {\n water: { color: \"#ACD7EC\", height: 0.1 },\n vegetation: { color: \"#91C499\", height: 0.5 },\n wall: { color: \"#787878\", topColor: '#ffffff', height: 4.2, width: 1 }\n }\n }\n}","import {\n CreateExtrudeLineStringOptionType,\n CreateExtrudePolygonOptionType,\n Element3DRendererOptions,\n} from '../../types'\nimport { element3DRendererOptions as defaultOptions } from '../element3DRendererOptions'\n\n\nconst DEFAULT_POLYGON_OPTION: CreateExtrudePolygonOptionType = {\n color: \"#FFFFFF\",\n offset: 0,\n altitude: 0,\n}\n\nexport const get3DRendererOption = (\n featureType: string,\n category: string,\n options: Element3DRendererOptions = {}\n): CreateExtrudePolygonOptionType | CreateExtrudeLineStringOptionType => {\n try {\n const option = options[featureType] ?? defaultOptions[featureType]\n return (\n (category && option.byCategory?.[category]) ??\n option?.default ??\n DEFAULT_POLYGON_OPTION\n )\n } catch (err) {\n console.log(err.message, { options, featureType, category })\n }\n}\n","import * as maptalks from \"maptalks\"\nimport { Element2DRendererOptions, IElementRenderer, IHighlightController, MapElement } from \"../types\"\nimport { ImdfFeature, LabelFeature, LevelFeature, OpeningFeature, UnitFeature } from \"../../../data\"\nimport { element2DRendererOptions as defaultOptions } from \"./element2DRendererOptions\"\nimport { PolygonOptionsType } from \"maptalks/dist/geometry/Polygon\"\nimport { Position } from \"geojson\"\nimport { Route } from \"../../../data/navigate/type\"\n\nconst DEFAULT_POLYGON_OPTION: PolygonOptionsType = {\n zIndex: 0,\n symbol: {\n polygonFill: \"#FFFFFF\",\n lineColor: \"#34495E\",\n polygonOpacity: 1,\n lineWidth: 2,\n },\n}\n\nconst ORDINAL_HEIGHT = 4\nconst MULTIORDINAL_HEIGHT_METER = 10\n\nconst getAltitude = (f: LevelFeature) =>\n Math.max(0, f.properties.ordinal * ORDINAL_HEIGHT || 0)\n\nconst getGeometryProperties = (feature: ImdfFeature) => ({\n // Core\n type: \"Feature\",\n id: feature.id,\n geometry: feature.geometry,\n properties: feature.properties,\n // Extra\n feature_type: feature.feature_type,\n category: feature.properties.category,\n name: feature.properties.name?.en,\n})\n\nconst getGeometryOption = (\n feature: ImdfFeature,\n options: Element2DRendererOptions\n): PolygonOptionsType => {\n try {\n const option = options[feature.feature_type] ?? defaultOptions[feature.feature_type]\n const category = feature.properties.category\n return (\n (category && option.byCategory?.[category]) ??\n option?.default ??\n DEFAULT_POLYGON_OPTION\n )\n } catch (err) {\n console.log(err.message, { options, feature })\n }\n}\n\nexport class Element2DRenderer\n extends EventTarget\n implements IElementRenderer\n{\n public isReady: boolean = false\n\n private options: Element2DRendererOptions\n private map: maptalks.Map\n private elementLayer: maptalks.VectorLayer\n private markerLayer: maptalks.VectorLayer\n\n constructor(map: maptalks.Map, options: Element2DRendererOptions) {\n super()\n this.options = options\n this.map = map\n\n // Create Layer for elements\n this.elementLayer = new maptalks.VectorLayer(\"elements\")\n this.elementLayer.addTo(this.map)\n\n this.markerLayer = new maptalks.VectorLayer(\"markers\")\n this.markerLayer.addTo(this.map)\n\n // Dispatch ready event, to let manager know we're ready to start\n this.isReady = true\n }\n\n createGeometry = (imdfFeature: ImdfFeature): MapElement => {\n // Create Element (Geometry)\n const feature = getGeometryProperties(imdfFeature)\n const { symbol, ...options } = getGeometryOption(imdfFeature, this.options)\n const altitude = feature.properties.ordinal * 10\n const geometry = maptalks.Geometry.fromJSON({\n feature,\n symbol,\n options: {\n ...options,\n zIndex: altitude,\n properties: { altitude },\n },\n })\n\n // Add to layer, and return\n if (Array.isArray(geometry)) {\n geometry.forEach((g) => g.addTo(this.elementLayer))\n return new maptalks.GeometryCollection(geometry)\n } else {\n geometry.addTo(this.elementLayer)\n return geometry\n }\n }\n\n createRoomWall(unit: UnitFeature, openings: OpeningFeature[]): MapElement | MapElement[] | null {\n return null\n }\n\n async createEscalator(f: ImdfFeature, coordinates: Position): Promise<MapElement | null> {\n return Promise.resolve(null)\n }\n\n createGroundLabel(f: LabelFeature, unit: UnitFeature): MapElement | MapElement[] | null {\n const text = f.properties.name\n const bound = f.geometry.coordinates[0]\n return null\n }\n\n async createBuilding(coordinate: Position, ordinal: number): Promise<MapElement | null> {\n return Promise.resolve(null)\n }\n\n createElement = (imdfFeature: ImdfFeature): MapElement | null => {\n switch (imdfFeature.feature_type) {\n default:\n return null\n }\n }\n\n showElements(elements: MapElement[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n element.setAltitude(ordinalDiff * MULTIORDINAL_HEIGHT_METER)\n element.show()\n })\n }\n hideElements(elements: MapElement[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n element.hide()\n })\n }\n\n createHighlightController(element: MapElement): IHighlightController {\n if (!(element instanceof maptalks.Geometry)) return null;\n return {\n start() {},\n clear() {}\n }\n }\n \n drawNavigation(route: Route) {}\n \n} \n","import { Element2DRendererOptions } from \"../types\";\n\nexport const element2DRendererOptions: Element2DRendererOptions = {\n unit: { \n default: { symbol: { polygonFill: '#cccccc' } },\n byCategory: {\n room: { symbol: { polygonFill: '#fff' } },\n walkway: { symbol: { polygonFill: \"#efefef\", lineColor: \"#dadada\", lineWidth: 2 } },\n terrace: { symbol: { polygonFill: \"#efefef\" } },\n unenclosedarea: { symbol: { polygonFill: \"#fff\" } },\n nonpublic: { symbol: { polygonFill: \"#999999\" }},\n }\n },\n kiosk: { \n default: {},\n },\n fixture: {\n default: { symbol: { polygonFill: \"#ffffff\" } },\n byCategory: {\n water: { symbol: { polygonFill: \"#ACD7EC\" } },\n vegetation: { symbol: { polygonFill: \"#91C499\" } }\n }\n }\n}\n","import * as maptalks from \"maptalks\"\nimport { IMarkerRenderer } from \"../types\"\nimport { Position } from \"geojson\"\n\nexport class Marker2DRenderer\n extends EventTarget\n implements IMarkerRenderer<maptalks.ui.UIMarker>\n{\n public isReady: boolean = false\n\n private map: maptalks.Map\n private markerLayer: maptalks.VectorLayer\n\n constructor(map: maptalks.Map) {\n super()\n this.map = map\n }\n\n createMarker = (\n coordinates: Position,\n ordinal: number,\n content: string\n ): maptalks.ui.UIMarker => {\n const marker = new maptalks.ui.UIMarker(coordinates, {\n content,\n collision: true,\n collisionFadeIn: true,\n altitude: 0,\n })\n marker.addTo(this.map)\n return marker\n }\n \n createTextMarker = (\n position: Position,\n label: string,\n options?: any\n ): maptalks.ui.UIMarker | null => {\n return null\n }\n\n createImageMarker = (\n position: Position,\n src: string,\n options?: any\n ): maptalks.ui.UIMarker | null => {\n return null\n }\n\n removeMarker = (marker: maptalks.ui.UIMarker) => {\n marker.remove()\n }\n\n showMarkers(elements: maptalks.ui.UIMarker[], ordinalDiff: number = 0) {}\n hideMarkers(elements: maptalks.ui.UIMarker[], ordinalDiff: number = 0) {}\n}","import * as maptalks from \"maptalks-gl\"\nimport * as THREE from \"three\"\nimport { IMarkerRenderer } from \"../types\"\nimport { BaseObject, ThreeLayer } from \"maptalks.three\"\nimport { Position } from \"geojson\"\n// import { createSpriteMaterialByLabelSymbol } from \"../utils/svg2material\"\nimport { TextMarkerOptions, TextSpriteMarker } from \"./objects/TextSpriteMarker\"\nimport { BarOptionType, BaseObjectOptionType } from \"maptalks.three/dist/type\"\n\nexport const HEIGHT_METER = 4\nexport const MULTIORDINAL_HEIGHT_METER = 9\n\nexport type ImageMarkerOptions = BaseObjectOptionType & {\n src: string\n bottomHeight?: number\n leg?: Omit<BarOptionType, 'height'> & {\n color: string\n }\n}\n\nexport type AnyMarkerOptions = TextMarkerOptions | ImageMarkerOptions\n\nexport class Marker3DRenderer\n extends EventTarget\n implements IMarkerRenderer<BaseObject>\n{\n public isReady: boolean = false\n\n private threeLayer: ThreeLayer\n\n private map: maptalks.Map \n\n constructor(map: maptalks.Map, options: any, layer: ThreeLayer) {\n super()\n this.map = map\n this.threeLayer = layer\n }\n\n createPointMaterialFromSvg(svgPath: string, size: number = 40) {\n return new THREE.PointsMaterial({\n size,\n sizeAttenuation: false, // Always same size in screen pixels (Screen pixel)\n // color: fillStyle, \n alphaTest: 0.5,\n // vertexColors: THREE.VertexColors,\n // color: 0xffffff,\n transparent: true,\n blending: THREE.NormalBlending,\n depthTest: true, // POI is hidden behind building\n depthWrite: true,\n map: new THREE.TextureLoader().load(svgPath)\n });\n }\n \n\n createTextMarker = (\n position: Position,\n label: string,\n options?: TextMarkerOptions\n ): BaseObject|BaseObject[] => {\n const combinedOptions = {\n altitude: 0,\n text: label,\n ...(options ?? {})\n }\n const [lng, lat] = position\n const marker = new TextSpriteMarker(new maptalks.Coordinate(lng, lat), combinedOptions, this.threeLayer)\n this.threeLayer.addMesh([marker])\n return marker\n } \n\n createImageMarker = (position: Position, src: string, options?: ImageMarkerOptions): BaseObject|BaseObject[] => {\n const [lng, lat] = position\n let meshes = []\n\n // Vertical Distance from floor\n const height = options.height ?? 0\n const { leg, ...markerOptions } = options\n const { color: legColor = '#000000', ...legOptions } = leg ?? {}\n const material = this.createPointMaterialFromSvg(src, 40)\n const marker = this.threeLayer.toPoint(new maptalks.Coordinate(lng, lat), { height, ...markerOptions }, material);\n marker.getObject3d().renderOrder = 10;\n\n meshes.push(marker)\n if (options.leg) {\n const legMaterial = new THREE.MeshLambertMaterial({ color: legColor, transparent: true })\n const leg = this.threeLayer.toBar(new maptalks.Coordinate(lng, lat), { ...legOptions, height }, legMaterial)\n // Hide leg behind Image Marker\n const legObj = leg.getObject3d();\n legObj.traverse((o: any) => {\n if (o.isMesh && o.material) {\n o.material.depthWrite = false; // key\n o.material.depthTest = true; // keep\n o.renderOrder = 0;\n }\n });\n meshes = [leg, ...meshes]\n }\n \n this.threeLayer.addMesh(meshes)\n return meshes\n }\n\n removeMarker = (marker: BaseObject) => {\n marker.remove()\n }\n\n showMarkers(elements: BaseObject[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n // element.setAltitude(ordinalDiff * MULTIORDINAL_HEIGHT_METER)\n element.show()\n })\n }\n\n hideMarkers(elements: BaseObject[], ordinalDiff: number = 0) {\n elements.forEach((element) => {\n try { \n element.hide()\n } catch (err) {\n console.log(`cannot hide`, err, element)\n }\n })\n }\n\n /** Marker */\n // getOrCreateIconMaterial(key) {\n // if (!this.materialByKey) this.materialByKey = new Map()\n\n // const existingMaterial = this.materialByKey.get(key)\n // if (existingMaterial) return existingMaterial\n\n // // Create new\n // const baseSymbol: maptalks.Path = {\n // markerType: \"path\",\n // markerPath: [\n // {\n // path: \"M20.775 1.2H1.225V20.35H8.215L11.3 22.8L14.385 20.35H20.775V1.2Z\",\n // fill: \"#ff0000\",\n // },\n // ],\n // markerPathWidth: 24,\n // markerPathHeight: 24\n // }\n\n // const markerSymbol: maptalks.PathMarkerSymbol = {\n // markerType: \"path\",\n // markerPath: [],\n // // TODO: Get Path by featureType.category\n // // markerPath: [{ fill: \"#FFFFFF\", path: \"M 19 3 H 5 c -1.1 0 -2 0.9 -2 2 v 14 c 0 1.1 0.9 2 2 2 h 14 c 1.1 0 2 -0.9 2 -2 V 5 c 0 -1.1 -0.9 -2 -2 -2 Z m -2 6 h -1.7 l -5 9 H 7 c -0.83 0 -1.5 -0.67 -1.5 -1.5 S 6.17 15 7 15 h 1.7 l 5 -9 H 17 c 0.83 0 1.5 0.67 1.5 1.5 S 17.83 9 17 9 Z\" }],\n // markerPathWidth: 24,\n // markerPathHeight: 24,\n // markerWidth: 24,\n // markerHeight: 24,\n // markerDy: 1.5,\n // markerDx: 1.5,\n // }\n\n // const created = createSpriteMaterialByLabelSymbol([\n // baseSymbol,\n // markerSymbol,\n // ])\n // this.materialByKey.set(key, created)\n // return created\n // }\n}","// TextSpriteMarker.js\nimport { Coordinate, Util } from \"maptalks\"\nimport * as THREE from \"three\"\nimport { BaseObject, ThreeLayer } from \"maptalks.three\" // in some builds it's maptalks.three.BaseObject\nimport { BaseObjectOptionType } from \"maptalks.three/dist/type\"\nimport { isNil, set } from \"lodash\"\nimport { Stop } from \"../../types\"\nimport { interpolateStops } from \"../../utils/interpolateStops\"\n\nconst OPTIONS: TextMarkerOptions = {\n // Texture options\n text: \"\",\n textAlign: \"center\",\n color: \"#ffffff\",\n fontFamily: \"sans-serif\",\n fontSize: 28,\n fontWeight: 400,\n background: \"transparent\",\n lineHeight: 32,\n padding: 8,\n strokeColor: \"#000000\",\n strokeWidth: 3,\n strokeStyle: \"round\",\n // Sprite options\n /* Overall scale multiplier */\n scale: 1,\n altitude: 0,\n opacity: 1\n}\n\nexport type TextMarkerOptions = BaseObjectOptionType & {\n // Texture options\n text?: string\n textAlign?: CanvasTextAlign\n color?: CanvasFillStrokeStyles[\"fillStyle\"]\n fontFamily?: string\n fontSize?: number\n fontWeight?: number\n background?: CanvasFillStrokeStyles[\"fillStyle\"]\n lineHeight?: number\n strokeColor?: CanvasFillStrokeStyles[\"strokeStyle\"]\n strokeWidth?: number\n strokeStyle?: CanvasLineJoin\n padding?: number\n maxWidth?: number\n // Sprite options\n scale?: number\n altitude?: number\n bottomHeight?: number\n opacity?: number | { stops: Stop[] }\n}\n\nexport class TextSpriteMarker extends BaseObject {\n #altitudeOffset: number = 0\n declare options: TextMarkerOptions;\n\n constructor(\n coordinate: Coordinate,\n options: TextMarkerOptions,\n layer: ThreeLayer,\n properties: Record<string, any> = {}\n ) {\n options = Util.extend({}, OPTIONS, options, { layer })\n super()\n this._coordinate = new Coordinate(coordinate)\n this._initOptions(options)\n this._createGroup()\n\n this.properties = { ...properties }\n const sprite = this._createSprite()\n\n this.getObject3d().add(sprite)\n\n this._updatePosition()\n\n this.type = \"TextSpriteMarker\"\n }\n\n getOptions(): TextMarkerOptions {\n return super.getOptions()\n }\n\n _createSprite() {\n const options = this.getOptions()\n const texture = this._createTextTexture(options.text, options)\n\n const material = new THREE.SpriteMaterial({\n map: texture,\n transparent: true,\n alphaTest: 0.1,\n })\n\n const sprite = new THREE.Sprite(material)\n\n // position will be set in _animation or directly after added to layer\n // scale to match texture aspect\n const w = texture.image.width\n const h = texture.image.height\n const base = 1 / 16 // to bring canvas px to map size-ish\n\n // Normalize text scale by the current map resolution so sprite size stays visually consistent across zoom levels.\n const normalizedScale = options.scale / this.getMap().getGLRes()\n\n sprite.scale.set(w * base * normalizedScale, h * base * normalizedScale, 1)\n\n // Compute world-space height for text and use it as altitude offset.\n this.#altitudeOffset = Math.max(\n h * base * options.scale * 0.5,\n 0.05 // minimum lift in world units\n )\n\n return sprite\n }\n\n _createTextTexture(text: string, options: TextMarkerOptions = {}) {\n const {\n padding,\n fontSize,\n fontFamily,\n fontWeight,\n lineHeight,\n background,\n color,\n textAlign,\n strokeColor,\n strokeWidth,\n maxWidth,\n } = options || {}\n\n // 1. create a temp canvas to measure\n const canvas = document.createElement(\"canvas\")\n const ctx = canvas.getContext(\"2d\")!\n ctx.font = `${fontWeight} ${fontSize}px ${fontFamily}`\n\n // 2. split into paragraphs (explicit \\n from user)\n const paragraphs = String(text).split(\"\\n\")\n\n // 3. wrap each paragraph to lines\n const wrappedLines: string[] = []\n\n paragraphs.forEach((paragraph) => {\n if (isNil(maxWidth) || isNaN(maxWidth)) {\n // no wrapping, keep as-is\n wrappedLines.push(paragraph)\n return\n }\n\n const words = paragraph.split(/\\s+/)\n let currentLine = \"\"\n\n words.forEach((word) => {\n const testLine = currentLine ? currentLine + \" \" + word : word\n const testWidth = ctx.measureText(testLine).width\n\n if (testWidth > maxWidth && currentLine) {\n // push current and start new\n wrappedLines.push(currentLine)\n currentLine = word\n } else {\n currentLine = testLine\n }\n })\n\n if (currentLine) {\n wrappedLines.push(currentLine)\n }\n })\n\n // 4. figure out final canvas size\n const lines = wrappedLines.length ? wrappedLines : [\"\"]\n const widest = Math.max(...lines.map((l) => ctx.measureText(l).width), 0)\n const finalWidth =\n (maxWidth ? Math.min(widest, maxWidth) : widest) + padding * 2\n const finalHeight = lineHeight * lines.length + padding * 2\n\n canvas.width = finalWidth\n canvas.height = finalHeight\n\n // 5. reapply styles after resize\n const ctx2 = canvas.getContext(\"2d\")!\n ctx2.font = `${fontWeight} ${fontSize}px ${fontFamily}`\n ctx2.textAlign = textAlign\n\n // background\n if (background && background !== \"transparent\") {\n ctx2.fillStyle = background\n ctx2.fillRect(0, 0, canvas.width, canvas.height)\n }\n\n // 6. draw all lines (stroke first, then fill)\n lines.forEach((line, i) => {\n const y = padding + lineHeight * (i + 0.8)\n let x = padding\n if (textAlign === \"center\") x = canvas.width / 2\n if (textAlign === \"right\" || textAlign === \"end\")\n x = canvas.width - padding\n\n if (strokeWidth > 0) {\n ctx2.lineWidth = strokeWidth\n ctx2.lineJoin = \"round\"\n ctx2.miterLimit = 2\n ctx2.strokeStyle = strokeColor\n ctx2.strokeText(line, x, y)\n }\n\n ctx2.fillStyle = color\n ctx2.fillText(line, x, y)\n })\n\n const texture = new THREE.CanvasTexture(canvas)\n texture.needsUpdate = true\n texture.minFilter = THREE.LinearFilter\n return texture\n }\n\n _updatePosition() {\n const options = this.getOptions()\n const layer = options.layer\n\n if (!layer) return\n\n const altitude = (options.altitude || 0) + this.#altitudeOffset\n const z = layer.altitudeToVector3(altitude, altitude).x\n const position = layer.coordinateToVector3(this._coordinate, z)\n set(this.properties, \"default.position\", position)\n this.getObject3d().position.copy(position)\n }\n\n _animation() {\n const layer = this.getLayer() as ThreeLayer\n\n if (!this.isAdd || !layer) return\n\n if (this._visible === true) {\n const zoom = layer.map.getZoom()\n \n const object3d = this.getObject3d()\n const { opacity } = this.getOptions()\n \n // Calculate opacity based on type\n let opacityValue: number\n if (typeof opacity === 'number') {\n opacityValue = opacity ?? 1\n } else if (Array.isArray(opacity.stops)) {\n opacityValue = interpolateStops(opacity, zoom)\n } else {\n throw new Error(`Unknown opacity value ${opacity}`)\n }\n // Hide object outside zoom range\n const visible = opacityValue > 0.5\n object3d.visible = visible\n }\n }\n\n setText(text: string) {\n const options = this.getOptions()\n options.text = text\n\n const newSprite = this._createSprite()\n const group = this.getObject3d()\n\n // Remove all old sprites from the group (but keep group itself)\n group.children.forEach((child) => group.remove(child))\n group.add(newSprite)\n\n this._updatePosition()\n }\n\n setAltitude(altitude: number) {\n const bottomHeight = this.options.bottomHeight ?? 0\n return super.setAltitude(altitude + bottomHeight + this.#altitudeOffset)\n }\n}\n","import { Stop } from \"../types\"\n\nexport const interpolateStops = ({ stops }: { stops: Stop[] }, zoom: number) => {\n // If zoom is before the first stop\n if (zoom <= stops[0][0]) return stops[0][1]\n // If zoom is after the last stop\n if (zoom >= stops[stops.length - 1][0]) return stops[stops.length - 1][1]\n \n // Find the two stops around the zoom\n for (let i = 0; i < stops.length - 1; i++) {\n const [z1, v1] = stops[i]\n const [z2, v2] = stops[i + 1]\n\n if (zoom >= z1 && zoom <= z2) {\n const t = (zoom - z1) / (z2 - z1)\n return v1 + t * (v2 - v1)\n }\n }\n}","export const getLineCenter = (line: number[][]) => {\n let x = 0, y = 0;\n for (const [lx, ly] of line) {\n x += lx;\n y += ly;\n }\n const len = line.length;\n return [x / len, y / len];\n};\n\n// Returns angle in radians\nexport const angleBetweenLineStrings = (\n line1: number[][],\n line2: number[][],\n): number => {\n const [x1, y1] = getLineCenter(line1);\n const [x2, y2] = getLineCenter(line2);\n\n const dx = x2 - x1;\n const dy = y2 - y1;\n\n // angle in radians, range (-PI, PI)\n return Math.atan2(dy, dx);\n};\n","import { Position } from \"geojson\";\nimport { booleanPointInPolygon } from \"@turf/boolean-point-in-polygon\";\nimport { polygon } from \"@turf/helpers\"\nimport { UnitFeature } from \"../../../data\";\n\nexport const findUnitOnPoint = (units: UnitFeature[], point: Position) => {\n try {\n return units.find(unit => booleanPointInPolygon(point, polygon(unit.geometry.coordinates as Position[][])))\n } catch (err) {\n return null\n }\n}"],"mappings":";;;;;;;AAAA,SAAS,iBAAAA,sBAAqB;;;ACGvB,IAAM,mBAAmB;AAEzB,IAAM,qBAAoC;AAAA,EAC/C;AAAA,EAC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;AAEA,WAAK,cAAc,QAAQ,CAAC,WAAW;AACrC,eAAO,YAAY,EAAE,SAAS,CAAC,UAAU;AACvC,cAAI,MAAM,OAAQ,OAAM,SAAS,UAAU;AAI3C,gBAAM,UAAU,KAAK,mBAAmB,gBAAgB;AAAA,QAC1D,CAAC;AAAA,MACH,CAAC;AAAA,IAMH;AAEA,SAAK,iBAAiB,QAAQ,CAAC,EAAE,SAAS,MAAM,SAAS,IAAI,CAAC;AAG9D,UAAM,OAAO;AAEb,0BAAsB,KAAK,OAAO,KAAK,IAAI,CAAC;AAAA,EAC9C;AACF;","names":["QueryObserver","point","polygon","lineString","center","booleanPointInPolygon","unit","point","kiosk","booleanPointInPolygon","section","unit","center","feature","booleanPointInPolygon","_","distance","turfCenter","feature","distance","unit","_","level","unit","distance","_","set","set","_","openings","unit","level","distance","_","_","_","turfCenter","_","center","turfCenter","_","_","openings","turfCenter","distance","center","_","booleanPointInPolygon","distance","set","distance","booleanPointInPolygon","set","feature","options","resolution","_","center","distance","point","center","center","center","center","center","feature","distance","unit","booleanPointInPolygon","options","t0","t1","t2","t3","feature","options","Map","LineString","Coordinate","_","turfDistance","turfCenter","ThreeLayer","_","turfCenter","TextureLoader","SpriteMaterial","_","scale","BaseObject","Sprite","SpriteMaterial","_","scale","maptalks","BaseObject","OPTIONS","feature","center","_","center","_","polygon","scale","feature","_","polygon","SpriteMaterial","TextureLoader","turfCenter","feature_type","properties","logoUrl","scale","difference","scale","bboxPolygon","feature","compact","turfCenter","THREE","maptalks","BaseObject","turfBuffer","cleanCoords","maptalks","BaseObject","isNumber","OPTIONS","ctx","text","scale","center","feature","turfBuffer","cleanCoords","center","BaseObject","lineString","maptalks","DEFAULT_POLYGON_OPTION","MULTIORDINAL_HEIGHT_METER","feature","DEFAULT_POLYGON_OPTION","MULTIORDINAL_HEIGHT_METER","maptalks","maptalks","THREE","Coordinate","Util","THREE","BaseObject","set","t","OPTIONS","BaseObject","Util","Coordinate","set","leg","booleanPointInPolygon","point","booleanPointInPolygon","scene","compact","turfCenter","center","_","Map","ThreeLayer","turfCenter","center","Coordinate","feature","geometry","distance","turfDistance","LineString"]}