Mapbox Map
Overview
A Mapbox GL JS map with a single pin, placed by looking up an address or by hand. The map is created only once it comes near the viewport, since every map created counts as a map load with Mapbox.
- Block name:
method/mapbox-map - Title: Mapbox Map (Method)
- Category:
method-component-blocks - Supports:
align(wide, full);htmloff - Render type: Dynamic (PHP
render_callback:render_method_mapbox_map_block()) - Inner blocks: No
- Scripts:
editorScript(index.js) andviewScript(frontend.js, which depends on themapbox-glscript handle) - Source: lib/blocks/method-mapbox-map/method-mapbox-map.php, lib/blocks/method-mapbox-map/src/edit.js, lib/blocks/method-mapbox-map/src/frontend.js, lib/blocks/utils/mapbox.js
Usage
The block needs a Mapbox access token and a pin; without both it prints nothing. The token is the one the site shares, if any: a child theme can return one through the method_mapbox_token filter (as the cmb2-mapbox / method-tec-mapbox integration does), or cmb2-mapbox’s token is read from Method’s options when its cmb2_mapbox_use_method switch is on. Only when the site shares no token does the block ask for one of its own, in a canvas placeholder and in the Map panel, and it warns when the token is not a public pk. token — the only kind a browser may use.
Place the pin in the Pin panel by typing an Address and choosing Find on map (or pressing Enter): the best match is placed at once and up to four alternatives are offered. The pin can also be placed by clicking the map while the block is selected, dragged on the map, or typed in as Latitude / Longitude. Choose a Style (or a custom style URL), the Initial zoom, whether the map shows Zoom buttons and uses Cooperative gestures, and the map’s height, minimum height or aspect ratio per breakpoint. The block toolbar has Center map on pin.
Attributes
| Attribute | Type | Default | Description |
|---|---|---|---|
accessToken | string | "" | The block’s own token, used only when the site shares none (method_mapbox_get_block_token()). |
address | string | "" | The text typed into the Address field. |
geocodedAddress | string | "" | The matched address of a looked-up location, for the panel’s status text and the map’s label; cleared when the pin is moved by hand. |
lng | number | — | Pin longitude, stored to six decimals. Validated on render (method_mapbox_get_pin()): a missing or out-of-range pair means no pin, and no map. |
lat | number | — | Pin latitude. |
zoom | number | 14 | Initial zoom, 0–22, decimals allowed; clamped on render. The map opens centered on the pin. |
mapStyle | string | "standard" | A key of method_mapbox_get_styles() — standard, standard-satellite, streets-v12, outdoors-v12, light-v11, dark-v11, satellite-v9, satellite-streets-v12, navigation-day-v1, navigation-night-v1 — or custom. |
customStyleUrl | string | "" | With mapStyle = custom: a mapbox://styles/… URL from Mapbox Studio or an https:// link to a style JSON. Until it is valid the Standard style is used (method_mapbox_resolve_style()). |
pinColor | string | — | Marker color; Mapbox’s default blue when unset. Passed through method_sanitize_theme_color(). |
pinScale | number | 1 | Marker size, 0.5–3 (1 is Mapbox’s default 41px marker); clamped on render. |
popupText | string | "" | Plain text shown in a popup when the pin is clicked (tags stripped). Also the first choice for the map’s accessible label. |
showNavigation | boolean | true | Zoom and compass controls in the top-left corner. |
cooperativeGestures | boolean | true | Scroll only zooms with Ctrl / Cmd held, and touch needs two fingers to pan, so the page keeps scrolling over the map. The editor preview always behaves this way. |
responsiveSettings | object | {"base":{"enabled":true,"height":"400px"},…} | Per-tier size, spacing, border and shadow; see below. |
responsiveSettings Structure
Per-tier settings live under responsiveSettings.base, mobile, tablet and wide. A tier is only read while its enabled flag is true; base is always on. The keys this block’s CSS map reads:
height,minHeight,aspectRatio(emitted asaspectRatioDimension) — the map’s size; new blocks start atheight: 400px. The preview resizes the map when the generated height changes.margin.top,margin.bottom.border,borderRadius.shadows— base only (MethodShadowControl).
Control Sets
| Component | Panel | Breakpoints | Notes |
|---|---|---|---|
| Block toolbar | — | — | Center map on pin. |
| Block panel: Map | Map | base | Access token (only while the site shares none), Style, Style URL (for Custom), Initial zoom, Zoom buttons, Cooperative gestures. |
| Block panel: Pin | Pin | base | Address with Find on map and the alternative matches, Latitude, Longitude, Remove pin, Pin size (the help text shows the resulting marker height), Popup text. |
MethodDimensionControls | Dimensions | base + mobile / tablet / wide | include={['height', 'minHeight', 'aspectRatio']} |
MethodSpacingControls | Spacing | base + mobile / tablet / wide | include={['margin']}, top and bottom. |
MethodBorderControls | Border | base + mobile / tablet / wide | Border and radius. |
MethodShadowControl | Shadow | base | Multi-layer box shadow. |
MethodColorControls | Color Settings | base | include={[]} with one extra setting, Pin → pinColor — the only color control the block has. |
MethodResponsiveTabs | Mobile / Tablet / Ultrawide | mobile, tablet, wide | Dimensions, spacing and border per tier. |
MethodStyleTag | — | all | Mirrors $cssargs in the canvas. |
Data & Dependencies
- Mapbox GL JS v3.23.1 from
api.mapbox.com, registered asmapbox-gl— the handle cmb2-mapbox and method-tec-mapbox already use, so the library never loads twice on a page. It is registered when a map renders (method_mapbox_enqueue_gl()), not oninit: cmb2-mapbox enqueues it into the admin head with inline scripts that need it there, which an earlier footer registration of the same handle would move. The block’s view script is givenmapbox-glas a dependency at registration. In the editor the library is loaded into the canvas iframe the first time a map block needs it (loadMapboxGl()); a failed load offers Retry, and a rejected token is reported over the map. - Shared runtime (lib/blocks/utils/mapbox.js) —
createMethodMap( mapboxgl, container, config )returns an instance withsetStyle,setNavigation,setPinandremove, so the editor preview updates in place rather than rebuilding; the style, zoom, coordinate and pin-scale helpers mirror their PHP counterparts;popupOffset()andgeocodeAddress()(Mapbox Geocoding API v6, editor only). - PHP helpers (lib/blocks/method-mapbox-map/method-mapbox-map.php) —
method_mapbox_get_site_token(),method_mapbox_get_block_token(),method_mapbox_get_styles(),method_mapbox_is_style_url(),method_mapbox_resolve_style(),method_mapbox_get_pin(),method_mapbox_get_map_config(). The editor receives the site token, the style list and the library URLs asmethodMapboxData. - Lazy creation: the view script watches every
.method-mapbox-map[data-map]with anIntersectionObserver(rootMargin: 200px) and creates the map on first approach; without the observer every map is created at once. A created container getsdata-map-ready. - Event: once a map is created a
method:mapbox-mapevent bubbles from its container with the runtime instance ({ map, marker, mapboxgl, … }) asdetail, for scripts that add to the map. - Styles (assets/scss/global.scss) — the wrapper is
position: relative; overflow: hiddenwith a 120px minimum height and a faint background so a map whose height was reset still shows something; the canvas fills it. - Responsive CSS:
method_get_block_responsive_styles()andmethod_collect_css()under#method-{id}.
Frontend Rendering
<div class="wp-block-method-mapbox-map method-mapbox-map" id="method-68f1b2c3a4d5e" role="region" aria-label="Map of Big Spring Park" data-map='{"token":"pk.…","style":"mapbox://styles/mapbox/standard","center":[-86.586812,34.729512],"zoom":14,"pin":{"lng":-86.586812,"lat":34.729512,"scale":1,"popup":"Big Spring Park","color":"#d17c28"},"navigation":true,"cooperativeGestures":true}'>
<div class="method-mapbox-map-canvas"></div>
</div>
The aria-label is “Map of …” from the popup text or, failing that, the looked-up address; with neither it is “Map”. The config in data-map (printed with its quotes escaped by get_block_wrapper_attributes(); shown unescaped here) is what method_mapbox_get_map_config() returns after the method_mapbox_map_config filter; pin.color is only present when a color is set. Generated CSS (per instance): #method-{id} → height, min-height, aspect ratio, margins, radius, border, shadow.
Adding to a map from a child theme:
document.addEventListener( 'method:mapbox-map', ( event ) => {
const { map, marker, mapboxgl } = event.detail;
map.on( 'load', () => {
map.addSource( 'parking', { type: 'geojson', data: '/wp-content/uploads/parking.geojson' } );
map.addLayer( { id: 'parking', type: 'fill', source: 'parking', paint: { 'fill-color': '#2b9d9a', 'fill-opacity': 0.3 } } );
} );
} );
Filters
| Hook | Type | Arguments | Description |
|---|---|---|---|
method_mapbox_token | Filter | string $token | The access token the whole site shares. Checked first by method_mapbox_get_site_token(), before cmb2-mapbox’s option. While a token is returned the block never shows its own token field. |
method_mapbox_map_styles | Filter | array $styles | The styles the Style option offers: key => [ label, url ]. Keys are what mapStyle stores. |
method_mapbox_map_config | Filter | array $config, array $block_attributes | The map config before it is printed in data-map: token, style, center, zoom, pin, navigation, cooperativeGestures. |
add_filter( 'method_mapbox_token', fn() => 'pk.your-public-token' );
add_filter( 'method_mapbox_map_styles', function ( array $styles ) {
$styles['brand'] = array(
'label' => 'Brand',
'url' => 'mapbox://styles/your-account/cl1234567890',
);
return $styles;
} );
// Open every map a little further out than the block asks for.
add_filter( 'method_mapbox_map_config', function ( array $config ) {
$config['zoom'] = max( 0, $config['zoom'] - 1 );
return $config;
} );
Changelog
| Version | Description |
|---|---|
| 2.0.0-beta27 | Introduced (fddeba0). |