### Install MapillaryJS Package Source: https://mapillary.github.io/mapillary-js/docs/intro/try These commands demonstrate how to install the MapillaryJS library using either Yarn or npm package managers. Both methods add the `mapillary-js` package as a dependency to your project, enabling its use in your application. ```Yarn yarn add mapillary-js ``` ```npm npm install --save mapillary-js ``` -------------------------------- ### Mapillary.Viewer Constructor Parameter Migration Source: https://mapillary.github.io/mapillary-js/docs/migration/v3 This snippet illustrates the change in how parameters are passed to the `Mapillary.Viewer` constructor between v2.x and v3.x. In v3.x, all parameters are consolidated into a single options object, improving readability and flexibility. ```JavaScript var mly = new Mapillary.Viewer({ apiClient: '', container: '', imageKey: '', userToken: '', // your other viewer options }); ``` ```JavaScript var mly = new Mapillary.Viewer( '', '', '', { // your other viewer options }, '', ); ``` -------------------------------- ### MapillaryJS Viewer Options Migration Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 This documentation outlines the changes to the configuration options for the MapillaryJS Viewer. It covers newly added options, options that have been removed, and options that have been renamed between v3.x and v4.x. ```APIDOC Viewer Options: Added Options (v4.x): - trackResize: boolean (default: true) - Description: Controls whether the viewer automatically tracks browser window resizing. Set to `false` to handle resizing with custom logic. - Breaking Change: Viewer now tracks browser window resizing by default. - dataProvider: object - Description: Allows overriding the default data provider for fetching Mapillary data. Removed Options (v3.x to v4.x): - baseImageSize: No replacement. - basePanoramaSize: No replacement. - maxImageSize: No replacement. - apiClient: Use `dataProvider` and/or `accessToken` instead. Renamed Options (v3.x to v4.x): - v3.x: imageKey - v4.x: imageId - v3.x: userToken - v4.x: accessToken ``` -------------------------------- ### Destructuring MapillaryJS Module Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 This example illustrates the change in destructuring MapillaryJS components. In v3.x, components are accessed via the `Mapillary` namespace, whereas v4.x allows direct destructuring from the `mapillary` global object (for UMD builds) or named imports. ```JavaScript const viewer = new Mapillary.Viewer({...});const marker = new Mapillary.MarkerComponent.SimpleMarker({...});const popup = new Mapillary.PopupComponent.Popup({...}); ``` ```JavaScript const { Popup, SimpleMarker, Viewer } = mapillary; const viewer = new Viewer({...});const marker = new SimpleMarker({...});const popup = new Popup({...}); ``` -------------------------------- ### MapillaryJS Camera Type Configuration Example Source: https://mapillary.github.io/mapillary-js/docs/extension/procedural-data-provider Provides a JavaScript example of how to define an array of camera configurations for MapillaryJS. This includes 'fisheye', 'perspective', and 'spherical' camera types, each with their specific focal length and distortion parameters (k1, k2) where applicable. ```javascript const cameraTypes = [ { cameraType: 'fisheye', focal: 0.45, k1: -0.006, k2: 0.004 }, { cameraType: 'perspective', focal: 0.8, k1: -0.13, k2: 0.07 }, { cameraType: 'spherical' } ]; ``` -------------------------------- ### MapillaryJS Viewer Component Options Migration Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 This section details the changes to component-specific options within the MapillaryJS Viewer configuration. It lists options that have been removed, renamed, or replaced with different mechanisms between v3.x and v4.x. ```APIDOC Viewer Component Options: Removed Options (v3.x to v4.x): - background: No replacement. - debug: No replacement. - route: No replacement. Renamed Options (v3.x to v4.x): - v3.x: imagePlane - v4.x: image - v3.x: mouse - v4.x: pointer - v3.x: spatialData - v4.x: spatial Replaced Options (v3.x to v4.x): - v3.x: image - v4.x: Moved to `fallback` options. - v3.x: navigation - v4.x: Moved to `fallback` options. ``` -------------------------------- ### MapillaryJS URL Entity Example Source: https://mapillary.github.io/mapillary-js/docs/extension/procedural-data-provider Illustrates the structure of a `URLEnt` object, which MapillaryJS uses to request additional data like thumbnails. This object typically contains an ID and a URL. ```javascript const thumb = {id: ''}; ``` -------------------------------- ### Importing MapillaryJS Module Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 This snippet demonstrates the change in how MapillaryJS modules are imported from v3.x to v4.x. Version 3.x uses a wildcard import, while v4.x adopts named imports for better tree-shaking and clarity. ```JavaScript import * as Mapillary from 'mapillary-js'; const viewer = new Mapillary.Viewer({...});const marker = new Mapillary.MarkerComponent.SimpleMarker({...});const popup = new Mapillary.PopupComponent.Popup({...}); ``` ```JavaScript import { Popup, SimpleMarker, Viewer } from 'mapillary-js'; const viewer = new Viewer({...});const marker = new SimpleMarker({...});const popup = new Popup({...}); ``` -------------------------------- ### Create Three.js Cone Geometry Source: https://mapillary.github.io/mapillary-js/docs/extension/graphics-developer This JavaScript function defines a `makeCone` utility that creates a Three.js `Mesh` object representing a cone. It initializes a `ConeGeometry` with specified dimensions (radius 2, height 6, 8 segments) and applies a `MeshPhongMaterial` with a yellow color. This cone serves as an example object to demonstrate coordinate transformation issues when rendered within MapillaryJS. ```javascript function makeCone() { const geometry = new ConeGeometry(2, 6, 8); const material = new MeshPhongMaterial({ color: 0xffff00, }); return new Mesh(geometry, material); } ``` -------------------------------- ### Initialize Mapillary Viewer with Component Options Source: https://mapillary.github.io/mapillary-js/docs/migration/v2 This snippet demonstrates the updated method for initializing the Mapillary Viewer, specifically highlighting the change in how component options are structured. In v2.x, component-specific options are nested under a `component` property within the main viewer options, providing a clearer separation compared to v1.x. ```JavaScript var mly = new Mapillary.Viewer( 'mly', '', '', { baseImageSize: Mapillary.ImageSize.Size320, cache: true, keyboard: false, sequence: { maxWidth: 150, minWidth: 80, }, renderMode: Mapillary.RenderMode.Fill, }, ); ``` ```JavaScript var mly = new Mapillary.Viewer( 'mly', '', '', { baseImageSize: Mapillary.ImageSize.Size320, component: { cache: true, keyboard: false, sequence: { maxWidth: 150, minWidth: 80, }, }, renderMode: Mapillary.RenderMode.Fill, }, ); ``` -------------------------------- ### Configure Mapillary.js Viewer URL Options Across Versions Source: https://mapillary.github.io/mapillary-js/docs/migration/v3 These snippets illustrate how to configure URL-related options for the Mapillary.js Viewer in different versions. Version 3.x introduces the `FalcorDataProvider` for most host settings, requiring explicit client and user tokens, while version 2.x integrates all host configurations directly within the Viewer constructor's `url` object. ```javascript var provider = new Mapillary.API.FalcorDataProvider({ apiHost: '', clientToken: '', clusterReconstructionHost: '', imageHost: '', imageTileHost: '', meshHost: '', scheme: '', userToken: '', }); var mly = new Mapillary.Viewer({ apiClient: provider, container: '', imageKey: '', url: { exploreHost: '', scheme: '', }, }); ``` ```javascript var mly = new Mapillary.Viewer( '', '', '', { url: { apiHost: '', clusterReconstructionHost: '', exploreHost: '', imageHost: '', imageTileHost: '', meshHost: '', scheme: '', }, }, '', ); ``` -------------------------------- ### MapillaryJS Viewer API Method Changes Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 This section details the changes to methods available on the MapillaryJS Viewer instance. Specifically, the `setUserToken` method has been renamed to `setAccessToken` and now accepts both client and user access tokens. ```APIDOC Viewer Methods: v3.x: setUserToken(token: string) - Sets the user token for authentication. v4.x: setAccessToken(token: string) - Sets the access token for authentication. - Parameters: - token: The client access token or user access token (string). - Description: This method replaces `setUserToken` and now supports both client and user access tokens. ``` -------------------------------- ### MapillaryJS Viewer Event Handling Migration Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 This documentation describes the changes in how events are handled and structured for the MapillaryJS Viewer. Event names are no longer static properties on the Viewer class, and all emitted events now follow a standardized object contract. ```APIDOC Viewer Event Handling: Event Listener Syntax Change: - v3.x: viewer.on(Mapillary.Viewer.click, ...); - v4.x: viewer.on('click', ...); - Description: Event names are now simple strings instead of static properties on the `Mapillary.Viewer` class. Event Contract Changes: - All emitted events are now objects with the following properties populated: - type: string - The type of the event (e.g., 'click'). - target: object - The instance that emitted the event (e.g., the Viewer instance). - Additional properties are provided per specific event type. ``` -------------------------------- ### Mapillary.js Component Changes (v3.x to v4.x) Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 Details the changes to components in Mapillary.js from version 3.x to 4.x, including components that have been removed or renamed. This impacts how certain functionalities are integrated or accessed. ```APIDOC Component Changes: Removed Components: v3.x Component -> v4.x Status background -> No replacement debug -> No replacement route -> Use the custom render API or custom HTML elements instead Renamed Components: v3.x Component -> v4.x Component imageplane -> image spatialdata -> spatial image -> imagefallback navigation -> navigationfallback ``` -------------------------------- ### Mapillary.js Component-Specific Event Renames (v3.x to v4.x) Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 Lists the renamings of specific events emitted by Mapillary.js components from version 3.x to 4.x. Developers should update their event listeners for these component-specific interactions. ```APIDOC Component-Specific Event Renames: v3.x Event -> v4.x Event MarkerComponent.dragend -> markerdragend MarkerComponent.dragstart -> markerdragstart MarkerComponent.changed -> markerposition MarkerComponent.hoveredkeychanged -> hover SequenceComponent.hoveredkeychanged -> hover SequenceComponent.playingchanged -> playing TagComponenent.geometrycreated -> geometrycreate TagComponenent.creategeometryend -> tagcreateend TagComponenent.creategeometrystart -> tagcreatestart TagComponenent.modechanged -> tagmode TagComponenent.tagschanged -> tags Tag.click -> click Tag.geometrychanged -> geometry Tag.changed -> tag ``` -------------------------------- ### Mapillary.js Image Class Property Changes (v3.x to v4.x) Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 Details the changes to properties of the `Node` class, which has been renamed to `Image` in Mapillary.js v4.x. This includes properties that have been removed, renamed, or replaced with new structures. ```APIDOC Image Class (formerly Node) Property Changes: Removed Properties: v3.x Property -> v4.x Status cameraUuid -> No replacement fullPano -> Use cameraType instead gpano -> Use cameraType instead pano -> Use cameraType instead mergeVersion -> No replacement projectKey -> No replacement Renamed Properties: v3.x Property -> v4.x Property alt -> computedAltitude ca -> compassAngle cameraProjectionType -> cameraType clusterKey -> clusterId computedCA -> computedCompassAngle computedLatLon -> computedLngLat key -> id latLon -> lngLat mergeCC -> mergeId organizationKey -> ownerId orientation -> exifOrientation originalAlt -> originalAltitude originalCA -> originalCompassAngle originalLatLon -> originalLngLat sequenceKey -> sequenceId userKey -> creatorId userName -> creatorName Replaced Properties: v3.x Property -> v4.x Property focal, ck1, ck2 -> cameraParameters ``` -------------------------------- ### Mapillary.Viewer User Authentication Token Method Name Change Source: https://mapillary.github.io/mapillary-js/docs/migration/v3 This snippet highlights the renaming of the method used to set the user authentication token in the `Mapillary.Viewer` class. The method `setAuthToken` from v2.x has been updated to `setUserToken` in v3.x for clarity. ```JavaScript viewer.setUserToken(''); ``` ```JavaScript viewer.setAuthToken(''); ``` -------------------------------- ### Mapillary.js Interaction API Changes (v3.x to v4.x) Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 Documents changes to the interaction API in Mapillary.js from version 3.x to 4.x, specifically noting removed interaction methods. This affects how certain user interactions are handled or configured. ```APIDOC Interaction API Changes: Removed Interaction Methods: v3.x Method -> v4.x Status MouseComponent#doubleClickZoom -> No replacement ``` -------------------------------- ### Mapillary.js Core Event Renames (v3.x to v4.x) Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 Documents the renaming of core event types in Mapillary.js from version 3.x to 4.x, providing a direct mapping for migration. Developers should update their event listeners to use the new names. ```APIDOC Core Event Renames: v3.x Event Name -> v4.x Event Name bearingchanged -> bearing fovchanged -> fov loading -> dataloading navigablechanged -> navigable nodechanged -> image positionchanged -> position povchanged -> pov removed -> remove sequenceedgeschanged -> sequenceedges spatialedgeschanged -> spatialedges ``` -------------------------------- ### MapillaryJS v2.x Edge Status Interface and Node Properties Source: https://mapillary.github.io/mapillary-js/docs/migration/v2 MapillaryJS v2.x introduces an asynchronous edge handling mechanism. Edges are now separated into `sequence` and `spatial` types, and their status is represented by the `IEdgeStatus` interface. This snippet defines the `IEdgeStatus` interface and the new edge-related properties on a node in v2.x. ```APIDOC interface IEdgeStatus { cached: boolean; edges: IEdge[]; } Node Properties (v2.x): sequenceEdges: IEdgeStatus sequenceEdges$: Observable spatialEdges: IEdgeStatus spatialEdges$: Observable Description: - IEdgeStatus: Interface defining the status of edges, including a 'cached' flag and the 'edges' array. - sequenceEdges: The current status of sequence edges. - sequenceEdges$: An Observable stream that emits updates to the sequence edge status. - spatialEdges: The current status of spatial edges. - spatialEdges$: An Observable stream that emits updates to the spatial edge status. Note: Edges may not be cached immediately upon node retrieval; use the Observable streams or dedicated events for updates. ``` -------------------------------- ### Mapillary Viewer Navigation Methods Error Handling Source: https://mapillary.github.io/mapillary-js/docs/migration/v2 This section details the error handling behavior for Mapillary Viewer's navigation methods. The `moveDir`, `moveCloseTo`, and `moveToKey` methods are designed to throw errors under specific conditions, such as the absence of a valid navigation result or the occurrence of I/O related problems. Callers are responsible for implementing appropriate error handling mechanisms. ```APIDOC Viewer.moveDir(direction: string): void throws Error - Description: Attempts to move the viewer in a specified direction. - Throws: Error if no valid navigation result is found or an I/O problem occurs. Viewer.moveCloseTo(key: string): void throws Error - Description: Attempts to move the viewer to an image close to the specified key. - Throws: Error if no valid navigation result is found or an I/O problem occurs. Viewer.moveToKey(key: string): void throws Error - Description: Attempts to move the viewer directly to the specified image key. - Throws: Error if an I/O related problem occurs during the operation. ``` -------------------------------- ### Deactivate Image Tiling in ProceduralDataProvider Source: https://mapillary.github.io/mapillary-js/docs/extension/procedural-data-provider This method is intended for image tiling functionality. In this example, it explicitly deactivates tiling by returning a rejected Promise with a 'Not implemented' error, indicating that this feature is not supported by the procedural data provider. ```JavaScript class ProceduralDataProvider extends DataProviderBase { // ... getImageTiles(tiles) { return Promise.reject(new MapillaryError('Not implemented')); } } ``` -------------------------------- ### Mapillary.js Type Definition Changes (v3.x to v4.x) Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 Outlines the changes to fundamental type definitions in Mapillary.js from version 3.x to 4.x, including renamings and structural modifications. Developers should update their type annotations and object structures accordingly. ```APIDOC Type Definition Changes: v3.x Type -> v4.x Type ILatLon: { lat: number, lon: number } -> LngLat: { lat: number, lng: number } ILatLonAlt: { alt: number, lat: number, lon: number } -> LngLatAlt: { alt: number, lat: number, lng: number } AbortMapillaryError -> CancelMapillaryError ``` -------------------------------- ### Return Empty Clusters in ProceduralDataProvider Source: https://mapillary.github.io/mapillary-js/docs/extension/procedural-data-provider This method provides cluster data. For this example, it returns an empty cluster object, indicating that no point clouds are generated or provided by this data provider. It resolves a Promise with an object containing empty points and a reference. ```JavaScript class ProceduralDataProvider extends DataProviderBase { // ... getCluster(url) { return Promise.resolve({points: {}, reference: REFERENCE}); } } ``` -------------------------------- ### Return Empty Meshes in ProceduralDataProvider Source: https://mapillary.github.io/mapillary-js/docs/extension/procedural-data-provider This method provides mesh data. For this example, it returns an empty mesh object, indicating that no triangles or mesh geometries are generated or provided by this data provider. It resolves a Promise with empty faces and vertices arrays. ```JavaScript class ProceduralDataProvider extends DataProviderBase { // ... getMesh(url) { return Promise.resolve({faces: [], vertices: []}); } } ``` -------------------------------- ### MapillaryJS v1.x Node Edge Properties Source: https://mapillary.github.io/mapillary-js/docs/migration/v2 In MapillaryJS v1.x, the `nodechanged` event guaranteed that the `edges` array was always populated and cached, allowing immediate traversal. This snippet shows the structure of edge-related properties on a node in v1.x. ```APIDOC Node Properties (v1.x): edges: IEdge[] edgesCached: boolean Description: - edges: An array of IEdge objects, always populated when retrieved from the nodechanged event. - edgesCached: A boolean indicating if edges are cached. ``` -------------------------------- ### MapillaryJS v2.x Node Property Changes Source: https://mapillary.github.io/mapillary-js/docs/migration/v2 MapillaryJS v2.x introduces significant changes to node properties, including renamed and removed fields, while some properties remain identical to v1.x. This documentation outlines the mapping of changed properties and lists those that have been removed entirely, requiring code adjustments for applications migrating from v1.x. ```APIDOC Node Properties - Identical (v1.x & v2.x): - ca - capturedAt - fullPano - image - key - latLon - loadStatus - merged - mesh - pano Node Properties - Changed (v1.x to v2.x mapping): - apiNavImIm.atomic_scale -> scale - apiNavImIm.ca -> originalCA - apiNavImIm.calt -> alt - apiNavImIm.camera_mode -> scale - apiNavImIm.captured_at -> capturedAt - apiNavImIm.cca -> computedCA - apiNavImIm.cfocal -> focal - apiNavImIm.clat -> computedLatLon.lat - apiNavImIm.clon -> computedLatLon.lon - apiNavImIm.gpano -> gpano - apiNavImIm.height -> height - apiNavImIm.key -> key - apiNavImIm.lat -> originalLatLon.lat - apiNavImIm.lon -> originalLatLon.lon - apiNavImIm.merge_cc -> mergeCC - apiNavImIm.merge_version -> mergeVersion - apiNavImIm.orientation -> orientation - apiNavImIm.rotation -> rotation - apiNavImIm.user -> username - apiNavImIm.width -> width - sequence.key -> sequenceKey Node Properties - Removed (v1.x only): - apiNavImIm - apiNavImIm.camera_mode - apiNavImIm.fmm35 - hs - sequence - worthy ``` -------------------------------- ### Transform Camera Local Matrix for MapillaryJS Integration Source: https://mapillary.github.io/mapillary-js/docs/extension/graphics-developer This snippet shows how to transform the camera's local transformation matrix to correctly render objects placed in the Three.js coordinate system. It multiplies the `MAPILLARY_TO_THREE_TRANSFORM` with the inverted view matrix, effectively adjusting the camera's perspective. ```javascript const matrix = MAPILLARY_TO_THREE_TRANSFORM.clone().multiply( new Matrix4().fromArray(viewMatrix).invert(), ); ``` -------------------------------- ### MapillaryJS and Three.js Coordinate System Mapping Source: https://mapillary.github.io/mapillary-js/docs/extension/graphics-developer This specification details the coordinate system differences between MapillaryJS and Three.js, which are crucial for correct 3D object rendering. MapillaryJS uses a right-handed local topocentric system (East, North, Up), while Three.js defaults to a system where Y is up and -Z is forward. The table illustrates the mapping of cardinal directions to their respective axes in both coordinate systems, highlighting the necessary transformations. ```APIDOC Coordinate System Mapping: | ENU | Direction | MapillaryJS | Three.js | | --- | --- | --- | --- | | East | Right | X | X | | North | Forward | Y | -Z | | Up | Up | Z | Y | MapillaryJS: - Right-handed local topocentric coordinate system - X: East - Y: North - Z: Up Three.js (Default): - Y: Up - -Z: Forward Transformation Implication: - To align MapillaryJS coordinates with Three.js default, rotate 90 degrees counter-clockwise around the X-axis. - To align Three.js coordinates with MapillaryJS, apply the inverse transform (90 degrees clockwise rotation around the X-axis). ``` -------------------------------- ### Subscribing to MapillaryJS v2.x Edge Change Events Source: https://mapillary.github.io/mapillary-js/docs/migration/v2 In MapillaryJS v2.x, due to the asynchronous nature of edge loading, developers should subscribe to specific viewer events to be notified when sequence or spatial edges for the current node are cached or updated. These events always relate to the node retrieved from the `nodechanged` event. ```JavaScript viewer.on(Mapillary.Viewer.sequenceedgeschanged, function(status) { /* */ }); viewer.on(Mapillary.Viewer.spatialedgeschanged, function(status) { /* */ }); ``` -------------------------------- ### Apply Rotation to Three.js Object Rotation in MapillaryJS Coordinates Source: https://mapillary.github.io/mapillary-js/docs/extension/graphics-developer This snippet shows how to transform an object's original rotation to align with the MapillaryJS coordinate system. It multiplies the `THREE_TO_MAPILLARY_TRANSFORM` matrix with a new matrix derived from the object's original Euler rotation, then extracts the resulting Euler rotation. ```javascript const rotationMatrix = THREE_TO_MAPILLARY_TRANSFORM.clone().multiply( new Matrix4().makeRotationFromEuler(originalRotation), ); const rotation = new Euler().setFromRotationMatrix(rotationMatrix); ``` -------------------------------- ### Mapillary.js Enum Renames (v3.x to v4.x) Source: https://mapillary.github.io/mapillary-js/docs/migration/v4 Documents the renaming of enum types in Mapillary.js from version 3.x to 4.x. This change affects how certain directional or categorical values are referenced. ```APIDOC Enum Renames: v3.x Enum -> v4.x Enum EdgeDirection -> NavigationDirection ``` -------------------------------- ### Include MapillaryJS CSS Stylesheet Source: https://mapillary.github.io/mapillary-js/docs/intro/try This HTML snippet links the MapillaryJS stylesheet from the unpkg CDN, providing the necessary styling for the viewer components. It should be placed within the `` section of your HTML file. ```HTML ``` -------------------------------- ### Initialize MapillaryJS Viewer with CDN (UMD) Source: https://mapillary.github.io/mapillary-js/docs/intro/try This JavaScript snippet initializes the MapillaryJS viewer when the library is loaded via CDN, using its global UMD name `mapillary`. It creates a new Viewer instance, referencing the container by its ID, and requires an access token and image ID. ```JavaScript ``` -------------------------------- ### Initialize MapillaryJS Viewer with ES6 Module Bundler Source: https://mapillary.github.io/mapillary-js/docs/intro/try This code demonstrates how to initialize the MapillaryJS Viewer when using an ES6 module bundler (like Webpack or Rollup). It imports the Viewer class, creates a container element, and instantiates the viewer with an access token and image ID. ```TypeScript import {Viewer, ViewerOptions} from 'mapillary-js'; const container = document.createElement('div'); container.style.width = '400px'; container.style.height = '300px'; document.body.appendChild(container); const options: ViewerOptions = { accessToken: '', container, imageId: '',}; const viewer = new Viewer(options); ``` ```JavaScript import {Viewer} from 'mapillary-js'; const container = document.createElement('div'); container.style.width = '400px'; container.style.height = '300px'; document.body.appendChild(container); const viewer = new Viewer({ accessToken: '', container, imageId: '',}); ``` -------------------------------- ### Include MapillaryJS via CDN Source: https://mapillary.github.io/mapillary-js/docs/intro/try This HTML snippet includes both the MapillaryJS JavaScript library and its CSS stylesheet directly from the unpkg CDN. This method is suitable for quick integration without a module bundler, typically placed in the `` section. ```HTML ``` -------------------------------- ### Define MapillaryJS Viewer Container in HTML Source: https://mapillary.github.io/mapillary-js/docs/intro/try This HTML snippet defines a `div` element that will serve as the container for the MapillaryJS viewer. It includes inline styles to set the dimensions of the viewer, and should be placed within the `` of your HTML file. ```HTML
``` -------------------------------- ### Initialize WebGL Shader Program Source: https://mapillary.github.io/mapillary-js/docs/extension/webgl-custom-renderer This JavaScript function compiles vertex and fragment shaders and links them into a WebGL shader program. It takes the WebGL context and shader sources as input, returning the compiled shaders and the program object for rendering. ```JavaScript function initShaderProgram(gl, vsSource, fsSource) { const vertexShader = loadShader(gl, gl.VERTEX_SHADER, vsSource); const fragmentShader = loadShader(gl, gl.FRAGMENT_SHADER, fsSource); const shaderProgram = gl.createProgram(); gl.attachShader(shaderProgram, vertexShader); gl.attachShader(shaderProgram, fragmentShader); gl.linkProgram(shaderProgram); // ... return {fragmentShader, shaderProgram, vertexShader};} ``` -------------------------------- ### Initialize WebGL Resources and Shaders in Mapillary.js Custom Renderer Source: https://mapillary.github.io/mapillary-js/docs/extension/webgl-custom-renderer This JavaScript code block illustrates the `onAdd` method of a `WebGLCubeRenderer`, which is invoked when the custom renderer is added to the Mapillary.js `Viewer`. It calculates the initial `modelMatrix` for the cube, initializes WebGL shader programs and buffers using the provided `context`, and retrieves attribute and uniform locations for the shader program. This method is crucial for setting up all necessary WebGL resources before rendering begins. ```JavaScript class WebGLCubeRenderer { // ... onAdd(viewer, reference, context) { this.cube.modelMatrix = makeModelMatrix(this.cube.geoPosition, reference); const gl = context; const {fragmentShader, shaderProgram, vertexShader} = initShaderProgram( gl, vertexShaderSource, fragmentShaderSource, ); this.buffers = initBuffers(gl); this.fragmentShader = fragmentShader; this.vertexShader = vertexShader; this.shaderProgram = shaderProgram; this.programInfo = { program: shaderProgram, attribLocations: { vertexPosition: gl.getAttribLocation(shaderProgram, 'aVertexPosition'), vertexColor: gl.getAttribLocation(shaderProgram, 'aVertexColor'), }, uniformLocations: { modelMatrix: gl.getUniformLocation(shaderProgram, 'uModelMatrix'), projectionMatrix: gl.getUniformLocation( shaderProgram, 'uProjectionMatrix', ), viewMatrix: gl.getUniformLocation(shaderProgram, 'uViewMatrix'), }, }; }} ``` -------------------------------- ### Initialize FlyCameraControls and Set Initial Camera Pose Source: https://mapillary.github.io/mapillary-js/docs/extension/fly-controls This method initializes the `FlyCameraControls` by creating a `PerspectiveCamera` and `FlyControls` instance. It uses the `viewMatrix` inverse to set the camera's initial position, attaches event listeners for control changes, and updates the viewer's projection and view matrices. ```JavaScript class FlyCameraControls { // ... onActivate(viewer, viewMatrix, projectionMatrix, reference) { this.reference = reference; const {fov, movementSpeed, rollSpeed} = this; // Create camera const container = viewer.getContainer(); const aspect = calcAspect(container); const camera = new PerspectiveCamera(fov, aspect, 0.1, 10000); camera.rotateX(Math.PI / 2); // Create controls this.controls = new FlyControls(camera, container); this.controls.movementSpeed = movementSpeed; this.controls.rollSpeed = rollSpeed; // Set camera position const viewMatrixInverse = new Matrix4().fromArray(viewMatrix).invert(); const me = viewMatrixInverse.elements; const translation = [me[12], me[13], me[14]]; this.controls.object.position.fromArray(translation); // Listen to control changes this.onControlsChange = () => { this.controls.object.updateMatrixWorld(true); this.viewMatrixCallback( this.controls.object.matrixWorldInverse.toArray(), ); }; this.controls.addEventListener('change', this.onControlsChange); // Update pose and projection this.clock = new Clock(); const delta = this.clock.getDelta(); this.controls.update(delta); camera.updateProjectionMatrix(); this.projectionMatrixCallback(camera.projectionMatrix.toArray()); }} ``` -------------------------------- ### Registering a Viewer Load Event Handler Source: https://mapillary.github.io/mapillary-js/docs/main/event Registers an event handler for the `load` event, which fires immediately after all necessary resources have been downloaded and the first visually complete rendering of the viewer has occurred. This is useful for initializing application-specific functionality and resources. ```JavaScript const viewer = new Viewer({accessToken, container}); viewer.on('load', (event) => console.log(`'${event.type}'`)); ``` -------------------------------- ### Mapillary.js Viewer Event Object Interfaces Source: https://mapillary.github.io/mapillary-js/docs/main/event Detailed API documentation for key event objects emitted by the Mapillary.js Viewer, specifically `ViewerPointerEvent` and `PointOfView`. It describes their properties, such as coordinate systems for pointer events and camera orientation for camera pose events, which are crucial for interactive applications. ```APIDOC ViewerPointerEvent Interface: - Emitted by pointer events (e.g., 'dblclick', 'mousemove'). - Properties: - pixelPoint: The pixel coordinates in the viewer container of the mouse event target. - basicPoint: The geodetic location in the viewer of the mouse event target. - lngLat: The basic image coordinates (longitude and latitude) in the current image of the mouse event target. Viewer.getPointOfView(): PointOfView - Method to retrieve the current camera pose information from the Viewer. - Returns: A PointOfView object. PointOfView Interface: - Represents the camera's viewpoint, position, and orientation. - Properties: - bearing: The horizontal orientation of the camera in degrees (0-360). - tilt: The vertical orientation of the camera in degrees (e.g., 0 for horizontal, 90 for looking straight down). ``` -------------------------------- ### Retain Original Three.js Object Rotation for Camera Alignment Source: https://mapillary.github.io/mapillary-js/docs/extension/graphics-developer When using the camera matrix transformation approach, the object's original rotation can be used directly. This is because the objects are placed in the Three.js coordinate system, and the camera is adjusted to match. ```javascript const rotation = new Euler().copy(originalRotation); ``` -------------------------------- ### MapillaryJS API Data Handling Utilities Source: https://mapillary.github.io/mapillary-js/docs/extension/procedural-data-provider Describes utility functions provided by MapillaryJS (via `api.modules.api`) for processing data returned from a data provider. These functions assist in decompressing data, fetching array buffers, and reading PBF mesh files. ```APIDOC MapillaryJS API Data Handling Utilities (from `api.modules.api`): 1. decompress(data: ArrayBuffer | string): Promise - Purpose: Decompresses data, typically for compressed JSON objects or array buffers. - Parameters: - `data`: The compressed data, either as an ArrayBuffer or a string. - Returns: A Promise that resolves with the decompressed ArrayBuffer. 2. fetchArrayBuffer(url: string, options?: RequestInit): Promise - Purpose: Fetches data from a given URL as an ArrayBuffer. - Parameters: - `url`: The URL to fetch data from. - `options`: Optional standard `RequestInit` options for the fetch operation. - Returns: A Promise that resolves with the fetched ArrayBuffer. 3. readMeshPbf(buffer: ArrayBuffer): Mesh - Purpose: Parses a Protocol Buffer (PBF) ArrayBuffer into a Mesh object. - Parameters: - `buffer`: The ArrayBuffer containing the PBF mesh data. - Returns: A `Mesh` object representing the parsed mesh data. ``` -------------------------------- ### Initialize ProceduralDataProvider with Generated Data Source: https://mapillary.github.io/mapillary-js/docs/extension/procedural-data-provider The constructor of `ProceduralDataProvider` initializes the base class, generates image and sequence data, and maps geo cells to arrays of images. It uses `S2GeometryProvider` for geometry if not provided, populating internal data structures for subsequent data retrieval. ```JavaScript class ProceduralDataProvider extends DataProviderBase { constructor(options) { super(options.geometry ?? new S2GeometryProvider()); const {images, sequences} = generateImages(); this.images = images; this.sequences = sequences; this.cells = generateCells(images, this._geometry); } } ``` -------------------------------- ### Define Three.js to MapillaryJS Coordinate Transformation Matrix Source: https://mapillary.github.io/mapillary-js/docs/extension/graphics-developer This snippet defines a constant transformation matrix used to rotate coordinates from the default Three.js coordinate system (Y-up) to the MapillaryJS ENU (East-North-Up) coordinate system, which typically has Z-up or a different orientation. ```javascript const THREE_TO_MAPILLARY_TRANSFORM = new Matrix4().makeRotationFromEuler( new Euler(Math.PI / 2, 0, 0), ); ``` -------------------------------- ### MapillaryJS Custom Renderer API Reference Source: https://mapillary.github.io/mapillary-js/docs/extension/webgl-custom-renderer Comprehensive API documentation for integrating and managing custom WebGL renderers within the MapillaryJS Viewer. This section details the `ICustomRenderer` interface methods for lifecycle management and drawing, along with the `Viewer` class methods for adding and removing custom renderers. ```APIDOC ICustomRenderer.onRemove(viewer: Viewer, context: WebGLRenderingContext): void - Description: Called when the custom renderer has been removed from the `Viewer`. - Purpose: Provides an opportunity to clean up WebGL resources (e.g., shaders, programs, buffers) and event listeners that were created during the renderer's lifecycle. - Parameters: - `viewer`: The MapillaryJS Viewer instance. - `context`: The WebGL rendering context. ICustomRenderer.render(context: WebGLRenderingContext, viewMatrix: number[], projectionMatrix: number[]): void - Description: Called during every animation frame when the Viewer is active. - Purpose: Allows the custom renderer to draw its content into the WebGL context. Custom renderers should not clear the context but instead superimpose content. - Parameters: - `context`: The WebGL rendering context. - `viewMatrix`: The current view matrix provided by MapillaryJS. - `projectionMatrix`: The current projection matrix provided by MapillaryJS. - Note: This method is not called when the Viewer is halted (no motion). Refer to Animation examples for forced rendering. Viewer.addCustomRenderer(renderer: ICustomRenderer): void - Description: Adds a custom renderer to the MapillaryJS Viewer. - Purpose: Integrates a user-defined WebGL renderer into the Viewer's rendering pipeline, allowing it to draw custom 3D objects. - Parameters: - `renderer`: An instance of a class implementing the `ICustomRenderer` interface. Viewer.removeCustomRenderer(renderer: ICustomRenderer): void - Description: Removes a previously added custom renderer from the MapillaryJS Viewer. - Purpose: Disables and detaches a custom renderer from the Viewer's rendering process, triggering its `onRemove` method for cleanup. - Parameters: - `renderer`: The `ICustomRenderer` instance to be removed. ``` -------------------------------- ### Generate Image Buffer On-the-Fly in ProceduralDataProvider Source: https://mapillary.github.io/mapillary-js/docs/extension/procedural-data-provider This method is responsible for generating and returning an image buffer dynamically. It calls an external `generateImageBuffer()` function to create the image data when requested, typically for a specific URL. ```JavaScript class ProceduralDataProvider extends DataProviderBase { // ... getImageBuffer(url) { return generateImageBuffer(); } } ``` -------------------------------- ### Define MapillaryJS to Three.js Coordinate Transformation Matrix (Inverse) Source: https://mapillary.github.io/mapillary-js/docs/extension/graphics-developer This constant defines the inverse transformation matrix, used to convert coordinates from the MapillaryJS ENU system back to the Three.js coordinate system. This approach is useful when transforming the camera matrix rather than individual objects. ```javascript const MAPILLARY_TO_THREE_TRANSFORM = new Matrix4().makeRotationFromEuler( new Euler(-Math.PI / 2, 0, 0), ); ``` -------------------------------- ### Remove Event Handlers from Mapillary.js Viewer Source: https://mapillary.github.io/mapillary-js/docs/main/event This example illustrates how to remove a previously registered event handler from the Mapillary.js Viewer using the `viewer.off()` method. It shows the process of attaching an 'image' event listener and then detaching it when it's no longer needed, preventing memory leaks and unnecessary processing. ```JavaScript const viewer = new Viewer({accessToken, container}); const onImage = (event) => { const imageId = event.image.id; console.log(`id: ${imageId}'`);}; viewer.on('image', onImage); // ... // Remove event handler at a later time viewer.off('image', onImage); ``` -------------------------------- ### Pseudo-Algorithm for Triangulating Polygons on a Sphere Source: https://mapillary.github.io/mapillary-js/docs/theory/polygon-triangulation This pseudo-algorithm outlines the steps to triangulate a polygon on a spherical surface. It involves dividing the problem into subareas, projecting coordinates to a 2D plane, clipping the polygon parts, triangulating each part in 2D, and then assembling the resulting 3D triangles. ```Pseudo-code 1. Divide the original image into x times y rectangular subareas where x >= 3 and y >= 2 to ensure that a subarea covers at most an angle of 120 degrees on the sphere. 2. Create an empty 3D coordinate triangles array. 3. For each subarea: 1. Clip the polygon according to the subarea boundaries using the distorted 2D coordinates. 2. Unproject the distorted 2D coordinates of the polygon to undistorted 3D coordinates. 3. Project the the undistorted 3D coordinates to a plane in front of a camera with principal ray going through the center of the subarea. 4. Triangulate the projected 2D coordinates. 5. Add the undistorted 3D coordinates corresponding to the triangle indices to the triangles array. 4. Use the assembled 3D coordinate triangle array. ``` -------------------------------- ### Apply Inverse Transformation to Three.js Object Position for Camera Alignment Source: https://mapillary.github.io/mapillary-js/docs/extension/graphics-developer When transforming the camera matrix, this code applies the inverse transformation (`MAPILLARY_TO_THREE_TRANSFORM`) directly to the topocentric ENU position. This converts the position into the Three.js coordinate system, allowing the original translation to be added without further transformation. ```javascript const [x, y, z] = geoToTopocentric(OBJECT_GEO_ANCHOR, reference); const position = new Vector3(x, y, z).applyMatrix4( MAPILLARY_TO_THREE_TRANSFORM, ); position.add(originalTranslation); ``` -------------------------------- ### Implement Custom MapillaryJS Geometry Provider Source: https://mapillary.github.io/mapillary-js/docs/extension/geometry-provider This code snippet demonstrates the basic structure for creating a custom geometry provider in MapillaryJS. It shows how to extend the `GeometryProviderBase` class and declares the four abstract methods (`bboxToCellIds`, `getAdjacent`, `getVertices`, `lngLatToCellId`) that must be implemented by any custom provider to define its geo-indexing logic. ```TypeScript class MyGeometryProvider extends GeometryProviderBase { public bboxToCellIds(sw, ne) { // ... } public getAdjacent(cellId) { // ... } public getVertices(cellId) { // ... } public lngLatToCellId(lngLat) { // ... } } ``` -------------------------------- ### MapillaryJS GeometryProviderBase Abstract Methods Source: https://mapillary.github.io/mapillary-js/docs/extension/geometry-provider This section details the abstract methods of the `GeometryProviderBase` class in MapillaryJS, which must be implemented by any custom geometry provider. These methods define how the provider handles geographic indexing, including converting bounding boxes to cell IDs, finding adjacent cells, retrieving cell outlines, and converting coordinates to cell IDs. ```APIDOC GeometryProviderBase Abstract Methods: bboxToCellIds(sw, ne) - Description: Converts a geodetic bounding box to the minimum set of cell ids containing the bounding box. - Parameters: - sw: South-west coordinates of the bounding box. - ne: North-east coordinates of the bounding box. - Returns: A set of cell IDs. getAdjacent(cellId) - Description: Returns the cell ids of all adjacent cells. In the case of approximately rectangular cells this is typically the eight orthogonally and diagonally adjacent cells. - Parameters: - cellId: The ID of the reference cell. - Returns: An array of adjacent cell IDs. getVertices(cellId) - Description: Returns the vertices of the cell outline. The vertices form an unclosed polygon in the 2D longitude, latitude space. No assumption on the position of the first vertex relative to the others can be made. - Parameters: - cellId: The ID of the cell. - Returns: An array of longitude-latitude pairs representing the cell's vertices. lngLatToCellId(lngLat) - Description: Converts geodetic coordinates to a cell id. - Parameters: - lngLat: An array or object containing longitude and latitude coordinates. - Returns: The cell ID corresponding to the given coordinates. ``` -------------------------------- ### Implement FlyCameraControls Constructor Source: https://mapillary.github.io/mapillary-js/docs/extension/fly-controls Demonstrates the basic constructor for a custom camera controls class, initializing properties like field of view, movement speed, and roll speed from options. These properties are typically used to configure the behavior of the camera controls. ```javascript class FlyCameraControls { constructor() { this.fov = options.fov; this.movementSpeed = options.movementSpeed; this.rollSpeed = options.rollSpeed; } // ... } ```