Skip to content

Commit

Permalink
fixed clearing map features on map style switching (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
zdila authored May 13, 2024
1 parent a13940a commit 7237ca1
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 10 deletions.
4 changes: 2 additions & 2 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@maptiler/geocoding-control",
"version": "1.2.3",
"version": "1.2.4",
"description": "The Javascript & TypeScript Map Control component for MapTiler Geocoding service. Easy to be integrated into any JavaScript mapping application.",
"type": "module",
"author": {
Expand Down
29 changes: 22 additions & 7 deletions src/maplibregl-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,15 +70,20 @@ export function createMapLibreGlMapController(

let reverseMarker: maplibregl.Marker | undefined;

let savedData: GeoJSON; // used to restore features on style switch

function addFullGeometryLayer() {
if (fullGeometryStyle?.fill || fullGeometryStyle?.line) {
if (
!map.getSource("full-geom") &&
(fullGeometryStyle?.fill || fullGeometryStyle?.line)
) {
map.addSource("full-geom", {
type: "geojson",
data: emptyGeojson,
});
}

if (fullGeometryStyle?.fill) {
if (!map.getLayer("full-geom-fill") && fullGeometryStyle?.fill) {
map.addLayer({
...fullGeometryStyle?.fill,
id: "full-geom-fill",
Expand All @@ -87,14 +92,18 @@ export function createMapLibreGlMapController(
});
}

if (fullGeometryStyle?.line) {
if (!map.getLayer("full-geom-line") && fullGeometryStyle?.line) {
map.addLayer({
...fullGeometryStyle?.line,
id: "full-geom-line",
type: "line",
source: "full-geom",
});
}

if (savedData) {
setData(savedData);
}
}

if (map.loaded()) {
Expand All @@ -105,6 +114,10 @@ export function createMapLibreGlMapController(
});
}

map.on("styledata", () => {
addFullGeometryLayer();
});

const handleMapClick = (e: MapMouseEvent) => {
eventHandler?.({
type: "mapClick",
Expand All @@ -131,6 +144,12 @@ export function createMapLibreGlMapController(
return new maplibregl.Marker({ element, offset: [1, -13] });
}

function setData(data: GeoJSON) {
savedData = data;

(map.getSource("full-geom") as GeoJSONSource)?.setData(data);
}

return {
setEventHandler(handler: undefined | ((e: MapEvent) => void)): void {
if (handler) {
Expand Down Expand Up @@ -196,10 +215,6 @@ export function createMapLibreGlMapController(
return;
}

function setData(data: GeoJSON) {
(map.getSource("full-geom") as GeoJSONSource)?.setData(data);
}

for (const marker of markers) {
marker.remove();
}
Expand Down

0 comments on commit 7237ca1

Please sign in to comment.