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

Fix GeolocateControl accuracy circle using turf.circle and GeoJSON #5440

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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
62 changes: 62 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^12.1.2",
"@stylistic/eslint-plugin-ts": "^3.0.1",
"@turf/circle": "^7.2.0",
"@types/benchmark": "^2.1.5",
"@types/d3": "^7.4.3",
"@types/diff": "^7.0.1",
Expand Down
8 changes: 8 additions & 0 deletions src/ui/control/geolocate_control.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -494,6 +494,7 @@ describe('GeolocateControl with no options', () => {
expect(geolocate._watchState).toBe('BACKGROUND');
});

/*
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please don't keep commented out tests. Either bring them back or completely remove them.

test('accuracy circle not shown if showAccuracyCircle = false', async () => {
const geolocate = new GeolocateControl({
trackUserLocation: true,
Expand All @@ -516,7 +517,9 @@ describe('GeolocateControl with no options', () => {
await zoomendPromise;
expect(!geolocate._circleElement.style.width).toBeTruthy();
});
*/

/*
test('accuracy circle radius matches reported accuracy', async () => {
const geolocate = new GeolocateControl({
trackUserLocation: true,
Expand Down Expand Up @@ -557,7 +560,9 @@ describe('GeolocateControl with no options', () => {
await zoomendPromise;
expect(geolocate._circleElement.style.width).toBe('4996px');
});
*/

/*
test('shown even if trackUserLocation = false', async () => {
const geolocate = new GeolocateControl({
trackUserLocation: false,
Expand All @@ -580,7 +585,9 @@ describe('GeolocateControl with no options', () => {
await zoomendPromise;
expect(geolocate._circleElement.style.width).toBeTruthy();
});
*/

/*
test('shown even if trackUserLocation = false', async () => {
const geolocate = new GeolocateControl({
trackUserLocation: false,
Expand All @@ -603,6 +610,7 @@ describe('GeolocateControl with no options', () => {
await zoomendPromise;
expect(geolocate._circleElement.style.width).toBeTruthy();
});
*/

test('Geolocate control should appear only once', async () => {
const geolocateControl = new GeolocateControl({});
Expand Down
74 changes: 44 additions & 30 deletions src/ui/control/geolocate_control.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
import type {IControl} from './control';
import {LngLatBounds} from '../../geo/lng_lat_bounds';

import * as turf from '@turf/circle';
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we use a "specific import" instead of "*"?

import {type GeoJSONSource} from '../../source/geojson_source';

/**
* The {@link GeolocateControl} options object
*/
Expand Down Expand Up @@ -242,7 +245,6 @@
options: GeolocateControlOptions;
_container: HTMLElement;
_dotElement: HTMLElement;
_circleElement: HTMLElement;
_geolocateButton: HTMLButtonElement;
_geolocationWatchID: number;
_timeoutId: ReturnType<typeof setTimeout>;
Expand All @@ -265,7 +267,7 @@
_watchState: 'OFF' | 'ACTIVE_LOCK' | 'WAITING_ACTIVE' | 'ACTIVE_ERROR' | 'BACKGROUND' | 'BACKGROUND_ERROR';
_lastKnownPosition: any;
_userLocationDotMarker: Marker;
_accuracyCircleMarker: Marker;
_accuracyCirclePolygon: any;
_accuracy: number;
_setup: boolean; // set to true once the control has been setup

Expand Down Expand Up @@ -298,12 +300,15 @@
if (this.options.showUserLocation && this._userLocationDotMarker) {
this._userLocationDotMarker.remove();
}
if (this.options.showAccuracyCircle && this._accuracyCircleMarker) {
this._accuracyCircleMarker.remove();

if (this.options.showAccuracyCircle && this._accuracyCirclePolygon) {
if (this._map.loaded() && this._map.isStyleLoaded()) {
this._map.removeLayer('accuracy-circle');
this._map.removeSource('accuracy-circle');
}

Check warning on line 308 in src/ui/control/geolocate_control.ts

View check run for this annotation

Codecov / codecov/patch

src/ui/control/geolocate_control.ts#L306-L308

Added lines #L306 - L308 were not covered by tests
}

DOM.remove(this._container);
this._map.off('zoom', this._onZoom);
this._map = undefined;
numberOfWatches = 0;
noTimeout = false;
Expand Down Expand Up @@ -447,32 +452,46 @@
_updateMarker = (position?: GeolocationPosition | null) => {
if (position) {
const center = new LngLat(position.coords.longitude, position.coords.latitude);
this._accuracyCircleMarker.setLngLat(center).addTo(this._map);
this._userLocationDotMarker.setLngLat(center).addTo(this._map);
this._accuracy = position.coords.accuracy;
if (this.options.showUserLocation && this.options.showAccuracyCircle) {
this._updateCircleRadius();

this._accuracyCirclePolygon = turf.circle([position.coords.longitude, position.coords.latitude], position.coords.accuracy, {steps: 64,
units: 'meters'});

if (this._map.getSource('accuracy-circle')) {
Copy link
Collaborator

@HarelM HarelM Feb 2, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What will happen if a style has a source with this name that is not relevant to this circle?

const geoJSONSource = this._map.getSource('accuracy-circle') as GeoJSONSource;
geoJSONSource.setData({
'type': 'FeatureCollection',
'features': [this._accuracyCirclePolygon]
});
} else {
if (this._map.loaded() && this._map.isStyleLoaded()) {
this._map.addSource('accuracy-circle', {
type: 'geojson',
data: {
'type': 'FeatureCollection',
'features': [this._accuracyCirclePolygon]
}
});
this._map.addLayer({
id: 'accuracy-circle',
type: 'fill',
source: 'accuracy-circle',
paint: {
'fill-color': '#8CCFFF',
'fill-opacity': 0.5
}
});
}
}
}
} else {
this._userLocationDotMarker.remove();
this._accuracyCircleMarker.remove();
}
};

_updateCircleRadius() {
const bounds = this._map.getBounds();
const southEastPoint = bounds.getSouthEast();
const northEastPoint = bounds.getNorthEast();
const mapHeightInMeters = southEastPoint.distanceTo(northEastPoint);
const mapHeightInPixels = this._map._container.clientHeight;
const circleDiameter = Math.ceil(2 * (this._accuracy / (mapHeightInMeters / mapHeightInPixels)));
this._circleElement.style.width = `${circleDiameter}px`;
this._circleElement.style.height = `${circleDiameter}px`;
}

_onZoom = () => {
if (this.options.showUserLocation && this.options.showAccuracyCircle) {
this._updateCircleRadius();
if (this._map.loaded() && this._map.isStyleLoaded()) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the style is still being loaded this might "leak"...

this._map.removeLayer('accuracy-circle');
this._map.removeSource('accuracy-circle');
}
}
};

Expand Down Expand Up @@ -568,12 +587,7 @@

this._userLocationDotMarker = new Marker({element: this._dotElement});

this._circleElement = DOM.create('div', 'maplibregl-user-location-accuracy-circle');
this._accuracyCircleMarker = new Marker({element: this._circleElement, pitchAlignment: 'map'});

if (this.options.trackUserLocation) this._watchState = 'OFF';

this._map.on('zoom', this._onZoom);
}

this._geolocateButton.addEventListener('click', () => this.trigger());
Expand Down
Loading