Class MapView

MapView is the main rendering and interaction class for Mappedin maps. It provides comprehensive controls for manipulating map elements, camera, styling, and user interactions.

  • Rendering Control: Camera, labels, markers, models, paths, and more
  • Interactive Elements: Hover effects, click handling, and state management
  • Animation System: Smooth transitions and state animations
  • Multi-floor Support: Floor switching and stacked maps
  • Navigation: Built-in wayfinding and directions
  • Styling: Dynamic theme and style customization
  • Event System: Comprehensive event handling for user interactions

Best Practice: Use the specialized API classes (Camera, Markers, Labels, etc.) for specific functionality.

// Initialize MapView
const mapData = await getMapData({key: 'your-key', secret: 'your-secret', mapId: 'your-map-id'});
const mapView = await show3dMap(container, mapData);
mapView.on('click', (event) => {
console.log('Clicked:', event.coordinate);
});
  • Camera: View control, zoom, pan, and rotation
  • Markers: Point-based visual elements
  • Labels: Text overlays on the map
  • Paths: Route visualization and navigation
  • Models: 3D model rendering
  • Style: Theme and appearance customization
  • Navigation: Wayfinding and directions
  • updateState(): Immediate state changes
  • animateState(): Smooth animated transitions
  • getState(): Retrieve current element states
  • updateGlobalState(): Apply global styling changes
// Listen for user interactions
mapView.on('click', (event) => {
console.log('Clicked:', event.coordinate);
});

mapView.on('hover', (event) => {
console.log('Hovered:', event.coordinate);
});

mapView.on('floorChanged', (event) => {
console.log('Floor changed to:', event.floor);
});

The MapView class is the main class for rendering and interacting with the map.

It provides a set of controls for manipulating the map's elements and state.

For help getting started, refer to the Getting Started Guide.

Properties

Camera: Camera

Controls for the map's camera.

Provides methods for camera positioning, zooming, panning, and view control.

// Set camera position
mapView.Camera.setPosition(coordinate, { duration: 1000 });

// Zoom to fit all spaces
mapView.Camera.fitToElements(spaces);

// Animate camera movement
mapView.Camera.animateTo(coordinate, { duration: 2000 });
Image3D: Image3D

Controls for the map's 3D images.

Manages image overlays and custom image elements on the map.

// Add an image
const image = mapView.Image3D.add(coordinate, 'path/to/image.png', {
width: 100,
height: 100
});
Labels: Labels

Controls for the map's labels.

Manages text overlays, tooltips, and label visibility on the map.

// Add a label
const label = mapView.Labels.add(coordinate, 'Welcome!');

// Update label style
mapView.Labels.update(label, { color: 'red', fontSize: 16 });

// Remove label
mapView.Labels.remove(label);
Markers: Markers

Controls for the map's markers.

Manages point-based visual elements like pins, icons, and custom markers.

// Add a marker
const marker = mapView.Markers.add(coordinate, {
color: 'red',
size: 20,
label: 'Important Location'
});

// Update marker
mapView.Markers.update(marker, { color: 'blue' });

// Remove marker
mapView.Markers.remove(marker);
Models: Models

Controls for the map's models.

Manages 3D model rendering and positioning on the map.

// Add a 3D model
const model = mapView.Models.add(coordinate, 'path/to/model.glb', {
scale: 1.0,
rotation: { x: 0, y: 0, z: 0 }
});
Navigation: Navigation

Controls for the map's navigation.

Outdoor: Outdoor

Controls for the outdoor map.

Manages outdoor map integration and outdoor tile rendering.

// Enable outdoor map
mapView.Outdoor.enable();

// Set outdoor style
mapView.Outdoor.setStyle('satellite');
Paths: Paths

Controls for the map's paths.

Manages route visualization, navigation paths, and custom path rendering.

// Add a path
const path = mapView.Paths.add(coordinates, {
color: 'blue',
width: 3,
animated: true
});

// Show navigation route
const directions = mapData.getDirections(space1, space2);
if (directions) {
mapView.Paths.show(directions);
}
Shapes: Shapes

Controls custom GeoJSON geometry on the map.

Allows adding custom geometric shapes and overlays to the map.

// Add custom shape
const shape = mapView.Shapes.add(geoJSON, {
color: 'red',
opacity: 0.5
});
Style: Style

Controls for the indoor map's style.

Text3D: Text3D

Controls for the map's 3D texts.

Provides 3D text rendering capabilities for enhanced visual effects.

// Add 3D text
const text3d = mapView.Text3D.add(coordinate, '3D Text', {
height: 10,
color: 'blue'
});

Accessors

  • get currentFloor(): Floor

    Gets the current (Floor) of the map.

    Returns Floor

    The current Floor, or undefined if no floor is set.

    const currentFloor = mapView.currentFloor;
    if (currentFloor) {
    console.log('Current floor:', currentFloor.name);
    console.log('Floor level:', currentFloor.level);
    }
  • get currentFloorStack(): FloorStack

    Gets the current (FloorStack).

    Returns FloorStack

    The current FloorStack, or undefined if no floor stack is set.

    const currentStack = mapView.currentFloorStack;
    if (currentStack) {
    console.log('Current floor stack:', currentStack.name);
    }
  • get tweenGroup(): Group

    The group which manages all tweens created with tween or animateState.

    Returns Group

Methods

  • Experimental

    This is an experimental feature that may undergo significant changes, including breaking changes, renaming, or complete removal in future versions. Do not rely on this API in production environments.

    Automatically creates labels, markers, and updates state of map elements provided with default settings.

    Parameters

    • OptionalmapElements: MapDataElements[]

      A custom array of map elements to automatically create labels, markers, and update state of. If not provided, all map elements will be used.

    Returns Promise<AutoElements>

    An object containing auto-created labels and markers.

  • Gets the rendered state of a map element.

    Retrieves runtime rendering state that changes frequently, such as text visibility for labels.

    Type Parameters

    Parameters

    • target: T

      The map element to get the rendered state for.

    Returns undefined | TGetRenderedState<T>

    An object containing the requested rendered state keys, or undefined if not found.

    const label = mapView.Labels.add(space, 'Hello');
    const renderedState = mapView.__EXPERIMENTAL__getRenderedState(label);
    console.log('Text visible:', renderedState?.textVisible);
  • Animate the state of a given target on the map from the current state to a new state. Only numeric properties and colors can be animated.

    Use updateState() for immediate updates.

    The following table maps targets to their available states:

    Target State Type Description
    Door TDoorsUpdateState Open/closed state, color
    Floor TFloorUpdateState Color, opacity, visibility
    Label TLabelUpdateState Text, color, visibility
    Marker TMarkerUpdateState Color, size, icon
    Model TModelUpdateState Scale, rotation, visibility
    Path TPathUpdateState Color, width, visibility
    Shape TShapeUpdateState Color, opacity, geometry
    Space TGeometryUpdateState Color, opacity, visibility
    Text3DView TText3DUpdateState Text, color, height
    DOORS TDoorsUpdateState Global door settings
    WALLS TWallsUpdateState Global wall settings

    Type Parameters

    Parameters

    • target: T

      The map element to animate.

    • state: PartialDeep<
          {
              [K in string
              | number
              | symbol as TGetState<T>[K] extends undefined | string | number
                  ? K
                  : TGetState<T>[K] extends undefined | object
                      ? {
                          [K in string
                          | number
                          | symbol as NonNullable<any[any]>[K] extends
                              | undefined
                              | string
                              | number
                              ? K
                              : NonNullable<any[any]>[K] extends undefined | object
                                  ? {
                                      [K in (...)
                                      | (...)
                                      | (...) as (...) extends (...) ? (...) : (...)]: (...) extends (...)
                                          ? (...)
                                          : (...)
                                  } extends never
                                      ? never
                                      : K
                                  : never]: NonNullable<any[any]>[K] extends undefined | object
                              ? undefined extends any[any]
                                  ? | {
                                      [K in (...)
                                      | (...)
                                      | (...) as (...) extends (...) ? (...) : (...)]: (...) extends (...)
                                          ? (...)
                                          : (...)
                                  }
                                  | any[any] & undefined
                                  : {
                                      [K in string
                                      | number
                                      | symbol as (...)[(...)] extends (...) | (...) | (...)
                                          ? K
                                          : (...) extends (...) ? (...) : (...)]: (...)[(...)] extends
                                          | (...)
                                          | (...)
                                          ? (...) extends (...) ? (...) : (...)
                                          : (...) extends (...) ? (...) : (...)
                                  }
                              : NonNullable<any[any]>[K] extends undefined | string | number
                                  ? any[any]
                                  : never
                      } extends never
                          ? never
                          : K
                      : never]: TGetState<T>[K] extends undefined | object
                  ? undefined extends any[any]
                      ? | {
                          [K in string
                          | number
                          | symbol as NonNullable<any[any]>[K] extends
                              | undefined
                              | string
                              | number
                              ? K
                              : NonNullable<any[any]>[K] extends undefined | object
                                  ? {
                                      [K in (...)
                                      | (...)
                                      | (...) as (...) extends (...) ? (...) : (...)]: (...) extends (...)
                                          ? (...)
                                          : (...)
                                  } extends never
                                      ? never
                                      : K
                                  : never]: NonNullable<any[any]>[K] extends undefined | object
                              ? undefined extends any[any]
                                  ? | {
                                      [K in (...)
                                      | (...)
                                      | (...) as (...) extends (...) ? (...) : (...)]: (...) extends (...)
                                          ? (...)
                                          : (...)
                                  }
                                  | any[any] & undefined
                                  : {
                                      [K in string
                                      | number
                                      | symbol as (...)[(...)] extends (...) | (...) | (...)
                                          ? K
                                          : (...) extends (...) ? (...) : (...)]: (...)[(...)] extends
                                          | (...)
                                          | (...)
                                          ? (...) extends (...) ? (...) : (...)
                                          : (...) extends (...) ? (...) : (...)
                                  }
                              : NonNullable<any[any]>[K] extends undefined | string | number
                                  ? any[any]
                                  : never
                      }
                      | any[any] & undefined
                      : {
                          [K in string
                          | number
                          | symbol as NonNullable<any[any]>[K] extends
                              | undefined
                              | string
                              | number
                              ? K
                              : NonNullable<any[any]>[K] extends undefined | object
                                  ? {
                                      [K in string
                                      | number
                                      | symbol as (...)[(...)] extends (...) | (...) | (...)
                                          ? K
                                          : (...) extends (...) ? (...) : (...)]: (...)[(...)] extends
                                          | (...)
                                          | (...)
                                          ? (...) extends (...) ? (...) : (...)
                                          : (...) extends (...) ? (...) : (...)
                                  } extends never
                                      ? never
                                      : K
                                  : never]: NonNullable<any[any]>[K] extends undefined | object
                              ? undefined extends any[any]
                                  ? | {
                                      [K in string
                                      | number
                                      | symbol as (...)[(...)] extends (...) | (...) | (...)
                                          ? K
                                          : (...) extends (...) ? (...) : (...)]: (...)[(...)] extends
                                          | (...)
                                          | (...)
                                          ? (...) extends (...) ? (...) : (...)
                                          : (...) extends (...) ? (...) : (...)
                                  }
                                  | any[any] & undefined
                                  : {
                                      [K in string
                                      | number
                                      | symbol as NonNullable<(...)>[K] extends
                                          | undefined
                                          | string
                                          | number
                                          ? K
                                          : (...)[(...)] extends (...) | (...) ? K : never]: NonNullable<
                                          (...),
                                      >[K] extends undefined | object
                                          ? undefined extends any[any] ? any : any
                                          : (...)[(...)] extends (...) | (...) | (...) ? any[any] : never
                                  }
                              : NonNullable<any[any]>[K] extends undefined | string | number
                                  ? any[any]
                                  : never
                      }
                  : TGetState<T>[K] extends undefined | string | number ? any[any] : never
          },
      >

      The target state to animate to.

    • Optionaloptions: {
          duration?: number;
          easing?: "ease-in" | "ease-out" | "ease-in-out" | "linear";
      }

      Animation configuration options.

      • Optionalduration?: number

        The duration of the animation in milliseconds (default: 1000).

      • Optionaleasing?: "ease-in" | "ease-out" | "ease-in-out" | "linear"

        The easing function to use for the animation.

    Returns TCancellablePromise<TAnimateStateResult>

    A cancellable promise that resolves when the animation completes.

    mapView.animateState(label, {
    appearance: {
    textSize: state.appearance.textSize! + 1,
    textColor: state.appearance.textColor! === '#000000' ? 'purple' : '#000000',
    },
    });

    to interactive when the animation completes.

    mapView.on('click', ({ spaces }) => {
    if (!spaces) return;
    spaces.forEach(space => {
    const state = mapView.getState(space)!;
    mapView.updateState(space, {
    interactive: false,
    });
    currentAnimation = mapView.animateState(space, {
    height: state.height + 1,
    color: state.color === 'rgb(255, 0, 0)' ? 'blue' : 'rgb(255, 0, 0)',
    });
    currentAnimation.finally(() => {
    mapView.updateState(space, {
    interactive: true,
    });
    });
    });
    });
  • Clears all added elements from the map.

    Returns void

  • Creates a Coordinate on the map.

    Parameters

    • latitude: number

      The latitude of the coordinate.

    • longitude: number

      The longitude of the coordinate.

    • Optionalfloor: Floor

      Optional floor information if applicable.

    Returns Coordinate

    The created Coordinate object.

    // Create a coordinate at the CN Tower.
    const coord = map.createCoordinate(43.642567, -79.387054);

    // Alternatively, you can directly use the Coordinate constructor:
    import { Coordinate } from '@mappedin/mappedin-js';
    const coord = new Coordinate(43.642567, -79.387054, floor?.id);
  • Creates a Coordinate on the map using a params object.

    Parameters

    • params: TCoordinateParams

      An object containing the coordinate parameters.

      • OptionalfloorId?: string

        Optional ID of the Floor this Coordinate is on.

      • latitude: number

        The latitude of the Coordinate.

      • longitude: number

        The longitude of the Coordinate.

      • OptionalverticalOffset?: number

        Optional vertical offset from the Floor in meters.

    Returns Coordinate

    The created Coordinate object.

    // Create a coordinate at the CN Tower using params object.
    const coord = map.createCoordinate({
    latitude: 43.642567,
    longitude: -79.387054
    });

    // Alternatively, you can directly use the Coordinate constructor:
    import { Coordinate } from '@mappedin/mappedin-js';
    const coord = new Coordinate({
    latitude: 43.642567,
    longitude: -79.387054,
    floorId: 'floor1',
    verticalOffset: 10
    });
  • Experimental

    Create a Coordinate from an X and Y position measured in pixels from the top left corner of the map canvas.

    Parameters

    • x: number
    • y: number
    • Optionalfloor: Floor

    Returns undefined | Coordinate

  • Destroys the MapView.

    Returns void

  • Gets the current dimensions of the map container.

    Returns { height: number; width: number }

    An object containing the width and height of the map container.

    const dimensions = mapView.getDimensions();
    console.log(`Map size: ${dimensions.width}x${dimensions.height}`);
  • Calculates directions (Directions) from one navigable point (TNavigationTarget) to multiple destination points on the map.

    Provides routes from a single starting point to multiple destinations. This method delegates to the MapData instance.

    Parameters

    Returns Promise<undefined | Directions[]>

    A Promise resolving to an array of Directions objects, one for each destination.

    In enterprise mode, path smoothing is disabled by default. Use the smoothing option to explicitly enable it if needed.

    const start = mapData.getById('space', 'entrance');
    const destinations = [
    mapData.getById('space', 'store-1'),
    mapData.getById('space', 'store-2'),
    mapData.getById('space', 'restaurant')
    ].filter(Boolean);

    const allDirections = await mapView.getDirectionsMultiDestination(start, destinations);
    allDirections.forEach((directions, index) => {
    console.log(`Route ${index + 1}: ${directions.distance}m`);
    });
  • Calculates the walking distance between two navigable points (TNavigationTarget) on the map.

    Returns the walking distance between two points. This method delegates to the MapData instance.

    Parameters

    Returns undefined | number

    The distance in meters.

    const space1 = mapData.getById('space', 'space-123');
    const space2 = mapData.getById('space', 'space-456');

    if (space1 && space2) {
    const distance = mapView.getDistance(space1, space2);
    console.log(`Direct distance: ${distance}m`);
    }
    const coordinate = mapData.mapCenter;
    const space = mapData.getByType('space')[0];
    const distance = mapView.getDistance(coordinate, space);
    console.log(`Distance from center: ${distance}m`);
  • Get global state of the MapView

    Returns ReadonlyObjectDeep<GlobalState>

  • Gets the current hover color.

    Returns undefined | string

    The current hover color.

    const hoverColor = mapView.getHoverColor();
    console.log('Hover color:', hoverColor);
  • Gets the map elements that are currently in view.

    Type Parameters

    • T extends string

    Parameters

    • type: T

      The type of map element to get.

    • Optionaloptions: Partial<{ fullyContains: boolean; screenOffsets: Partial<InsetPadding> }>

      Optional configuration for the in view check.

    Returns MapFeatureOfType<T>[]

    An array of map elements that are currently in view.

  • Gets the current map data associated with this view.

    Returns MapData

    The current MapData instance, or undefined if no map is loaded.

    const mapData = mapView.getMapData();
    if (mapData) {
    console.log('Map name:', mapData.mapName);
    const spaces = mapData.getByType('space');
    console.log('Number of spaces:', spaces.length);
    }
  • Returns the current scale of the map in meters per pixel.

    Returns number

    const metersPerPixel = mapView.getMetersPerPixel();
    console.log('Meters per pixel:', metersPerPixel);
  • Experimental

    Get the X and Y of a Coordinate measured from the top left corner of the map canvas.

    Parameters

    Returns { x: number; y: number }

  • Gets the current state of a map element.

    Retrieves the current visual properties and state of a map element.

    Type Parameters

    Parameters

    • target: T

      The map element to get the state for.

    Returns TGetState<T>

    The current state of the element.

    const space = mapData.getById('space', 'space-123');
    if (space) {
    const state = mapView.getState(space);
    console.log('Space color:', state.color);
    console.log('Space opacity:', state.opacity);
    }
    const marker = mapView.Markers.add(coordinate);
    const state = mapView.getState(marker);
    console.log('Marker rank:', state.rank);
    console.log('Marker placement:', state.placement);
  • Determines if a given target is within the viewport.

    This method checks if the specified target, such as a Space, MapObject, Label, Marker, or string identifier, is currently within the visible area of the map viewport. Note that this method returns true even if the target is not visible (e.g., its visibility is set to false).

    Parameters

    • target: string | Label | Space | MapObject | Marker

      The target to check for viewport inclusion. This can be a Space, MapObject, Label, Marker, or string identifier.

    Returns boolean

    A boolean indicating whether the target is within the viewport.

  • Unsubscribe a function previously subscribed with on

    Type Parameters

    Parameters

    • eventName: EventName

      An event name to which the provided function was previously subscribed.

    • fn: (payload: TEventPayload<EventName>) => void

      A function that was previously passed to on. The function must have the same reference as the function that was subscribed.

    Returns void

    // Unsubscribe from the 'click' event
    const handler = (event) => {
    const { coordinate } = event;
    const { latitude, longitude } = coordinate;
    console.log(`Map was clicked at ${latitude}, ${longitude}`);
    };
    mapView.off('click', handler);
  • Subscribe a function to an event.

    Type Parameters

    Parameters

    • eventName: EventName

      An event name which, when fired, will call the provided function.

    • fn: (payload: TEventPayload<EventName>) => void

      A callback that gets called when the corresponding event is fired. The callback will get passed an argument with a type that's one of event payloads.

    Returns void

    // Subscribe to the 'click' event
    const handler = (event) => {
    const { coordinate } = event;
    const { latitude, longitude } = coordinate;
    console.log(`Map was clicked at ${latitude}, ${longitude}`);
    };
    mapView.on('click', handler);
  • Preload floor geometry and outlines for the map at runtime. Can be used when anticipating a large number of floors will be visible at once to keep the map responsive.

    Parameters

    • floors: Floor[]

      The floors to preload.

    Returns void

  • Remove a tween created with tween.

    Parameters

    • tween: Tween<any>

      The tween to remove.

    Returns void

  • Sets the current floor of the map.

    Changes the visible floor and updates the camera to focus on the new floor.

    Parameters

    • floor: string | Floor

      The floor to set, either as a Floor object or floor ID string.

    • Optionaloptions: TSetFloorOptions

      Optional configuration for the floor change.

    Returns void

    A promise that resolves when the floor change is complete.

    const floors = mapData.getByType('floor');
    const groundFloor = floors.find(f => f.elevation === 0);
    if (groundFloor) {
    await mapView.setFloor(groundFloor);
    }
    await mapView.setFloor('floor-1');
    
  • Sets the current (FloorStack) of the map.

    Changes to a specific floor stack, which may contain multiple floors for complex buildings.

    Parameters

    Returns void

    A promise that resolves when the floor stack change is complete.

    const floorStacks = mapData.getByType('floor-stack');
    const mainBuilding = floorStacks.find(fs => fs.name === 'Main Building');
    if (mainBuilding) {
    await mapView.setFloorStack(mainBuilding);
    }
  • Sets the hover color for map elements.

    Parameters

    • c: string

      The color to use for hover effects.

    Returns void

    mapView.setHoverColor('#ff0000');
    
  • Experimental

    Takes a screenshot of the current scene and returns it as a data URL.

    NOTE: This only captures the 3D scene, and optionally the outdoor context, not the UI elements like labels, markers, etc. Also, this does not cause the screenshot to be saved to the user's device, it only returns the data.

    Parameters

    • Optionaloptions: TTakeScreenshotOptions

      Options for taking a screenshot.

      • OptionalwithOutdoorContext?: boolean

        Whether to include the outdoor context in the screenshot.

        false
        

    Returns Promise<string>

    A Promise that resolves with the screenshot as a base64-encoded data URL string

    false
    
  • Create a tween object that will be updated on every render frame. See https://tweenjs.github.io/tween.js/docs/user_guide.html for more information.

    When creating a large number of tween objects, it may be important to call removeTween to prevent memory leaks.

    Type Parameters

    • T extends Record<string, unknown>

    Parameters

    • object: T

      The data to be tweened.

    Returns Tween<T>

    The tween object.

  • Triggers a manual update of the map view.

    Forces the map to re-render. This is typically not needed as the map updates automatically, but can be useful in certain edge cases.

    Returns void

    // Force map update after external changes
    mapView.update();
  • Update global state of the MapView

    Parameters

    • update: {
          backgroundAlpha?: number;
          backgroundColor?: string;
          environment?: EnvMapOptions;
          geometry?: { hoverColor?: string };
          text3d?: { hoverColor?: string };
      }
      • OptionalbackgroundAlpha?: number

        The alpha value of the background, between 0 and 1.

        1
        
      • OptionalbackgroundColor?: string

        The color of the background, in hex format(#000000).

      • Optionalenvironment?: EnvMapOptions

        environment map for reflections.

        'basic'
        
      • Optionalgeometry?: { hoverColor?: string }
        • OptionalhoverColor?: string

          hover color of the geometries

      • Optionaltext3d?: { hoverColor?: string }
        • OptionalhoverColor?: string

          hover color of the text3d

    Returns void