Skip to main content

Map Compass

|

This example demonstrates how to render a compass icon that displays the heading rotation of an interactive map. The compass indicates the direction where 0 degrees is north, 90 degrees is east, 180 degrees is south, and 270 degrees is west. You will also learn how to rotate the map back to its default north-up orientation.

Live Demo

Code Implementation

SDK Initialization, Compass Image, and Rotation Logic

index.ts
import { GemKit, GemMap, SdkSettings, PositionService, EngineMisc } from '@magiclane/maps-sdk';
import { GEMKIT_TOKEN } from './token';
let map: GemMap | null = null;
let compassAngle = 0;
let compassImg: HTMLImageElement | null = null;

// Helper to get compass image from SDK
function getCompassImage(): string | null {
// SdkSettings.getImageById returns a base64 string or URL
const imgData = SdkSettings.getImageById({
id: EngineMisc.compassEnableSensorON,
size: { width: 100, height: 100 }
});
if (!imgData) return null;
// If imgData is a Buffer or Uint8Array, convert to base64 data URL
if (typeof imgData === 'string') {
// If already a string, assume it's a valid src
return imgData;
}
// If it's a buffer, convert to base64
let binary = '';
const bytes = new Uint8Array(imgData);
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
const base64 = btoa(binary);
return `data:image/png;base64,${base64}`;
}

// Create compass UI
function createCompass() {
if (compassImg) compassImg.remove();

compassImg = document.createElement('img');
compassImg.style.cssText = `
position: fixed; right: 12px; top: 12px; width: 40px; height: 40px;
background: #fff; border-radius: 50%; padding: 3px; z-index: 2000; cursor: pointer;
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
transition: transform 0.2s;
`;
const imgSrc = getCompassImage();
if (imgSrc) compassImg.src = imgSrc;
compassImg.onclick = () => {
if (map) map.alignNorthUp();
};
document.body.appendChild(compassImg);
updateCompassRotation();
}

// Update compass rotation
function updateCompassRotation() {
if (compassImg) {
compassImg.style.transform = `rotate(${-compassAngle}deg)`;
}
}

// Map angle update callback
function onMapAngleUpdate(angle: number) {
compassAngle = angle;
updateCompassRotation();
}

// Map created callback
async function onMapCreated(gemMap: GemMap) {
map = gemMap;

map.registerMapAngleUpdateCallback(onMapAngleUpdate);
createCompass();
}

// Main entry
window.addEventListener('DOMContentLoaded', async () => {
// Initialize GemKit with your API token
const gemKit = await GemKit.initialize(GEMKIT_TOKEN);

const container = document.getElementById('map-container');
if (!container) throw new Error('Map container not found');

const viewId = 0;
// Create a view with the specified ID and callback
const wrapper = gemKit.createView(viewId, (gemMap: GemMap) => {
onMapCreated(gemMap);
});
if (wrapper) container.appendChild(wrapper);
});

Key Features

Map Angle Synchronization

The example registers a callback to track the map's rotation angle:

  • Angle Tracking: The registerMapAngleUpdateCallback monitors the map's heading
  • Real-time Updates: Compass rotates smoothly as the map orientation changes
  • Visual Feedback: The compass icon reflects the current map rotation

Compass Interaction

Clicking the compass icon resets the map orientation:

  • North Alignment: Tapping the compass calls alignNorthUp() to reset the map
  • Interactive Control: Provides an intuitive way to return to default orientation
  • Visual Indicator: The compass always shows which direction is north

How It Works

  1. Initialize Map: Create the map view and register the angle update callback
  2. Get Compass Image: Retrieve the compass icon from SDK settings using EngineMisc.compassEnableSensorON
  3. Create Compass UI: Position the compass in the top-right corner with proper styling
  4. Track Rotation: Update the compass rotation whenever the map angle changes
  5. Reset Orientation: Allow users to reset to north-up by clicking the compass

Implementation Details

Compass Image

The compass image is obtained from the SDK's built-in resources:

  • Uses SdkSettings.getImageById() to get the compass icon
  • Converts image data to base64 if needed for browser display
  • Supports both string URLs and binary image data

Rotation Calculation

The compass rotation is calculated using:

  • Map angle in degrees (0° = North, 90° = East, 180° = South, 270° = West)
  • Negative rotation applied to compass to show north direction
  • Smooth CSS transitions for visual appeal

User Interaction

The compass provides interactive functionality:

  • Click handler attached to compass element
  • Calls map.alignNorthUp() to reset map orientation
  • Visual feedback with cursor pointer and hover effects

Next Steps