### Hello World Example
Source: https://github.com/ar-js-org/locar.js/blob/master/examples/README.md
A basic example displaying a red box at a specified fake GPS location. Suitable for desktop testing as it defaults to facing North.
```html
```
--------------------------------
### Running Vite Dev Server
Source: https://github.com/ar-js-org/locar.js/blob/master/examples/README.md
Use this command to start the Vite development server for testing locar.js examples locally. Ensure locar.js is added to the URL.
```bash
npm run dev
```
--------------------------------
### Building locar.js Examples with Vite
Source: https://github.com/ar-js-org/locar.js/blob/master/examples/README.md
This command builds the locar.js examples for deployment, typically configured for GitHub Pages. Adjust the Vite configuration for local builds if needed.
```bash
npm run build
```
--------------------------------
### Install LocAR.js
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/index.html
Install the LocAR.js library using npm. Ensure 'three.js' is also included as a dependency.
```bash
npm install locar
```
--------------------------------
### Start LocAR.js Application
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/tutorial/part1.md
Initializes the LocAR.js application by calling the start() method. This returns a promise that resolves when the device sensors are ready and permissions are granted, providing a LocAR object.
```typescript
const locar = await app.start();
```
--------------------------------
### start
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/App.html
Initializes and starts the AR application. This method must be called after the App object has been constructed and should be used to begin the AR session, returning a promise that resolves with the LocAR object.
```APIDOC
## start
### Description
Initializes and starts the AR application. This method must be called after the App object has been constructed and should be used to begin the AR session, returning a promise that resolves with the LocAR object.
### Method Signature
`start(): Promise[]`
### Returns
`Promise[]` - A promise that resolves with the LocAR object upon successful initialization. It rejects with an object containing a code and message if the startup fails.
```
--------------------------------
### startGps
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Starts the GPS on a real device. Returns a promise indicating success or failure.
```APIDOC
## startGps
### Description
Start the GPS on a real device.
### Method
(Implicitly a method of the LocAR class)
### Returns
Promise - A promise that resolves with a boolean indicating whether the GPS was started successfully. GPS errors can be handled by listening for the 'gpserror' event.
### Source
lib/three/locar.ts:87
```
--------------------------------
### Install LocAR.js and Vite Dependencies
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/tutorial/index.md
This package.json configuration includes LocAR.js as a dependency and Vite as a development dependency for building and serving the application.
```json
{
"dependencies": {
"locar": "^0.2.0"
},
"devDependencies": {
"vite": "^7.3.2"
},
"scripts": {
"dev": "vite dev",
"build": "vite build"
}
}
```
--------------------------------
### LocAR.js package.json dependencies
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/index.html
Example of how to specify LocAR.js and three.js as dependencies in your project's package.json file.
```json
"dependencies": {
"locar" : "^0.2.3",
"three" : "^0.175.0"
}
```
--------------------------------
### Initialize LocAR and Listen for GPS Updates
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/tutorial/part2.md
Initializes the LocAR app, starts GPS tracking, and adds four colored boxes to the scene upon receiving the first GPS update. Handles GPS errors.
```typescript
import * as THREE from 'three';
import {
App, GpsReceivedEvent
} from 'locar';
const app = new App({
cameraOptions: { hFov: 80, near: 0.001, far: 1000 }
});
try {
let firstLocation = true;
const locar = await app.start();
locar.on("gpserror", (error : GeolocationPositionError) => {
alert(`GPS error: ${error.code}`);
});
locar.on("gpsupdate", (ev: GpsReceivedEvent) => {
if(firstLocation) {
alert(`Got the initial location: longitude ${ev.position.coords.longitude}, latitude ${ev.position.coords.latitude}`);
const boxProps = [{
latDis: 0.0005,
lonDis: 0,
colour: 0xff0000
}, {
latDis: -0.0005,
lonDis: 0,
colour: 0xffff00
}, {
latDis: 0,
lonDis: -0.0005,
colour: 0x00ffff
}, {
latDis: 0,
lonDis: 0.0005,
colour: 0x00ff00
}];
const geom = new THREE.BoxGeometry(10,10,10);
for(const boxProp of boxProps) {
const mesh = new THREE.Mesh(
geom,
new THREE.MeshBasicMaterial({color: boxProp.colour})
);
locar.add(
mesh,
ev.position.coords.longitude + boxProp.lonDis,
ev.position.coords.latitude + boxProp.latDis
);
}
firstLocation = false;
}
});
locar.startGps();
}
catch(e: any) {
alert(`${e.code} ${e.message}`);
}
```
--------------------------------
### WebcamStartedEvent Interface
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/WebcamStartedEvent.html
The WebcamStartedEvent interface is emitted when the webcam starts. It includes properties for the video height and width.
```APIDOC
## Interface WebcamStartedEvent
Event emitted when the webcam starts.
### Properties
* **videoHeight** (number) - The height of the video stream.
* **videoWidth** (number) - The width of the video stream.
```
--------------------------------
### HTML Structure for LocAR.js App
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/tutorial/part1.md
Basic HTML setup for a LocAR.js application, including viewport meta tag and full-screen styling. Ensure the script tag points to your main application file.
```html
LocAR.js example 1
```
--------------------------------
### Start GPS Tracking with LocAR
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/tutorial/part2.md
Initiates the device's GPS to start listening for location updates. LocAR automatically updates the camera's position based on GPS data.
```javascript
arjs.startGps();
```
--------------------------------
### App Constructor
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/App.html
Initializes a new App object with specified startup options.
```APIDOC
## constructor
### Description
Create an App object.
### Parameters
#### Path Parameters
* **-** (*AppOptions*) - Required - Startup options.
### Returns App
Overrides [EventEmitter](EventEmitter.html).[constructor](EventEmitter.html#constructor)
```
--------------------------------
### Webcam Constructor
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/Webcam.html
Initializes a new Webcam instance. It can accept constraints for camera initialization and an optional selector for an existing video element.
```APIDOC
## constructor Webcam
### Description
Create a Webcam.
### Parameters
* **constraints** {Object} - options to use for initialising the camera. This is the same constraints object as used by standard MediaDevices API.
* **video.facingMode** string
* **videoElementSelector** string - Optional selector to obtain the HTML video element to render the webcam feed. If a falsy value (e.g. null or undefined), a video element will be created.
### Returns Webcam
```
--------------------------------
### init()
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Initializes the device orientation controls. It's recommended to call this after setting up event handlers for deviceorientationgranted and deviceorientationerror.
```APIDOC
## init()
### Description
Initialise device orientation controls. Should be called after you have created the DeviceOrientationControls object and set up the deviceorientationgranted and deviceorientationerror event handlers.
### Method
init
### Returns
void
```
--------------------------------
### Initialize LocAR.js App and Add a 3D Box
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/tutorial/part1.md
Sets up the LocAR.js application, initializes the camera with specified options, adds a red 3D box at a real-world location, and sets a fake GPS position. Includes basic error handling.
```typescript
import * as THREE from 'three';
import { App } from 'locar';
const app = new App({
cameraOptions: { hFov: 80, near: 0.001, far: 1000 }
});
try {
const locar = await app.start();
const geom = new THREE.BoxGeometry(10, 10, 10);
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const mesh = new THREE.Mesh(geom, material);
locar.add(mesh, -0.72, 51.0505);
locar.fakeGps(-0.72, 51.05);
} catch (e: any) {
alert(`Error: ${e.code} ${e.message}`);
}
```
--------------------------------
### Configure Camera Options with App Class
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/tutorial/part1.md
Instantiates the App class with custom camera parameters, including horizontal field of view, near, and far clipping planes. These options are used to create a THREE.PerspectiveCamera internally.
```typescript
const app = new App({
cameraOptions: { hFov: 80, near: 0.001, far: 1000 }
});
```
--------------------------------
### Methods
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
This section details the methods available in the DeviceOrientationControls class.
```APIDOC
## Methods
### getAlpha()
- **Description**: Returns the current alpha value from the device orientation.
- **Returns**: `number`
### getBeta()
- **Description**: Returns the current beta value from the device orientation.
- **Returns**: `number`
### getCorrectedHeading()
- **Description**: Returns the corrected heading based on device orientation.
- **Returns**: `number`
### getGamma()
- **Description**: Returns the current gamma value from the device orientation.
- **Returns**: `number`
### obtainPermissionGesture()
- **Description**: Initiates a gesture to obtain orientation permissions.
- **Returns**: `void`
### requestOrientationPermissions()
- **Description**: Requests permission for accessing device orientation.
- **Returns**: `void`
```
--------------------------------
### on
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/App.html
Adds an event handler to the App instance. This method allows users to subscribe to specific events emitted by the application and define custom logic to be executed when those events occur.
```APIDOC
## on
### Description
Adds an event handler to the App instance. This method allows users to subscribe to specific events emitted by the application and define custom logic to be executed when those events occur.
### Method Signature
`on(eventName: string, eventHandler: (...args: any[]) => void): void[]`
### Parameters
#### Parameters
- **eventName** (string) - The name of the event to handle.
- **eventHandler** ((...args: any[]) => void) - The function to be called when the event is triggered.
### Returns
`void[]`
### Inherited From
[EventEmitter](EventEmitter.html).[on](EventEmitter.html#on)
```
--------------------------------
### Webcam Methods
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/Webcam.html
Provides essential methods for interacting with the Webcam instance, including event management and retrieving video stream dimensions.
```APIDOC
## emit
### Description
Emit an event.
### Parameters
* **eventName** string - the event to emit.
* **...params** any[]
### Returns void
## getVideoDimensions
### Returns string
## off
### Description
Remove an event handler.
### Parameters
* **eventName** string - the event to remove a handler from.
* **eventHandler** function - the event handler function to remove.
### Returns void
## on
### Description
Add an event handler.
### Parameters
* **eventName** string - the event to handle.
* **eventHandler** function - the event handler function.
### Returns void
```
--------------------------------
### ClickHandler Constructor
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/ClickHandler.html
Initializes a new instance of the ClickHandler class. This constructor requires a WebGLRenderer to be provided.
```APIDOC
## constructor
### Description
Create a ClickHandler.
### Parameters
* **renderer** (WebGLRenderer) - The WebGLRenderer instance to use for handling clicks.
### Returns ClickHandler
A new instance of the ClickHandler.
```
--------------------------------
### on Method
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/EventEmitter.html
Adds an event handler for a specific event.
```APIDOC
## on(eventName: string, eventHandler: (...args: any[]) => void): void
### Description
Add an event handler.
### Parameters
* **eventName** (string) - The name of the event to handle.
* **eventHandler** ((...args: any[]) => void) - The event handler function.
### Returns
* void
```
--------------------------------
### App Methods
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/App.html
Provides methods for event emission and management.
```APIDOC
## emit
### Description
Emit an event.
### Parameters
#### Path Parameters
* **eventName** (string) - Required - the event to emit.
* **...params** (any[]) - Required
### Returns void
Inherited from [EventEmitter](EventEmitter.html).[emit](EventEmitter.html#emit)
```
```APIDOC
## off
### Description
Remove an event handler.
### Parameters
#### Path Parameters
* **eventName** (string) - Required - the event to remove a handler from.
* **eventHandler** ((...args: any[]) => void) - Required - the event handler function to remove.
### Returns void
Inherited from [EventEmitter](EventEmitter.html).[off](EventEmitter.html#off)
```
--------------------------------
### DeviceOrientationControls Methods
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Provides methods for managing event listeners and initializing the controls.
```APIDOC
## DeviceOrientationControls Methods
### Methods
* **addEventListener(type, listener)**
* Description: Adds an event listener.
* Parameters:
* `type` (string): The type of event to listen for.
* `listener` (Function): The callback function to execute.
* **dispatchEvent(event)**
* Description: Dispatches an event.
* Parameters:
* `event` (Object): The event object to dispatch.
* **hasEventListener(type, listener)**
* Description: Checks if an event listener is registered.
* Parameters:
* `type` (string): The type of event.
* `listener` (Function): The listener function to check.
* Returns: (boolean) - True if the listener is registered, false otherwise.
* **init()**
* Description: Initializes the controls. This method should be called after instantiation.
* **on(type, listener)**
* Description: Alias for `addEventListener`.
* Parameters:
* `type` (string): The type of event.
* `listener` (Function): The callback function.
* **removeEventListener(type, listener)**
* Description: Removes an event listener.
* Parameters:
* `type` (string): The type of event to remove.
* `listener` (Function): The listener function to remove.
```
--------------------------------
### AppOptions Interface
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/AppOptions.html
Interface defining the options that can be passed into the App object for configuring the AR experience.
```APIDOC
## Interface AppOptions
Options to pass into the App object.
```typescript
interface AppOptions {
cameraOptions?: { far: number; hFov: number; near: number };
canvas?: HTMLCanvasElement;
deviceOrientationOptions?: DeviceOrientationControlsOptions & {
enabled: boolean;
};
gpsOptions?: GpsOptions;
projection?: Projection;
serverLogger?: ServerLogger;
videoConstraints?: { video: { facingMode: string } };
}
```
### Properties
* **cameraOptions** (`{ far: number; hFov: number; near: number }` | `undefined`): Optional. The three.js camera options to use. Specifies horizontal field of view.
* **canvas** (`HTMLCanvasElement` | `undefined`): Optional. The canvas element to render the AR scene into. A canvas will be created if this is omitted.
* **deviceOrientationOptions** (`DeviceOrientationControlsOptions & { enabled: boolean; }` | `undefined`): Optional. Device orientation options for DeviceOrientationControls.
* **gpsOptions** (`GpsOptions` | `undefined`): Optional. GPS options. Refer to GpsOptions documentation for details.
* **projection** (`Projection` | `undefined`): Optional. The projection to use. Defaults to `SphMercProjection`.
* **serverLogger** (`ServerLogger` | `undefined`): Optional. Server logger to use. Ensure user consent is obtained as per data protection regulations.
* **videoConstraints** (`{ video: { facingMode: string } }` | `undefined`): Optional. Video constraints for the Media Devices API.
```
--------------------------------
### Properties
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
This section details the configurable properties of the DeviceOrientationControls.
```APIDOC
## Properties
### enableInlineStyling
- **Type**: boolean
- **Description**: Controls whether inline styles are enabled.
### enablePermissionDialog
- **Type**: boolean
- **Description**: Determines if a permission dialog should be shown.
### eventEmitter
- **Type**: EventEmitter
- **Description**: An event emitter instance for handling events.
### initialOffset
- **Type**: boolean | null
- **Description**: Sets an initial offset for the orientation.
### lastQuaternion
- **Type**: Quaternion | null
- **Description**: Stores the last quaternion value.
### object
- **Type**: Object3D
- **Description**: The Object3D to which the controls are applied.
### orientationChangeEventName
- **Type**: "deviceorientation" | "deviceorientationabsolute"
- **Description**: The name of the event to listen for device orientation changes.
### orientationChangeThreshold
- **Type**: number
- **Description**: The threshold for detecting orientation changes.
### orientationOffset
- **Type**: number
- **Description**: An offset value for the orientation.
### preferConfirmDialog
- **Type**: boolean
- **Description**: Indicates preference for a confirmation dialog.
### screenOrientation
- **Type**: number
- **Description**: Represents the current screen orientation.
### smoothingFactor
- **Type**: number
- **Description**: Factor used for smoothing orientation data.
```
--------------------------------
### LocAR Constructor
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Initializes a new LocAR instance. Requires a Three.js scene and camera. Optional parameters include GPS initialization options, a server logger for debugging, and a projection configuration.
```APIDOC
## new LocAR(scene: Scene, camera: Camera, options?: GpsOptions, serverLogger?: ServerLogger | null, projection?: Projection)
### Description
Initializes a new LocAR instance. Requires a Three.js scene and camera. Optional parameters include GPS initialization options, a server logger for debugging, and a projection configuration.
### Parameters
#### Parameters
- **scene** (Scene) - The Three.js scene to use.
- **camera** (Camera) - The Three.js camera to use. Should usually be a THREE.PerspectiveCamera.
- **options** (GpsOptions) - Optional. Initialisation options for the GPS; see setGpsOptions() below.
- **serverLogger** (ServerLogger | null) - Optional. An object which can optionally log GPS position to a server for debugging. null by default, so no logging will be done. This object should implement a sendData() method to send data (2nd arg) to a given endpoint (1st arg). Please see source code for details. Ensure you comply with privacy laws (GDPR or equivalent) if implementing this.
- **projection** (Projection) - Optional. Projection configuration.
```
--------------------------------
### SphMercProjection Constructor
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/SphMercProjection.html
Creates an instance of SphMercProjection.
```APIDOC
## constructor
### Description
Creates a SphMercProjection.
### Returns
* SphMercProjection
### Defined in
* lib/three/sphmerc-projection.ts:10
```
--------------------------------
### on(eventName, eventHandler)
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Attaches an event handler to a specific event name. This is a custom method for simplified event listening.
```APIDOC
## on(eventName, eventHandler)
### Description
Attaches an event handler to a specific event name.
### Method
on
### Parameters
#### Parameters
- **eventName** (string) - The name of the event to listen for.
- **eventHandler** ((event: any) => void) - The function to execute when the event is fired.
### Returns
void
```
--------------------------------
### emit Method
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/EventEmitter.html
Emits an event with the specified name and parameters.
```APIDOC
## emit(eventName: string, ...params: any[]): void
### Description
Emit an event.
### Parameters
* **eventName** (string) - The name of the event to emit.
* **...params** (any[]) - Additional parameters to pass to the event handlers.
### Returns
* void
```
--------------------------------
### emit
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Emits an event with optional parameters.
```APIDOC
## emit
### Description
Emits an event with the specified name and any number of parameters.
### Parameters
* **eventName** (string): The name of the event to emit.
* **...params** (any[]): Any additional parameters to pass with the event.
### Returns
* void
```
--------------------------------
### add
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Adds a new AR object to the scene at a specified geographic location (longitude, latitude, and optional elevation). Properties can be attached to the object for further description.
```APIDOC
## add(object: Object3D, lon: number, lat: number, elev?: number, properties?: Record)
### Description
Adds a new AR object to the scene at a specified geographic location (longitude, latitude, and optional elevation). Properties can be attached to the object for further description.
### Parameters
#### Parameters
- **object** (Object3D) - The object to add.
- **lon** (number) - The longitude.
- **lat** (number) - The latitude.
- **elev** (number) - Optional. The elevation in metres (if not specified, 0 is assigned).
- **properties** (Record) - Optional. Properties describing the object (for example, the contents of the GeoJSON properties field).
```
--------------------------------
### DeviceOrientationControls Constructor
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Initializes a new instance of the DeviceOrientationControls class. This constructor sets up the necessary properties and event listeners for tracking device orientation.
```APIDOC
## DeviceOrientationControls()
### Description
Initializes a new instance of the DeviceOrientationControls class.
### Constructor
`new DeviceOrientationControls(object, options)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Parameters
* **object** (Object) - The object to control with device orientation.
* **options** (Object) - Optional configuration options for the controls.
```
--------------------------------
### project Method
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/Projection.html
Projects geographic coordinates (longitude, latitude) to a 2D Cartesian coordinate system.
```APIDOC
project: (lon: number, lat: number) => [number, number]
```
--------------------------------
### Projection Interface
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/Projection.html
Defines the structure for custom map projection implementations. Requires `project` and `unproject` methods.
```APIDOC
interface Projection {
project(lon: number, lat: number): [number, number];
unproject(projected: [number, number]): [number, number];
}
```
--------------------------------
### setGpsOptions
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Sets the GPS options for the LocAR instance. Defaults to an empty object if no options are provided.
```APIDOC
## setGpsOptions
### Description
Set the GPS options.
### Method
(Implicitly a method of the LocAR class)
### Parameters
#### Parameters
- **options** (GpsOptions) - Optional - The GPS options to set. Defaults to {}.
### Returns
void
### Source
lib/three/locar.ts:73
```
--------------------------------
### Import LocAR.js in your project
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/index.html
Import the LocAR library into your JavaScript projects. This approach avoids issues with duplicate three.js imports.
```javascript
import * as LocAR from 'locar';
```
--------------------------------
### lonLatToWorldCoords
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Converts longitude and latitude to three.js/WebGL world coordinates.
```APIDOC
## lonLatToWorldCoords
### Description
Converts longitude and latitude to three.js/WebGL world coordinates using the specified projection. This method negates the northing component to align with the WebGL coordinate system. It should only be called after an initial position has been determined.
### Parameters
* **lon** (number): The longitude.
* **lat** (number): The latitude.
### Returns
* [number, number]: A two-element array containing the WebGL x and z coordinates.
```
--------------------------------
### EventEmitter Constructor
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/EventEmitter.html
Initializes a new instance of the EventEmitter class.
```APIDOC
## new EventEmitter()
### Description
Initializes a new instance of the EventEmitter class.
### Returns
* EventEmitter - A new instance of the EventEmitter.
```
--------------------------------
### update()
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Updates the device orientation controls. This method should be called in the animation loop to ensure controls are up-to-date.
```APIDOC
## update()
### Description
Updates the device orientation controls.
### Method
update
### Returns
void
```
--------------------------------
### DeviceOrientationControlsOptions
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/types/DeviceOrientationControlsOptions.html
Defines the configuration options for DeviceOrientationControls. These options allow customization of permission dialogs, styling, and sensor data processing for device orientation.
```APIDOC
## DeviceOrientationControlsOptions
### Description
Type alias for the options object used to configure `DeviceOrientationControls`. Allows customization of permission dialogs, styling, and sensor data processing.
### Properties
#### enablePermissionDialog
- **enablePermissionDialog** (boolean) - Optional - On iOS, enable permission dialog to seek permission to use device orientation through a user gesture. Recommended to set to true.
#### enableStyling
- **enableStyling** (boolean) - Optional - Set iOS-look and feel styling for the permission dialog for device orientation.
#### orientationChangeThreshold
- **orientationChangeThreshold** (number) - Optional - Movement threshold to detect an orientation change (radians).
#### preferConfirmDialog
- **preferConfirmDialog** (boolean) - Optional - Use a standard confirm dialog rather than a custom element to grant device orientation permissions.
#### smoothingFactor
- **smoothingFactor** (number) - Optional - Default is 0.2. If too high, AR content movement will lag behind the sensors. If too low, the scene will be jittery.
```
--------------------------------
### LonLat Interface
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/LonLat.html
Defines the structure for geographical coordinates, including latitude and longitude.
```APIDOC
## Interface LonLat
### Description
Longitude and latitude.
### Properties
- **latitude** (number) - The latitude value.
- **longitude** (number) - The longitude value.
### Example
```typescript
{
"latitude": 40.7128,
"longitude": -74.0060
}
```
```
--------------------------------
### GpsOptions Interface
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/GpsOptions.html
The GpsOptions interface specifies optional parameters for initializing GPS functionality, including minimum accuracy and distance.
```APIDOC
## Interface GpsOptions
GPS intialisation options.
### Properties
* **gpsMinAccuracy** (number) - Optional - The minimum accuracy in meters for GPS readings.
* **gpsMinDistance** (number) - Optional - The minimum distance in meters to trigger a location update.
```
--------------------------------
### Create and Add a 3D Mesh
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/tutorial/part1.md
Standard three.js code to create a red box geometry and mesh, which is then added to the LocAR object at a specific longitude and latitude.
```typescript
const geom = new THREE.BoxGeometry(10, 10, 10);
const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
const mesh = new THREE.Mesh(geom, material);
locar.add(mesh, -0.72, 51.0505);
```
--------------------------------
### unproject Method
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/Projection.html
Unprojects 2D Cartesian coordinates back to geographic coordinates (longitude, latitude).
```APIDOC
unproject: (projected: [number, number]) => [number, number]
```
--------------------------------
### on
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Adds an event handler to the LocAR instance. This method is inherited from EventEmitter.
```APIDOC
## on
### Description
Add an event handler.
### Method
(Implicitly a method of the LocAR class)
### Parameters
#### Parameters
- **eventName** (string) - Required - the event to handle.
- **eventHandler** ((...args: any[]) => void) - Required - the event handler function.
### Returns
void
### Source
lib/three/event-emitter.ts:14
```
--------------------------------
### DeviceOrientationControls Methods
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Methods available for the DeviceOrientationControls class, inherited from EventDispatcher.
```APIDOC
## Methods
### addEventListener
* **addEventListener**(type: string, listener: Function)
### dispatchEvent
* **dispatchEvent**(event: { type: string, [key: string]: any })
### hasEventListener
* **hasEventListener**(type: string, listener: Function): boolean
### init
* **init**(): void
### on
* **on**(event: string, listener: Function): void
### removeEventListener
* **removeEventListener**(type: string, listener: Function)
```
--------------------------------
### addGeoLine
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Adds a line to the AR scene based on geographical points and material properties.
```APIDOC
## addGeoLine
### Description
Adds a line to the AR scene based on geographical points and material properties.
### Parameters
* **points** (Array<[number, number, number?]>): An array of points defining the line. Each point can be [longitude, latitude, altitude?].
* **material** (Material): The material to use for the line.
* **lineWidth** (number, optional): The width of the line. Defaults to 1.
### Returns
* Mesh[]: An array of Mesh objects representing the added line.
```
--------------------------------
### ClickHandler.raycast Method
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/ClickHandler.html
Casts a ray into the scene from the camera's perspective to detect intersected objects. This method is crucial for identifying which objects the user is interacting with.
```APIDOC
## raycast
### Description
Cast a ray into the scene to detect objects.
### Parameters
* **camera** (Camera) - The camera used for raycasting.
* **scene** (Scene) - The scene to cast the ray into.
### Returns Intersection>[]
An array of all intersected objects.
```
--------------------------------
### SphMercProjection.project
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/SphMercProjection.html
Projects a longitude and latitude into the Spherical Mercator coordinate system.
```APIDOC
## project
### Description
Project a longitude and latitude into Spherical Mercator.
### Parameters
* **lon** (number) - The longitude.
* **lat** (number) - The latitude.
### Returns
* [number, number]
Two-member array containing easting and northing.
### Implementation of
* [Projection](../interfaces/Projection.html).[project](../interfaces/Projection.html#project)
### Defined in
* lib/three/sphmerc-projection.ts:21
```
--------------------------------
### setElevation
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Sets the elevation (y coordinate) of the camera in meters.
```APIDOC
## setElevation
### Description
Set the elevation (y coordinate) of the camera.
### Method
(Implicitly a method of the LocAR class)
### Parameters
#### Parameters
- **elev** (number) - Required - the elevation in metres.
### Returns
void
### Source
lib/three/locar.ts:316
```
--------------------------------
### setProjection
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Sets the projection to be used by the LocAR instance.
```APIDOC
## setProjection
### Description
Set the projection to use.
### Method
(Implicitly a method of the LocAR class)
### Parameters
#### Parameters
- **proj** (Projection) - Required - The projection to use.
### Returns
void
### Source
lib/three/locar.ts:62
```
--------------------------------
### DeviceOrientationControls Constructor
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Creates an instance of DeviceOrientationControls. This class is used to attach device orientation controls to a Three.js object, typically a camera.
```APIDOC
## new DeviceOrientationControls(object, options)
### Description
Create an instance of DeviceOrientationControls.
### Parameters
* **object** (Object3D) - Required - the object to attach the controls to (usually your Three.js camera)
* **options** (DeviceOrientationControlsOptions) - Optional - options for DeviceOrientationControls: currently accepts smoothingFactor (< 1), enablePermissionDialog, orientationChangeThreshold (radians)
### Returns DeviceOrientationControls
Overrides EventDispatcher.constructor
```
--------------------------------
### SphMercProjection.unproject
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/SphMercProjection.html
Unprojects Spherical Mercator easting and northing coordinates back to longitude and latitude.
```APIDOC
## unproject
### Description
Unproject a Spherical Mercator easting and northing.
### Parameters
* **projected** ([number, number]) - Two-member array containing easting and northing
### Returns
* [number, number]
Two-member array containing longitude and latitude
### Implementation of
* [Projection](../interfaces/Projection.html).[unproject](../interfaces/Projection.html#unproject)
### Defined in
* lib/three/sphmerc-projection.ts:30
```
--------------------------------
### DeviceOrientationControls Properties
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Properties available for the DeviceOrientationControls class.
```APIDOC
## Properties
### alphaOffset
* **alphaOffset**: number
### connect
* **connect**: () => void
### createObtainPermissionGestureDialog
* **createObtainPermissionGestureDialog**: () => void
### deviceOrientation
* **deviceOrientation**: {
absolute?: boolean;
alpha?: number;
beta?: number;
gamma?: number;
webkitCompassHeading?: number;
} | null
### disconnect
* **disconnect**: () => void
### dispose
* **dispose**: () => void
### enabled
* **enabled**: boolean
```
--------------------------------
### WebcamErrorEvent Interface
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/WebcamErrorEvent.html
Represents an error event from the webcam, containing a code and a message describing the error.
```APIDOC
## Interface: WebcamErrorEvent
### Description
Event emitted when the webcam encounters an error.
### Properties
- **code** (string) - The error code.
- **message** (string) - A message describing the error.
```
--------------------------------
### fakeGps
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Simulates a GPS signal with specified longitude, latitude, and optional elevation and accuracy.
```APIDOC
## fakeGps
### Description
Sends a fake GPS signal, useful for testing the application on a desktop or laptop without actual GPS hardware.
### Parameters
* **lon** (number): The longitude of the fake GPS signal.
* **lat** (number): The latitude of the fake GPS signal.
* **elev** (number | null, optional): The elevation in meters. Defaults to null.
* **acc** (number, optional): The accuracy of the GPS reading in meters. Defaults to 0.
```
--------------------------------
### Set Fake GPS Location
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/tutorial/part1.md
Sets a simulated GPS location for the application using longitude and latitude. This is useful for testing without real GPS data.
```javascript
arjs.fakeGps(-0.72, 51.05);
```
--------------------------------
### Fetch and Display POIs from Web API on GPS Update
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/tutorial/part3.md
This snippet handles GPS updates to fetch points of interest from a web API. It fetches data only if the user has moved a significant distance or if it's the first position update. It also prevents duplicate POIs from being added by checking an indexed map.
```typescript
import * as THREE from 'three';
import {
App,
GpsReceivedEvent,
LocAR
} from 'locar';
import type { LonLat } from 'locar';
const app = new App({
cameraOptions: { hFov: 80, near: 0.001, far: 1000 }
});
try {
let firstPosition = true;
const locar = await app.start();
let lastLonLat: LonLat | null = null;
let distSinceUpdate = Number.MAX_VALUE;
const indexedObjects = new Map();
const cube = new THREE.BoxGeometry(20, 20, 20);
locar.on("gpserror", (error: GeolocationPositionError) => {
alert(`GPS error: code ${error.code}`);
});
locar.on("gpsupdate", async(ev: GpsReceivedEvent) => {
const lonLat = {
latitude: ev.position.coords.longitude,
longitude: ev.position.coords.latitude
};
if(lastLonLat !== null) {
distSinceUpdate = LocAR.haversineDist(lonLat, lastLonLat);
}
if(firstPosition || distSinceUpdate > 500) {
firstPosition = false;
lastLonLat = lonLat;
const response = await fetch(`https://hikar.org/webapp/map?bbox=${ev.position.coords.longitude-0.02},${ev.position.coords.latitude-0.02},${ev.position.coords.longitude+0.02},${ev.position.coords.latitude+0.02}&layers=poi&outProj=4326`);
const pois = await response.json();
pois.features.forEach ( (poi: any) => {
if(!indexedObjects.get(poi.properties.osm_id)) {
const mesh = new THREE.Mesh(
cube,
new THREE.MeshBasicMaterial({color: 0xff0000})
);
locar.add(mesh, poi.geometry.coordinates[0], poi.geometry.coordinates[1], 0, poi.properties);
indexedObjects.set(poi.properties.osm_id, mesh);
}
});
}
});
locar.startGps();
} catch (e: any) {
alert(`${e.code} ${e.message}`);
}
```
--------------------------------
### sendData Method
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/ServerLogger.html
Sends data to a specified server endpoint. This method can return a Response object directly or a Promise that resolves to a Response object.
```APIDOC
## sendData
### Description
Sends data to a specified server endpoint.
### Method Signature
sendData(endpoint: string, data: any): Response | Promise
### Parameters
* **endpoint** (string) - The URL or identifier of the server endpoint.
* **data** (any) - The data payload to be sent to the server.
### Returns
Response | Promise - A Response object or a Promise resolving to a Response object.
```
--------------------------------
### Add Four Boxes on Initial GPS Update
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/tutorial/part2.md
This code snippet is executed within the `gpsupdate` event handler. It adds four boxes (red, yellow, cyan, green) at specific distances north, south, west, and east of the initial GPS location. Ensure `firstLocation` flag is managed to prevent repeated additions.
```typescript
locar.on("gpsupdate", (ev: GpsReceivedEvent) => {
if(firstLocation) {
alert(`Got the initial location: longitude ${ev.position.coords.longitude}, latitude ${ev.position.coords.latitude}`);
const boxProps = [{
latDis: 0.0005,
lonDis: 0,
colour: 0xff0000
}, {
latDis: -0.0005,
lonDis: 0,
colour: 0xffff00
}, {
latDis: 0,
lonDis: -0.0005,
colour: 0x00ffff
}, {
latDis: 0,
lonDis: 0.0005,
colour: 0x00ff00
}];
const geom = new THREE.BoxGeometry(10,10,10);
for(const boxProp of boxProps) {
const mesh = new THREE.Mesh(
geom,
new THREE.MeshBasicMaterial({color: boxProp.colour})
);
locar.add(
mesh,
ev.position.coords.longitude + boxProp.lonDis,
ev.position.coords.latitude + boxProp.latDis
);
}
firstLocation = false;
}
});
```
--------------------------------
### ServerLogger Interface Definition
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/ServerLogger.html
Defines the structure of the ServerLogger interface, which includes a method for sending data.
```typescript
interface ServerLogger {
[sendData](#senddata-1)(endpoint: string, data: any): Response | Promise;
}
```
--------------------------------
### dispatchEvent(event)
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Fires an event type. Inherited from EventDispatcher.
```APIDOC
## dispatchEvent(event)
### Description
Fire an event type.
### Method
dispatchEvent
### Type Parameters
- T extends never
### Parameters
#### Parameters
- **event** (BaseEvent & { [T]: any }) - The event that gets fired.
### Returns
void[]
```
--------------------------------
### DeviceOrientationControls Properties
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Exposes various properties that can be accessed or modified to control and monitor the device orientation.
```APIDOC
## DeviceOrientationControls Properties
### Properties
* **alphaOffset** (number) - An offset applied to the alpha (heading) value.
* **connect** (Function) - Connects the controls to the device's orientation sensor.
* **createObtainPermissionDialog** (Function) - Creates a dialog to request permission for orientation.
* **deviceOrientation** (Object) - Stores the latest device orientation event data.
* **disconnect** (Function) - Disconnects the controls from the device's orientation sensor.
* **dispose** (Function) - Cleans up resources and removes event listeners.
* **enabled** (boolean) - Indicates whether the controls are currently enabled.
* **enableInlineStyling** (boolean) - Enables inline styling for permission dialogs.
* **enablePermissionDialog** (boolean) - Enables the display of a permission dialog.
* **eventEmitter** (Object) - An event emitter instance for custom events.
* **getAlpha** (Function) - Returns the current alpha (heading) value.
* **getBeta** (Function) - Returns the current beta (pitch) value.
* **getCorrectedHeading** (Function) - Returns the corrected heading value.
* **getGamma** (Function) - Returns the current gamma (roll) value.
* **initialOffset** (number) - An initial offset applied during setup.
* **lastQuaternion** (Object) - Stores the last computed quaternion representing orientation.
* **object** (Object) - The object being controlled.
* **obtainPermissionGesture** (Function) - Initiates the gesture to obtain orientation permissions.
* **orientationChangeEventName** (string) - The name of the orientation change event.
* **orientationChangeThreshold** (number) - The threshold for detecting significant orientation changes.
* **orientationOffset** (number) - An offset applied to the orientation values.
* **preferConfirmDialog** (boolean) - Prefers a confirmation dialog for permission requests.
* **requestOrientationPermissions** (Function) - Requests permissions for device orientation.
* **screenOrientation** (number) - The current screen orientation value.
* **smoothingFactor** (number) - The factor used for smoothing orientation data.
* **update** (Function) - Updates the controls with the latest sensor data.
* **updateAlphaOffset** (Function) - Updates the alpha offset value.
```
--------------------------------
### GpsReceivedEvent Interface
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/GpsReceivedEvent.html
This interface defines the structure of the event emitted when a new GPS position is received. It includes the distance moved since the last event and the new geolocation position.
```APIDOC
## Interface GpsReceivedEvent
Event emitted when a GPS position is received.
### Properties
* **distMoved** (number) - distance moved in metres since last GpsReceivedEvent
* **position** (GeolocationPosition) - The new GPS position
```
--------------------------------
### sendData Method Signature
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/ServerLogger.html
Details the signature of the sendData method within the ServerLogger interface. It accepts an endpoint string and data of any type, returning either a Response or a Promise resolving to a Response.
```typescript
sendData(endpoint: string, data: any): Response | Promise
```
--------------------------------
### off Method
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/EventEmitter.html
Removes an event handler for a specific event.
```APIDOC
## off(eventName: string, eventHandler: (...args: any[]) => void): void
### Description
Remove an event handler.
### Parameters
* **eventName** (string) - The name of the event to remove a handler from.
* **eventHandler** ((...args: any[]) => void) - The event handler function to remove.
### Returns
* void
```
--------------------------------
### addEventListener(type, listener)
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Adds a listener to an event type. Inherited from EventDispatcher.
```APIDOC
## addEventListener(type, listener)
### Description
Adds a listener to an event type.
### Method
addEventListener
### Type Parameters
- T extends never
### Parameters
#### Parameters
- **type** (T) - The type of event to listen to.
- **listener** (EventListener<{}[T], T, DeviceOrientationControls>) - The function that gets called when the event is fired.
### Returns
void[]
```
--------------------------------
### updateAlphaOffset()
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/DeviceOrientationControls.html
Updates the alpha offset for the device orientation controls. This can be used to correct the orientation if needed.
```APIDOC
## updateAlphaOffset()
### Description
Updates the alpha offset for the device orientation controls.
### Method
updateAlphaOffset
### Returns
void
```
--------------------------------
### DeviceOrientationErrorEvent Interface
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/DeviceOrientationErrorEvent.html
Represents an error event related to device orientation, containing a code and a message describing the error.
```APIDOC
## Interface: DeviceOrientationErrorEvent
### Description
Event emitted when there is an error with device orientation. This interface defines the structure of such error events.
### Properties
#### code
- **code** (string) - Description: An error code indicating the type of device orientation error.
#### message
- **message** (string) - Description: A human-readable message providing details about the device orientation error.
```
--------------------------------
### eastNorthToWorldCoords
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/classes/LocAR.html
Converts projected east/north coordinates to three.js/WebGL world coordinates.
```APIDOC
## eastNorthToWorldCoords
### Description
Converts projected east/north coordinates to three.js/WebGL world coordinates. This method negates the northing component to align with the WebGL coordinate system. It assumes the input position is in the correct projection and should only be called after an initial position has been determined.
### Parameters
* **projectedPos** ([number, number]): The projected position in east/north coordinates.
### Returns
* [number, number]: A two-element array containing the WebGL x and z coordinates.
```
--------------------------------
### DeviceOrientationGrantedEvent Interface
Source: https://github.com/ar-js-org/locar.js/blob/master/docs/api/interfaces/DeviceOrientationGrantedEvent.html
The DeviceOrientationGrantedEvent is an event emitted when device orientation permission has been granted. It contains a reference to the target DeviceOrientationControls.
```APIDOC
## Interface: DeviceOrientationGrantedEvent
### Description
Event emitted when device orientation permission has been granted.
### Properties
- **target** (DeviceOrientationControls) - The DeviceOrientationControls instance associated with the event.
```