Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor compass #14

Merged
merged 4 commits into from
Dec 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
# maplibre-gl-compass

![test](https://github.com/qazsato/maplibre-gl-compass/actions/workflows/test.yml/badge.svg)
[![npm version](https://badge.fury.io/js/maplibre-gl-compass.svg)](https://badge.fury.io/js/maplibre-gl-compass)
[![npm downloads](https://img.shields.io/npm/dm/maplibre-gl-compass.svg)](https://badge.fury.io/js/maplibre-gl-compass)
[![MIT License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)

A **heading-up** compass for MapLibre GL JS 🧭

## About

**maplibre-gl-compass** is a plugin for MapLibre GL JS.
This plugin rotates the map based on the values from the [Device orientation events](https://developer.mozilla.org/en-US/docs/Web/API/Device_orientation_events).
Therefore, it can only be used on devices equipped with an orientation sensor, such as mobile devices.

Expand Down Expand Up @@ -41,7 +38,7 @@ map.addControl(new CompassControl())
import { Map } from 'maplibre-gl'
import 'maplibre-gl/dist/maplibre-gl.css'
import { CompassControl } from 'maplibre-gl-compass'
import type { CompassEvent } from 'maplibre-gl-compass'
import type { CompassEvent, CompassError } from 'maplibre-gl-compass'
import 'maplibre-gl-compass/style.css'

const map = new Map({/* YOUR_MAP_OPTION */})
Expand All @@ -67,6 +64,10 @@ compass.on('compass', (event: CompassEvent) => {
// Your custom logic is here!
})

compass.on('error', (event: CompassError) => {
// Your custom logic is here!
})

map.addControl(compass)
```

Expand Down
14 changes: 7 additions & 7 deletions docs/index-C-v9-Spc.js → docs/index-B7U_mx4l.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<link rel="icon" type="image/svg+xml" href="/maplibre-gl-compass/compass.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>maplibre-gl-compass</title>
<script type="module" crossorigin src="/maplibre-gl-compass/index-C-v9-Spc.js"></script>
<script type="module" crossorigin src="/maplibre-gl-compass/index-B7U_mx4l.js"></script>
<link rel="stylesheet" crossorigin href="/maplibre-gl-compass/index-BkH9e1jg.css">
</head>
<body>
Expand Down
14 changes: 7 additions & 7 deletions src/components/DebugView.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { WebkitDeviceOrientationEvent } from '../maplibre-gl-compass'
import type { CompassEvent } from '../core/Compass'
import './DebugView.css'

export class DebugView {
Expand All @@ -19,16 +19,16 @@ export class DebugView {
parent.appendChild(this.element)
}

update(heading?: number, event?: WebkitDeviceOrientationEvent) {
update(event?: CompassEvent) {
const eventName = this.element.querySelector('.event-name')
const headingSpan = this.element.querySelector('.heading')
const alphaSpan = this.element.querySelector('.alpha')
const betaSpan = this.element.querySelector('.beta')
const gammaSpan = this.element.querySelector('.gamma')
if (eventName) eventName.textContent = event?.type || ''
if (headingSpan) headingSpan.textContent = `${heading || ''}`
if (alphaSpan) alphaSpan.textContent = `${event?.alpha || ''}`
if (betaSpan) betaSpan.textContent = `${event?.beta || ''}`
if (gammaSpan) gammaSpan.textContent = `${event?.gamma || ''}`
if (eventName) eventName.textContent = event?.originalEvent.type || ''
if (headingSpan) headingSpan.textContent = `${event?.heading || ''}`
if (alphaSpan) alphaSpan.textContent = `${event?.originalEvent.alpha || ''}`
if (betaSpan) betaSpan.textContent = `${event?.originalEvent.beta || ''}`
if (gammaSpan) gammaSpan.textContent = `${event?.originalEvent.gamma || ''}`
}
}
139 changes: 139 additions & 0 deletions src/core/Compass.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
export type CompassEvent = {
heading: number | undefined
originalEvent: WebkitDeviceOrientationEvent
}

export type CompassError = {
code: 'TIMEOUT' | 'PERMISSION_DENIED'
message: string
}

// https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent
export type WebkitDeviceOrientationEvent = DeviceOrientationEvent & {
webkitCompassHeading?: number
webkitCompassAccuracy?: number
}

export class Compass {
private static readonly eventTypes = ['deviceorientation', 'error'] as const
private deviceOrientationCallback: ((event: CompassEvent) => void) | undefined
private errorCallback: ((error: CompassError) => void) | undefined
private isListening = false

on(
type: (typeof Compass.eventTypes)[number],
callback: ((event: CompassEvent) => void) | ((error: CompassError) => void),
) {
if (!Compass.eventTypes.includes(type)) {
throw new Error(`Event type ${type} is not supported.`)
}
switch (type) {
case 'deviceorientation':
this.deviceOrientationCallback = callback as (
event: CompassEvent,
) => void
break
case 'error':
this.errorCallback = callback as (error: CompassError) => void
break
}
}

turnOn() {
if (this.isListening) {
return
}
this.addDeviceOrientationListener()
this.addDeviceOrientationAbsoluteListener()
this.isListening = true
}

turnOff() {
this.removeDeviceOrientationListener()
this.removeDeviceOrientationAbsoluteListener()
this.isListening = false
}

private addDeviceOrientationListener() {
// For iOS 13 and later
// refs: https://developer.mozilla.org/en-US/docs/Web/API/DeviceOrientationEvent#browser_compatibility
if ('requestPermission' in window.DeviceOrientationEvent) {
// @ts-ignore
window.DeviceOrientationEvent.requestPermission()
.then((response: string) => {
if (response !== 'granted') {
this.handleError('PERMISSION_DENIED', 'Permission denied')
return
}
window.addEventListener(
'deviceorientation',
this.onDeviceOrientation,
true,
)
})
.catch(() => this.handleError('PERMISSION_DENIED', 'Permission denied'))
return
}
window.addEventListener('deviceorientation', this.onDeviceOrientation, true)
}

private removeDeviceOrientationListener() {
window.removeEventListener(
'deviceorientation',
this.onDeviceOrientation,
true,
)
}

private addDeviceOrientationAbsoluteListener() {
window.addEventListener(
'deviceorientationabsolute',
this.onDeviceOrientation,
true,
)
}

private removeDeviceOrientationAbsoluteListener() {
window.removeEventListener(
'deviceorientationabsolute',
this.onDeviceOrientation,
true,
)
}

private onDeviceOrientation = (event: WebkitDeviceOrientationEvent) => {
if (event.type === 'deviceorientationabsolute' && event.alpha != null) {
this.removeDeviceOrientationListener()
} else if (
event.type === 'deviceorientation' &&
event.webkitCompassHeading != null
) {
this.removeDeviceOrientationAbsoluteListener()
}

if (this.deviceOrientationCallback) {
this.deviceOrientationCallback({
heading: this.calculateCompassHeading(event),
originalEvent: event,
})
}
}

private calculateCompassHeading(event: WebkitDeviceOrientationEvent) {
if (event.webkitCompassHeading != null) {
return event.webkitCompassHeading
}
if (event.alpha == null) {
return undefined
}
let compassHeading = 360 - event.alpha
if (compassHeading < 0) {
compassHeading += 360
}
return compassHeading
}

private handleError(code: 'TIMEOUT' | 'PERMISSION_DENIED', message: string) {
this.errorCallback?.({ code, message })
}
}
Loading
Loading