### Live Example: Integrate Three.js with MapillaryJS Viewer
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/graphics-developer.md
Demonstrates how to initialize a MapillaryJS viewer and add a custom Three.js renderer. This example shows the basic setup for displaying Three.js objects within the MapillaryJS environment.
```jsx
function render(props) {
let viewer;
function init(opts) {
const {container} = opts;
const imageId = 'image|fisheye|0';
const dataProvider = new procedural.ProceduralDataProvider({intervals: 2});
const options = graphics.makeViewerOptions({container, dataProvider});
viewer = new Viewer(options);
viewer.moveTo(imageId).catch(mapillaryErrorHandler);
const renderer = new graphics.ThreeToMapillaryRenderer({
translation: [0, 5, 0],
});
viewer.addCustomRenderer(renderer);
}
function dispose() {
if (viewer) {
viewer.remove();
}
}
return (
);
}
```
--------------------------------
### Live Example: Custom Renderer Integration
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/graphics-developer.md
Demonstrates integrating a custom MapillaryToThreeRenderer with a ViewerComponent. This example shows how to initialize the viewer, add the custom renderer, and manage its lifecycle.
```jsx
function render(props) {
let viewer;
function init(opts) {
const {container} = opts;
const imageId = 'image|fisheye|0';
const dataProvider = new procedural.ProceduralDataProvider({intervals: 2});
const options = graphics.makeViewerOptions({container, dataProvider});
viewer = new Viewer(options);
viewer.moveTo(imageId).catch(mapillaryErrorHandler);
const renderer = new graphics.MapillaryToThreeRenderer({
translation: [0, 5, 0],
});
viewer.addCustomRenderer(renderer);
}
function dispose() {
if (viewer) {
viewer.remove();
}
}
return (
);
}
```
--------------------------------
### Initialize Viewer with Component Options (v2.x)
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/migration/v2.md
Example of initializing the Mapillary Viewer in v2.x, where component options are nested under a 'component' key.
```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,
},
);
```
--------------------------------
### Initialize Viewer with Component Options (v1.x)
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/migration/v2.md
Example of initializing the Mapillary Viewer in v1.x, where component options were part of the main viewer options.
```javascript
var mly = new Mapillary.Viewer(
'mly',
'',
'',
{
baseImageSize: Mapillary.ImageSize.Size320,
cache: true,
keyboard: false,
sequence: {
maxWidth: 150,
minWidth: 80,
},
renderMode: Mapillary.RenderMode.Fill,
},
);
```
--------------------------------
### Initialize Mapillary Editor
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/extend-editor.html
This snippet shows the basic setup for initializing the Mapillary editor. Ensure you have the access token and a container element.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/extend-editor.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({ accessToken, container });
```
--------------------------------
### Camera Capture Generation Example
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/procedural-data-provider.md
Defines camera types and their parameters for visualization. Supports fisheye, perspective, and spherical camera types.
```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',
},
];
```
--------------------------------
### Initialize Viewer with Coordinates
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/viewer-coordinates.html
Sets up the Mapillary viewer in a specified container element using an access token. This is the basic setup required to display Mapillary imagery.
```javascript
body { margin: 0; padding: 0; }
html, body, .viewer { width: 100%; height: 100%; }
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/viewer-coordinates.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
container,
});
```
--------------------------------
### Get Cluster Implementation
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/procedural-data-provider.md
Returns empty clusters as no point clouds are generated for this example. Ensure to return a Promise resolving to an object with 'points' and 'reference'.
```javascript
class ProceduralDataProvider extends DataProviderBase {
// ...
getCluster(url) {
return Promise.resolve({points: {}, reference: REFERENCE});
}
}
```
--------------------------------
### Initialize Mapillary JS Viewer and Data Provider
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/debug/chunk.html
Sets up the viewer and a ChunkDataProvider with S2 geometry. This is the initial setup required before interacting with chunks.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { CameraControls, Viewer, S2GeometryProvider, } from "/dist/mapillary.module.js";
import { ChunkDataProvider } from "/doc-src/src/js/utils/ChunkDataProvider.js";
import { CAMERA_TYPE_SPHERICAL, cameraTypeToAspect, generateCluster, } from "/doc-src/src/js/utils/provider.js";
let viewer;
let dataProvider;
let chunks;
let chunkCounter = 0;
const INTERVALS = 1;
const REFERENCE = { alt: 0, lat: 0, lng: 0 };
(function main() {
const container = document.createElement("div");
container.className = "viewer";
document.body.append(container);
dataProvider = new ChunkDataProvider({
geometry: new S2GeometryProvider(18),
});
const options = {
dataProvider,
cameraControls: CameraControls.Earth,
component: {
cache: false,
cover: false,
image: false,
spatial: {
cameraSize: 0.3,
cellGridDepth: 2,
cellsVisible: true,
},
},
container,
imageTiling: false,
};
viewer = new Viewer(options);
viewer.setFilter(['!=', 'cameraType', 'invalid'])
chunks = [];
listen();
})();
```
--------------------------------
### Install MapillaryJS with npm
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/intro/try.mdx
Use this command to add the MapillaryJS package to your project when using npm.
```zsh
npm install --save mapillary-js
```
--------------------------------
### Get Mesh Implementation
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/procedural-data-provider.md
Returns empty meshes as no triangles are generated for this example. The returned object should contain 'faces' and 'vertices' arrays.
```javascript
class ProceduralDataProvider extends DataProviderBase {
// ...
getMesh(url) {
return Promise.resolve({faces: [], vertices: []});
}
}
```
--------------------------------
### Initialize and Move to Image
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/debug/index.html
Basic setup for initializing the MapillaryJS viewer and loading a specific image. Ensure the viewer container is present in the DOM and an access token is provided.
```javascript
import { isFallbackSupported, isSupported, CameraControls, RenderMode, Viewer, } from "/dist/mapillary.module.js";
import { accessToken } from "/doc-src/.access-token/token.js";
(function main() {
checkSupport();
const imageId = "303729947926829";
const container = document.createElement("div");
container.className = "viewer";
document.body.append(container);
const viewer = new Viewer({
accessToken,
cameraControls: CameraControls.Gravity,
component: { cover: false },
container,
renderMode: RenderMode.Letterbox,
});
viewer.moveTo(imageId).catch((error) => console.warn(error));
viewer.on("load", (event) => console.log(event.type));
addButtons(viewer);
})();
function checkSupport() {
const sup = `isSupported: ${isSupported()}`;
const fSup = `isFallbackSupported: ${isFallbackSupported()}`;
console.log(`${sup}, ${fSup}`);
}
```
--------------------------------
### Install MapillaryJS with Yarn
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/intro/try.mdx
Use this command to add the MapillaryJS package to your project when using Yarn.
```zsh
yarn add mapillary-js
```
--------------------------------
### Initialize Viewer with Options
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/viewer-options.html
Basic initialization of the Mapillary viewer. Ensure you have a container element and a valid access token. This setup is common for embedding the viewer on a webpage.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/viewer-options.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
container
});
```
--------------------------------
### Initialize Viewer with Procedural Data Provider
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/debug/reset.html
Sets up the Mapillary JS viewer with a dynamic procedural data provider. This is the initial setup for the viewer and data provider.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { CameraControls, Viewer, S2GeometryProvider, } from "/dist/mapillary.module.js";
import { DynamicProceduralDataProvider } from "/doc-src/src/js/utils/DynamicProceduralDataProvider.js";
let viewer;
let dataProvider;
let intervals = 2;
const REFERENCE_DELTA = 1e-5;
const reference = { lng: 0, lat: 0, alt: 0 };
(function main() {
const container = document.createElement("div");
container.className = "viewer";
document.body.append(container);
dataProvider = new DynamicProceduralDataProvider({
geometry: new S2GeometryProvider(16),
reference,
intervals,
});
const options = {
dataProvider,
cameraControls: CameraControls.Earth,
component: {
cover: false,
spatial: {
cameraSize: 0.3,
cellGridDepth: 2,
cellsVisible: true,
},
},
container,
imageTiling: false,
};
viewer = new Viewer(options);
viewer.on("image", (event) => console.log("image", event.image ? event.image.id : null));
viewer.on("reference", (event) => console.log("reference", event));
viewer.on("reset", (event) => console.log("reset", event));
viewer
.moveTo(dataProvider.images.keys().next().value)
.catch((error) => console.error(error));
listen();
})();
function increment() {
reference.lng += REFERENCE_DELTA;
reference.lat += REFERENCE_DELTA;
reference.alt += REFERENCE_DELTA;
intervals++;
}
function listen() {
window.document.addEventListener("keydown", async (e) => {
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
return;
}
try {
switch (e.key) {
case "q": {
// Clear data provider and reset viewer
dataProvider.clear();
await viewer.reset();
break;
}
case "w": {
// Clear data provider, reset viewer, repopulate
// and move to new image
increment();
dataProvider.clear();
await viewer.reset();
dataProvider.populate({ reference, intervals });
await viewer.moveTo(
dataProvider.images.keys().next().value
);
break;
}
case "e": {
// Reset viewer and move to other image
const image = await viewer.getImage();
const imageId = image.id;
await viewer.reset();
const newId = [
...dataProvider.images.keys(),
].find((id) => id !== imageId);
if (newId) {
await viewer.moveTo(newId);
}
break;
}
case "r": {
// Reset viewer and move to same image
const image = await viewer.getImage();
const imageId = image.id;
await viewer.reset();
await viewer.moveTo(imageId);
break;
}
case "t": {
// Set a new data provider
increment();
dataProvider = new DynamicProceduralDataProvider({
reference,
intervals,
idCounter: dataProvider.idCounter,
});
await viewer.setDataProvider(dataProvider);
await viewer.moveTo(
dataProvider.images.keys().next().value
);
break;
}
case "y": {
// Set a filter after reset
const image = await viewer.getImage();
const imageId = image.id;
await viewer.reset();
await viewer.setFilter([]);
await viewer.moveTo(imageId);
break;
}
case "u": {
// Set a filter after reset and move
const image = await viewer.getImage();
const imageId = image.id;
await viewer.reset();
await viewer.moveTo(imageId);
await viewer.setFilter([]);
break;
}
case "i": {
// Append and move to reset
reference.lng += 2.4e-3;
reference.lat += 5e-5;
const imageIds = dataProvider.append({
reference,
intervals,
});
await viewer.moveTo(imageIds[0]);
break;
}
default:
break;
}
} catch (error) {
console.log(error);
}
});
}
```
--------------------------------
### Initialize Viewer with Markers
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/debug/marker.html
Initializes the MapillaryJS viewer with the marker component enabled. This setup is required before adding any markers.
```javascript
import { SimpleMarker, Viewer } from "/dist/mapillary.module.js";
import { accessToken } from "/doc-src/.access-token/token.js";
const imageId = "147617667372938";
const mly = new Viewer({
accessToken,
component: {
cover: false,
marker: true
},
container: "mly"
});
```
--------------------------------
### Initialize Component Pointer Example
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/component-pointer.html
Initializes the Mapillary JS viewer with the Component Pointer functionality. Ensure you have a valid access token and a container element.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/component-pointer.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
container,
});
```
--------------------------------
### Example URLEnt for Thumbnails
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/procedural-data-provider.md
This snippet shows the structure of a URLEnt object used for requesting thumbnail data. The provider should use the provided ID and URL to fetch the thumbnail.
```javascript
const thumb = {id: ''};
```
--------------------------------
### Initialize Mapillary JS with Custom Renderer
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/extend-webgl-renderer.html
This snippet shows the basic setup for initializing Mapillary JS, including setting the access token and providing a container element. It imports the necessary functions and token.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/extend-webgl-renderer.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
container
});
```
--------------------------------
### Initialize Viewer with Options
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/main/init.md
This example demonstrates how to initialize the Mapillary JS Viewer with a comprehensive set of options. It configures camera controls, disables combined panning and image tiling, sets render and transition modes, and disables resize tracking, while also specifying a cover component.
```jsx
function render(props) {
let viewer;
function dispose() {
if (viewer) {
viewer.remove();
}
}
const style = {height: '400px'};
const imageId = '178975760792906';
function init(opts) {
const {accessToken, container} = opts;
const viewerOptions = {
accessToken,
cameraControls: CameraControls.Street,
combinedPanning: false,
component: {cover: false},
container,
imageId,
imageTiling: false,
renderMode: RenderMode.Letterbox,
trackResize: false,
transitionMode: TransitionMode.Instantaneous,
};
viewer = new Viewer(viewerOptions);
}
return ;
}
```
--------------------------------
### Initialize Mapillary JS with Extended Renderer
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/extend-three-renderer.html
This snippet shows the basic setup for initializing Mapillary JS, passing an access token and a container element. It assumes the necessary imports are handled.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/extend-three-renderer.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
container
});
```
--------------------------------
### Initialize Viewer with Filters
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/viewer-filters.html
Initializes the Mapillary JS viewer with an access token and a container element. This setup is required before applying any viewer filters.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/viewer-filters.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({ accessToken, container });
```
--------------------------------
### Initialize Component Tag Example
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/component-tag.html
Initializes the Mapillary JS viewer within a specified container element. Requires an access token and a DOM element for rendering.
```javascript
body { margin: 0; padding: 0; }
html, body, .viewer { width: 100%; height: 100%; }
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/component-tag.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({ accessToken, container });
```
--------------------------------
### Initialize Map Sync with Custom Container
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/extend-map-sync.html
This snippet shows the basic setup for initializing Mapillary JS map synchronization. It requires an access token and a container element.
```javascript
import { accessToken, mapboxAccessToken, } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/extend-map-sync.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
mapboxAccessToken,
container,
});
```
--------------------------------
### Initialize Mapillary JS with a Custom Data Provider
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/extend-procedural-data-provider.html
This snippet shows the basic setup for initializing Mapillary JS, including importing the necessary function and creating a container element. It assumes the 'init' function is imported from a local JavaScript file.
```javascript
import { init } from "/doc-src/src/js/examples/extend-procedural-data-provider.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
container
});
```
--------------------------------
### Initialize MapillaryJS Viewer (UMD)
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/debug/umd.html
This snippet shows how to import the Viewer from the UMD build and initialize it with an access token, container, and an initial image ID. Ensure the 'accessToken' variable is defined and the MapillaryJS library is loaded.
```html
body {
margin: 0;
padding: 0;
}
html, body, .viewer {
width: 100%;
height: 100%;
}
const { Viewer } = mapillary;
const container = document.createElement("div");
container.classList.add("viewer");
document.body.append(container);
const viewer = new Viewer({
accessToken,
component: {
cover: false
},
container,
imageId: "780299919518360",
});
```
--------------------------------
### Initialize Viewer with Options Object (v3.x)
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/migration/v3.md
In v3.x, all viewer constructor parameters are passed within an options object. This includes API client, container, and optional image key or user token.
```javascript
var mly = new Mapillary.Viewer({
apiClient: '',
container: '',
imageKey: '',
userToken: '',
// your other viewer options
});
```
--------------------------------
### Create and Add Markers in Batches
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/debug/marker.html
Demonstrates creating a large number of markers in batches and adding them to the viewer. Includes performance timing for creation and addition operations.
```javascript
const createTimes = [];
const addTimes = [];
const batchSize = 1000;
let markerCount = 0;
const markerComponent = mly.getComponent("marker");
// Log performance results
const logTimes = function () {
const totalCreateTime = createTimes.reduce(function (acc, val) {
return acc + val;
}, 0);
const totalAddTime = addTimes.reduce(function (acc, val) {
return acc + val;
}, 0);
console.log("Markers added:", markerCount);
console.log("Batch size:", batchSize);
console.log("Total create time:", totalCreateTime.toFixed(2));
console.log(
"Average batch create time:",
(totalCreateTime / createTimes.length).toFixed(2)
);
console.log(
"Average marker create time:",
(totalCreateTime / createTimes.length / batchSize).toFixed(4)
);
console.log("Total add time:", totalAddTime.toFixed(2));
console.log(
"Average batch add time:",
(totalAddTime / addTimes.length).toFixed(2)
);
console.log("Average marker add time:", (totalAddTime / addTimes.length / batchSize).toFixed(4));
};
// Create markers in a bounding box with center at lngLat
const createRandomMarkers = function (start, count, lngLat) {
const getRandomUniform = function (min, max) {
return Math.random() * (max - min) + min;
};
const t0 = window.performance.now();
const boxWidth = 0.1;
const minLat = lngLat.lat - boxWidth / 2;
const maxLat = lngLat.lat + boxWidth / 2;
const minLng = lngLat.lng - boxWidth / 2;
const maxLng = lngLat.lng + boxWidth / 2;
const markers = [];
for (let i = start; i < start + count; i++) {
const lat = getRandomUniform(minLat, maxLat);
const lng = getRandomUniform(minLng, maxLng);
const marker = new SimpleMarker(
i.toString(),
{ lat: lat, lng: lng },
{ interactive: true }
);
markers.push(marker);
}
createTimes.push(window.performance.now() - t0);
return markers;
};
// Add markers to component in batch
const addMarkers = function (markers) {
const t0 = window.performance.now();
markerComponent.add(markers);
addTimes.push(window.performance.now() - t0);
};
// Start creating and adding markers when image has been set
mly.moveTo(imageId).then(
function (n) {
let intervalId = window.setInterval(function () {
const markers = createRandomMarkers(
markerCount,
batchSize,
n.lngLat
);
addMarkers(markers);
markerCount += batchSize;
if (markerCount >= 1e6) {
window.clearInterval(intervalId);
logTimes();
}
}, 5);
},
function (e) {
console.error(e);
}
);
```
--------------------------------
### Deploy MapillaryJS Documentation
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/README.md
Use this command to deploy the MapillaryJS documentation. Ensure you have set your GitHub username.
```bash
GIT_USER= yarn deploy
```
--------------------------------
### Get Image Buffer Implementation
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/procedural-data-provider.md
Generates the image buffer on the fly. This method is called when an image buffer is requested.
```javascript
class ProceduralDataProvider extends DataProviderBase {
// ...
getImageBuffer(url) {
return generateImageBuffer();
}
}
```
--------------------------------
### Initialize Custom Renderer Resources
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/three-custom-renderer.md
Sets up the Three.js renderer, camera, and scene, and adds the cube mesh. Disables autoClear for the renderer and matrixAutoUpdate for the camera.
```javascript
class ThreeCubeRenderer {
// ...
onAdd(viewer, reference, context) {
const position = geoToPosition(this.cube.geoPosition, reference);
this.cube.mesh.position.fromArray(position);
const canvas = viewer.getCanvas();
this.renderer = new WebGLRenderer({
canvas,
context,
});
this.renderer.autoClear = false;
this.camera = new Camera();
this.camera.matrixAutoUpdate = false;
this.scene = new Scene();
this.scene.add(this.cube.mesh);
}
}
```
--------------------------------
### Initialize Viewer with Default Shader
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/debug/shader.html
Sets up the MapillaryJS viewer with default settings and moves to a specific image.
```javascript
import { CameraControls, Shader, ShaderChunk, Viewer, } from "/dist/mapillary.module.js";
import { accessToken } from "/doc-src/.access-token/token.js";
(function main() {
const imageId = "303729947926829";
const container = document.createElement("div");
container.className = "viewer";
document.body.append(container);
const viewer = new Viewer({
accessToken,
cameraControls: CameraControls.Street,
component: { cover: false },
container,
});
viewer.moveTo(imageId).catch((error) => console.warn(error));
addButtons(viewer);
})();
function addButton(content, handler) {
const button = document.createElement("button");
button.textContent = content;
button.addEventListener("click", handler);
document.body.append(button);
}
function addButtons(viewer) {
addButton("Texture", () => viewer.setShader(Shader.texture));
addButton("Terrain", () => viewer.setShader(makeTerrain()));
addButton("Magnesis", () => viewer.setShader(makeMagnesis()));
addButton("Depth-Blend", () => viewer.setShader(makeDepth(0.65)) );
addButton("Depth", () => viewer.setShader(makeDepth(1.0)));
addButton("Earth", () => viewer.setCameraControls(CameraControls.Earth) );
addButton("Street", () => viewer.setCameraControls(CameraControls.Street) );
}
```
--------------------------------
### Get Spatial Images Implementation
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/procedural-data-provider.md
Reuses the 'getImages' method to retrieve spatial image data. This method is an alias for 'getImages' in this implementation.
```javascript
class ProceduralDataProvider extends DataProviderBase {
// ...
getSpatialImages(imageIds) {
return this.getImages(imageIds);
}
}
```
--------------------------------
### Initialize Component Marker
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/component-marker.html
Initializes the Mapillary JS viewer with a component marker. Ensure you have the access token and the component-marker example script imported.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/component-marker.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({ accessToken, container });
```
--------------------------------
### Initialize Viewer From Map
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/viewer-from-map.html
Import necessary modules and initialize the Mapillary viewer with access tokens and a container element. Ensure you have your Mapillary and Mapbox access tokens configured.
```javascript
import { accessToken, mapboxAccessToken, } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/viewer-from-map.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
mapboxAccessToken,
container,
});
```
--------------------------------
### Initialize Leaflet Map and MapillaryJS Viewer
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/debug/leaflet.html
Sets up the Leaflet map and the MapillaryJS viewer. Ensure the HTML has containers with IDs 'map' and 'mly'.
```javascript
import { CircleMarker, SimpleMarker, Viewer, } from "/dist/mapillary.module.js";
import { accessToken } from "/doc-src/.access-token/token.js";
const imageId = "147617667372938";
// Setup map
const map = L.map("map").setView( [56.04351888068181, 12.695600612967427],
18 );
const osmUrl = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
const osmAttrib = 'Map data © OpenStreetMap contributors';
const osm = new L.TileLayer(osmUrl, { maxZoom: 19, attribution: osmAttrib, });
map.addLayer(osm);
map.keyboard.disable();
// Setup viewer
const mly = new Viewer({
accessToken,
component: {
marker: {
visibleBBoxSize: 100
},
},
container: "mly",
});
mly.moveTo(imageId).then( () => { /* noop */ }, (error) => {
console.error(error);
}
);
```
--------------------------------
### Initialize Shader Program
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/webgl-custom-renderer.md
Compiles vertex and fragment shaders and links them into a shader program. This is a standard procedure for setting up WebGL 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};
}
```
--------------------------------
### Listen to Image Events
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/main/event.md
Listen to the 'image' event to get information about the current image. This is useful for updating UI elements based on the displayed image.
```jsx
function render(props) {
let viewer;
const style = {height: '400px'};
const imageId = '177438650974210';
function dispose() {
if (viewer) {
viewer.remove();
}
}
function init(options) {
viewer = new Viewer(options);
viewer.moveTo(imageId).catch(mapillaryErrorHandler);
function createThumb(container) {
const img = document.createElement('img');
img.style.position = 'absolute';
img.style.right = '0';
img.style.width = '200px';
img.style.border = '1px solid #888';
container.appendChild(img);
return img;
}
const thumb = createThumb(options.container);
const onImage = (event) => {
const image = event.image;
thumb.src = image.image.src;
};
viewer.on('image', onImage);
}
return ;
}
```
--------------------------------
### Initialize Fly Controls on Activation
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/fly-controls.md
Implement the `onActivate` method to initialize resources, set up the camera, create fly controls, and establish event listeners for camera changes. This method is called when the custom controls are activated.
```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());
}
}
```
--------------------------------
### Get Image Tiles Implementation (Not Implemented)
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/procedural-data-provider.md
Rejects the request with a 'Not implemented' error. This functionality is deactivated via a viewer option, so the method can be omitted.
```javascript
class ProceduralDataProvider extends DataProviderBase {
// ...
getImageTiles(tiles) {
return Promise.reject(new MapillaryError('Not implemented'));
}
}
```
--------------------------------
### Initialize Viewer with Separate Parameters (v2.x)
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/migration/v3.md
In v2.x, viewer constructor parameters were passed as separate arguments, with options and auth token at the end. This format is deprecated in v3.x.
```javascript
var mly = new Mapillary.Viewer(
'',
'',
'',
{
// your other viewer options
},
'',
);
```
--------------------------------
### Listen to Viewer Position Change Event
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/main/event.md
Register an event handler for the 'position' event to get the viewer's current geographical coordinates when the position changes.
```js
const viewer = new Viewer({accessToken, container});
viewer.on('position', async (event) => {
const position = await viewer.getPosition();
const lng = position.lngLat.lng;
const lat = position.lngLat.lat;
console.log(`id: ${imageId}', lng: ${lng}, lat: ${lat}`);
});
```
--------------------------------
### Get Sequence Implementation
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/procedural-data-provider.md
Returns a generated sequence if it exists for the given sequence ID. Rejects with an error if the sequence is not found. Uses a Promise for asynchronous resolution.
```javascript
class ProceduralDataProvider extends DataProviderBase {
// ...
getSequence(sequenceId) {
return new Promise((resolve, reject) => {
if (this.sequences.has(sequenceId)) {
resolve(this.sequences.get(sequenceId));
} else {
reject(new Error(`Sequence ${sequenceId} does not exist`));
}
});
}
}
```
--------------------------------
### Initialize Viewer with Procedural Data Provider
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/procedural-data-provider.md
Attaches a custom procedural data provider to the Viewer and moves to an initial image ID. Requires the ViewerComponent and necessary imports.
```jsx
function render(props) {
let viewer;
function init(opts) {
const {container} = opts;
const imageId = 'image|fisheye|0';
const dataProvider = new procedural.ProceduralDataProvider({});
const options = {
dataProvider,
cameraControls: CameraControls.Earth,
component: {
cover: false,
spatial: {cameraSize: 0.5, cellGridDepth: 3, cellsVisible: true},
},
container,
imageTiling: false,
};
viewer = new Viewer(options);
viewer.moveTo(imageId).catch(mapillaryErrorHandler);
}
function dispose() {
if (viewer) {
viewer.remove();
}
}
return (
);
}
```
--------------------------------
### Filter Street Imagery
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/main/control.md
Apply a global filter to specify which images are navigable. This example filters for 'fisheye' camera types. The filter can be cleared by setting it to an empty array.
```jsx
function render(props) {
let viewer;
function dispose() {
if (viewer) {
viewer.remove();
}
}
const style = {height: '400px'};
const imageId = '821390568809272';
function init(opts) {
const {accessToken, container} = opts;
const options = {accessToken, container};
viewer = new Viewer(options);
viewer.moveTo(imageId).catch(mapillaryErrorHandler);
viewer.setFilter(['==', 'cameraType', 'fisheye']);
}
return (
);
}
```
--------------------------------
### Initialize Mapillary JS with Extended Fly Controls
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/extend-fly-controls.html
Sets up the Mapillary JS viewer with custom fly controls. Ensure you have a valid access token and a container element.
```javascript
body { margin: 0; padding: 0; } html, body, .viewer { width: 100%; height: 100%; }
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/extend-fly-controls.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
container,
});
```
--------------------------------
### Configure Viewer with Falcor Data Provider (v3.x)
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/migration/v3.md
In v3.x, URL options are primarily set via the Falcor data provider. Client and user tokens must also be set on the provider when it's explicitly configured.
```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: '',
},
});
```
--------------------------------
### Handle Pointer Events
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/main/event.md
Listen to pointer events like 'dblclick' and 'mousemove' to get coordinate information. The event object provides pixel, basic, and lngLat coordinates.
```javascript
const viewer = new Viewer({accessToken, container});
const onPointerEvent = (event) => {
const lng = event.lngLat ? event.lngLat.lng : null;
const lat = event.lngLat ? event.lngLat.lat : null;
console.log(`'${event.type}' - lng: ${lng}, lat: ${lat}`);
};
viewer.on('dblclick', onPointerEvent);
viewer.on('mousemove', onPointerEvent);
```
--------------------------------
### Configure Pointer Component
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/main/component.md
Demonstrates how to retrieve the 'pointer' component and configure its properties like drag pan and zoom behavior after viewer initialization. Use this to customize user interaction with the map.
```jsx
function render(props) {
let viewer;
function dispose() {
if (viewer) {
viewer.remove();
}
}
const style = {height: '400px'};
const imageId = '4165984473444513';
function init(opts) {
const {accessToken, container} = opts;
const viewerOptions = {
accessToken,
container,
};
viewer = new Viewer(viewerOptions);
viewer.moveTo(imageId).catch(mapillaryErrorHandler);
const pointerComponent = viewer.getComponent('pointer');
pointerComponent.configure({
dragPan: true,
scrollZoom: false,
touchZoom: false,
});
}
return ;
}
```
--------------------------------
### Handle Marker Drag Events
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/debug/leaflet.html
Manages the drag start and end events for markers in the viewer. It removes indicators during dragging and updates marker positions after the drag ends.
```javascript
markerComponent.on("markerdragstart", () => {
// Remove indicators when dragging marker in the viewer
indicator.state.dragging = true;
removeViewerIndicator();
removeMapIndicator();
});
markerComponent.on("markerdragend", () => {
indicator.state.dragging = false;
if (!indicator.state.lastPos) {
return;
}
// Unproject the last position and move indicator marker if lngLat exist
mly.unproject(indicator.state.lastPos).then(moveIndicatorMarker);
});
```
--------------------------------
### Initialize Viewer with Access Token
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/viewer-events.html
Initializes the Mapillary viewer with a provided access token and container element. Ensure the access token is correctly configured.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/viewer-events.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
container
});
```
--------------------------------
### Initialize Viewer and Map Integration
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/viewer-to-map.html
This snippet shows the necessary imports and initialization code to set up the Mapillary JS viewer and link it to a map. Ensure you have your access tokens configured.
```javascript
import { accessToken, mapboxAccessToken, } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/viewer-to-map.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
mapboxAccessToken,
container
});
```
--------------------------------
### Initialize Mapillary JS Component Tag
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/component-tag-create.html
This snippet shows the basic setup for initializing the Mapillary JS viewer with a component tag. Ensure you have the access token and container element ready.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/component-tag-create.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
container
});
```
--------------------------------
### Configure Viewer with URL Options (v2.x)
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/migration/v3.md
In v2.x, URL options were directly passed as part of the viewer's options object. This approach is different in v3.x where Falcor is used.
```javascript
var mly = new Mapillary.Viewer(
'',
'',
'',
{
url: {
apiHost: '',
clusterReconstructionHost: '',
exploreHost: '',
imageHost: '',
imageTileHost: '',
meshHost: '',
scheme: '',
},
},
'',
);
```
--------------------------------
### Get Core Images Implementation
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/extension/procedural-data-provider.md
Retrieves images associated with a given cell ID. Returns an empty array if the cell ID is not found. This method is recommended for bandwidth efficiency in production.
```javascript
class ProceduralDataProvider extends DataProviderBase {
// ...
getCoreImages(cellId) {
const images = this.cells.has(cellId) ? this.cells.get(cellId) : [];
return Promise.resolve({cell_id: cellId, images});
}
}
```
--------------------------------
### Initialize Component Popup
Source: https://github.com/mapillary/mapillary-js/blob/main/examples/doc/component-popup.html
Set up the Mapillary JS viewer and initialize the component popup. Ensure you have a valid access token and a container element.
```javascript
import { accessToken } from "/doc-src/.access-token/token.js";
import { init } from "/doc-src/src/js/examples/component-popup.js";
const container = document.createElement("div");
container.className = "viewer";
document.body.appendChild(container);
init({
accessToken,
container
});
```
--------------------------------
### Display Coordinates on Click
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/main/event.md
Use the 'click' event to capture pixel coordinates and display basic image coordinates. This example shows how to position an element and update its text content based on click events.
```jsx
function render(props) {
let viewer;
const style = {height: '400px'};
const imageId = '3044480469113592';
function dispose() {
if (viewer) {
viewer.remove();
}
}
function createCoordinates(container) {
const div = document.createElement('div');
div.style.position = 'absolute';
div.style.padding = '4px';
div.style.border = '1px solid #888';
div.style.background = 'rgb(4, 203, 98)';
div.textContent = 'Click in viewer';
container.appendChild(div);
return div;
}
function init(options) {
viewer = new Viewer(options);
viewer.moveTo(imageId).catch(mapillaryErrorHandler);
const coordinates = createCoordinates(options.container);
const onClick = (event) => {
const [pixelX, pixelY] = event.pixelPoint;
coordinates.style.left = `${pixelX}px`;
coordinates.style.top = `${pixelY}px`;
if (event.basicPoint) {
const [basicX, basicY] = event.basicPoint;
const x = basicX.toFixed(3);
const y = basicY.toFixed(3);
coordinates.textContent = `[${x}, ${y}]`;
} else {
coordinates.textContent = 'Clicked outside image';
}
};
viewer.on('click', onClick);
}
return ;
}
```
--------------------------------
### Initialize MapillaryJS Viewer with CDN
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/intro/try.mdx
Initialize the MapillaryJS viewer using the global `mapillary` object after including the CDN files. The container ID and access token are required.
```html
```
--------------------------------
### Activate and Deactivate Bearing Component
Source: https://github.com/mapillary/mapillary-js/blob/main/doc/docs/main/component.md
This example demonstrates how to activate and deactivate the 'bearing' component using checkboxes. It shows how to create custom UI elements to control component visibility and behavior within the viewer.
```jsx
function render(props) {
let viewer;
function dispose() {
if (viewer) {
viewer.remove();
}
}
const style = {height: '400px'};
const imageId = '340458257702273';
// Create bearing checkbox
const checkbox = document.createElement('input');
checkbox.setAttribute('type', 'checkbox');
checkbox.style.pointerEvents = 'none';
checkbox.checked = true;
const space = document.createElement('div');
space.classList.add('button-space');
space.appendChild(checkbox);
const toolbar = document.createElement('div');
toolbar.classList.add('example-editor-toolbar');
toolbar.style.zIndex = 100;
toolbar.style.top = '16px';
toolbar.style.left = '16px';
toolbar.appendChild(space);
// Listen to bearing checkbox clicks
space.addEventListener('click', () => {
checkbox.dispatchEvent(new MouseEvent('click', {bubbles: false}));
});
checkbox.addEventListener('change', (event) => {
if (event.target.checked) {
viewer.activateComponent('bearing');
} else {
viewer.deactivateComponent('bearing');
}
});
function init(opts) {
const {accessToken, container} = opts;
const viewerOptions = {accessToken, container};
viewer = new Viewer(viewerOptions);
viewer.moveTo(imageId).catch(mapillaryErrorHandler);
container.appendChild(toolbar);
}
return ;
}
```