Fill the style's center, zoom, bearing and pitch from the map (#2405)

Fixes #730.

The Style Settings modal now has a "Use current map view" button above
the Center field. It copies the map's current center, zoom, bearing and
pitch into the style, so you don't have to copy them from the URL hash
by hand.

To make bearing and pitch available, the MapLibre map now reports them
with center and zoom, and also reports after a rotate or pitch ends
(before, only `dragend` and `zoomend` did). The OpenLayers renderer
doesn't report bearing or pitch, so with it the button only fills center
and zoom.

Values are rounded before they go into the style: center to 5 decimals
(about 1 m), zoom to 2, bearing and pitch to 1. Without that the style
gets values like `2.1635000000000204`.

The Center field gets a `key` that changes each time the button is
clicked. `InputArray` only reads its value when it mounts, so it keeps
half-typed coordinates while you edit, but that also means it wouldn't
show a center set from outside. Remounting it on the button click shows
the new center and leaves normal typing alone.

**Before / after** (Style Settings):

| Before | After |
|---|---|
| <img
src="https://raw.githubusercontent.com/KhadeerBasha1232/maputnik/pr-assets/pr-730/before-style-settings.png"
width="400"> | <img
src="https://raw.githubusercontent.com/KhadeerBasha1232/maputnik/pr-assets/pr-730/after-style-settings.png"
width="400"> |

**Performance:** no measurable impact. The map calls the existing
`onChange` once more at the end of a rotate or pitch gesture, which is
the same work it already does after each drag and zoom.

## Launch Checklist

 - [x] Briefly describe the changes in this PR.
 - [x] Link to related issues: fixes #730.
- [x] Include before/after visuals or gifs if this PR includes visual
changes.
- [x] Write tests for all new functionality: `use current map view
copies the map's view into the style` in `modals.spec.ts` opens the map
at zoom 5, sets bearing 12 and pitch 30 in the form, clicks the button
and checks that the style has the map's center, zoom, bearing 0 and
pitch 0. It fails on `main`, and it also fails if the map doesn't report
bearing and pitch. A second test, `use current map view shows the map's
center in the form`, checks that the Center input shows the new value.
 - [x] Add an entry to `CHANGELOG.md` under the `## main` section.

Tested locally: `npm run lint` clean, `npx tsc --noEmit` clean, `npx
vitest run` (57 passed) and the full `npx playwright test` suite (222
passed). The first test fails on `main`, and also fails if I put back
`main`'s `MapMaplibreGl.tsx`.

Assisted-By: Claude Opus 5.5 (Claude Code). It helped write the change,
the test and this description. I've reviewed and tested the change and
can answer questions about it.
This commit is contained in:
SHAIK KHADEER BASHA authored and GitHub committed 2026-12-04 21:00:39 +02:00
1 parent 11c7daa2bb
commit f5bd7c6176
9 files changed
+93 -10

No files matched your search

+1
View File
@@ -15,6 +15,7 @@
- Set the min and max zoom of a PMTiles source, for example to overzoom past the last zoom level in the file
- Change a layer's type from the layer editor; properties the new type doesn't support are removed
- Add a "Line metrics" checkbox to GeoJSON sources, which `line-gradient` needs to render
- Add a "Use current map view" button to the style settings modal that fills center, zoom, bearing and pitch from the map
- _...Add new stuff here..._
### 🐞 Bug fixes
+1 -1
View File
@@ -366,7 +366,7 @@ describe("layer editor", () => {
test("should convert to an expression without crashing", async () => {
await when.makeExpression("circle-radius");
await then(get.element("[data-wd-key='spec-field-container:circle-radius'] .maputnik-expression-editor")).shouldBeVisible();
await then(get.expressionEditor("circle-radius")).shouldBeVisible();
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({
layers: [{ id, paint: { "circle-radius": ["interpolate", ["linear"], ["zoom"], 6, 5, 10, 5] } }],
});
+5 -5
View File
@@ -234,7 +234,7 @@ describe("layers list", () => {
await when.setValueToPropertyArray("spec-field:icon-padding", "5");
await when.makeExpression("icon-padding");
await then(get.element("[data-wd-key='spec-field-container:icon-padding'] .cm-content")).shouldContainText('"literal"');
await then(get.expressionEditor("icon-padding")).shouldContainText('"literal"');
});
describe("text-variable-anchor-offset", () => {
@@ -263,16 +263,16 @@ describe("layers list", () => {
test("should identify each anchor and offset by row and axis", async () => {
await when.addValueToPropertyArray("spec-field:text-variable-anchor-offset", "8");
await then(get.element("[data-wd-key='spec-field:text-variable-anchor-offset'] select[aria-label$='row 1 anchor']")).shouldBeVisible();
await then(get.element("[data-wd-key='spec-field:text-variable-anchor-offset'] input[aria-label$='row 2 X offset']")).shouldHaveValue("0");
await then(get.element("[data-wd-key='spec-field:text-variable-anchor-offset'] input[aria-label$='row 2 Y offset']")).shouldHaveValue("8");
await then(get.variableAnchorOffsetControl(1, "anchor")).shouldBeVisible();
await then(get.variableAnchorOffsetControl(2, "X offset")).shouldHaveValue("0");
await then(get.variableAnchorOffsetControl(2, "Y offset")).shouldHaveValue("8");
});
test("should remove an anchor row", async () => {
// the row's delete button shares the function stop's class
await when.deleteFunctionStop("text-variable-anchor-offset");
await then(get.element("[data-wd-key='spec-field:text-variable-anchor-offset'] select")).shouldNotExist();
await then(get.variableAnchorOffsetControl(1, "anchor")).shouldNotExist();
});
});
});
+12
View File
@@ -433,6 +433,18 @@ export class MaputnikDriver {
return "neither";
}),
/** The expression editor a spec field shows once its value is an expression. */
expressionEditor: (fieldName: string) =>
this.helper.get.elementByTestId("spec-field-container:" + fieldName).locator(".maputnik-expression-editor"),
/** One control of a text-variable-anchor-offset row, e.g. `(2, "X offset")`. Rows count from 1. */
variableAnchorOffsetControl: (row: number, control: "anchor" | "X offset" | "Y offset") =>
this.helper.get.elementByTestId("spec-field:text-variable-anchor-offset").getByLabel(`row ${row} ${control}`),
/** The longitude or latitude input of the Center field in the style settings modal. */
styleCenterInput: (axis: "longitude" | "latitude") =>
this.helper.get.elementByTestId("modal:settings").getByLabel("Center", { exact: true }).nth(axis === "longitude" ? 0 : 1),
spritePixel: (id: string, x: number, y: number) => this.helper.get.canvasPixel(`sprite-preview:${id}`, x, y),
canvas: () => this.helper.get.element("canvas"),
+25
View File
@@ -502,6 +502,31 @@ describe("modals", () => {
});
});
describe("when the map is at zoom 5", () => {
beforeEach(async () => {
await when.setStyle("geojson", 5);
await when.click("nav:settings");
await when.setValue("modal:settings.bearing", "12");
await when.setValue("modal:settings.pitch", "30");
});
test("use current map view copies the map's view into the style", async () => {
await when.click("modal:settings.view-from-map");
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({
center: [2.1635, 41.3805],
zoom: 5,
bearing: 0,
pitch: 0,
});
});
test("use current map view shows the map's center in the form", async () => {
await when.click("modal:settings.view-from-map");
await then(get.styleCenterInput("longitude")).shouldHaveValue("2.1635");
await then(get.styleCenterInput("latitude")).shouldHaveValue("41.3805");
});
});
test("sky and fog blends", async () => {
await when.setValue("modal:settings.sky-horizon-blend", "0.3");
await when.setValue("modal:settings.fog-ground-blend", "0.2");
+1 -1
View File
@@ -80,7 +80,7 @@ describe("sprite picker", () => {
test("keeps expressions in the existing expression editor", async () => {
await when.chooseSprite("green");
await when.makeExpression("icon-image");
await then(get.element("[data-wd-key='spec-field-container:icon-image'] .maputnik-expression-editor")).shouldBeVisible();
await then(get.expressionEditor("icon-image")).shouldBeVisible();
await then(get.styleFromLocalStorage()).shouldDeepNestedInclude({ layers: [{ id: "symbols", layout: { "icon-image": ["literal", "green"] } }] });
await then(get.elementByTestId("spec-field-input:icon-image")).shouldNotExist();
});
+5
View File
@@ -119,6 +119,8 @@ type AppState = {
lng: number,
lat: number,
},
bearing?: number,
pitch?: number,
_from: "map" | "app"
},
maplibreGlDebugOptions: Partial<MapOptions> & {
@@ -710,6 +712,8 @@ export class App extends React.Component<any, AppState> {
lng: number,
lat: number,
},
bearing?: number,
pitch?: number,
_from: "map" | "app"
}) => {
this.setState({
@@ -973,6 +977,7 @@ export class App extends React.Component<any, AppState> {
/>
<ModalSettings
mapStyle={this.state.mapStyle}
mapView={this.state.mapView}
onStyleChanged={this.onStyleChanged}
onChangeMetadataProperty={this.onChangeMetadataProperty}
isOpen={this.state.isOpen.settings}
+4 -2
View File
@@ -69,7 +69,7 @@ type MapMaplibreGlInternalProps = {
showOverdrawInspector?: boolean
}
replaceAccessTokens(mapStyle: StyleSpecification): StyleSpecification
onChange(value: {center: LngLat, zoom: number, _from: "map" | "app"}): unknown
onChange(value: {center: LngLat, zoom: number, bearing: number, pitch: number, _from: "map" | "app"}): unknown
} & WithTranslation;
type MapMaplibreGlState = {
@@ -174,7 +174,7 @@ class MapMaplibreGlInternal extends React.Component<MapMaplibreGlInternalProps,
const mapViewChange = () => {
const center = map.getCenter();
const zoom = map.getZoom();
this.props.onChange({center, zoom, _from: "map"});
this.props.onChange({center, zoom, bearing: map.getBearing(), pitch: map.getPitch(), _from: "map"});
};
mapViewChange();
@@ -257,6 +257,8 @@ class MapMaplibreGlInternal extends React.Component<MapMaplibreGlInternalProps,
map.on("dragend", mapViewChange);
map.on("zoomend", mapViewChange);
map.on("rotateend", mapViewChange);
map.on("pitchend", mapViewChange);
}
onLayerSelectById = (id: string) => {
+39 -1
View File
@@ -13,18 +13,32 @@ import { FieldColor } from "../FieldColor";
import { Modal } from "./Modal";
import { FieldJson } from "../FieldJson";
import { Block } from "../Block";
import { InputButton } from "../InputButton";
import { spec as fieldSpecAdditional } from "../../libs/field-spec-additional";
import type {OnStyleChangedCallback, StyleSpecificationWithId} from "../../libs/definitions";
type ModalSettingsInternalProps = {
mapStyle: StyleSpecificationWithId
mapView: {
zoom: number
center: {
lng: number
lat: number
}
bearing?: number
pitch?: number
}
onStyleChanged: OnStyleChangedCallback
onChangeMetadataProperty(...args: unknown[]): unknown
isOpen: boolean
onOpenToggle(): void
} & WithTranslation;
class ModalSettingsInternal extends React.Component<ModalSettingsInternalProps> {
class ModalSettingsInternal extends React.Component<ModalSettingsInternalProps, {viewFromMapCount: number}> {
state = {
viewFromMapCount: 0,
};
changeTransitionProperty(property: keyof TransitionSpecification, value: number | undefined) {
const transition = {
...this.props.mapStyle.transition,
@@ -133,6 +147,21 @@ class ModalSettingsInternal extends React.Component<ModalSettingsInternalProps>
this.props.onStyleChanged(changedStyle);
}
setViewFromMap = () => {
const {zoom, center, bearing, pitch} = this.props.mapView;
// Rounded so the style doesn't get values like 2.1635000000000204
const round = (value: number, digits: number) => +value.toFixed(digits);
const changedStyle: StyleSpecificationWithId = {
...this.props.mapStyle,
center: [round(center.lng, 5), round(center.lat, 5)],
zoom: round(zoom, 2),
};
if (bearing !== undefined) changedStyle.bearing = round(bearing, 1);
if (pitch !== undefined) changedStyle.pitch = round(pitch, 1);
this.props.onStyleChanged(changedStyle);
this.setState(({viewFromMapCount}) => ({viewFromMapCount: viewFromMapCount + 1}));
};
render() {
const metadata = this.props.mapStyle.metadata || {} as any;
const {t, onChangeMetadataProperty, mapStyle} = this.props;
@@ -223,7 +252,16 @@ class ModalSettingsInternal extends React.Component<ModalSettingsInternalProps>
onChange={(value) => onChangeMetadataProperty("maputnik:locationiq_access_token", value)}
/>
<InputButton
data-wd-key="modal:settings.view-from-map"
onClick={this.setViewFromMap}
>
{t("Use current map view")}
</InputButton>
{/* InputArray only reads its value on mount, so remount it to show a center set by the button */}
<FieldArray
key={this.state.viewFromMapCount}
label={t("Center")}
fieldSpec={latest.$root.center}
length={2}