This recipe describes how to import the MapBox JS component into a UI Builder page. The described approach uses the Custom Code
codeless block that imports the component’s JavaScript and provides integration between the component’s code and codeless logic.
You can see the final result on the following page:
https://www.backendless.us/api/files/ui-builder/containers/default/index.html?page=mapbox
We will be using MapBox’s GL JS library documented at:
Let’s go:
-
The MapBox component uses the following CSS file:
https://api.mapbox.com/mapbox-gl-js/v2.5.0/mapbox-gl.css
The CSS file can be imported using the following recipe:
How to import an external CSS into a UI Builder pageHere’s the codeless logic rendering to import the CSS:
-
On the page where you will be rendering MapBox map, add the
Block
component and type inmap
in theAnchor
property:
IMPORTANT: whenever you need to assign an
id
to a<div>
that would render the component, use theAnchor
property. -
Return to the Page logic - we will be adding the logic to the
On Page Enter
event (the same event where we loaded the CSS). -
Add the
Custom Code
block to the event:
-
Click the gear icon for the
Custom Code
block and paste the following JavaScript code into the editor:const mapboxgl = await BackendlessUI.requireModule( "https://api.mapbox.com/mapbox-gl-js/v2.5.0/mapbox-gl.js" ) mapboxgl.accessToken = 'YOUR-MAPBOX-ACCESS-TOKEN-GOES-HERE'; const map = new mapboxgl.Map({ container: 'map', // container ID style: 'mapbox://styles/mapbox/streets-v11', // style URL center: [-74.5, 40], // starting position [lng, lat] zoom: 9 // starting zoom });
-
Make sure to substitute
YOUR-MAPBOX-ACCESS-TOKEN-GOES-HERE
with your own access token from MapBox. -
Click
SAVE AND CLOSE
. Your page is now ready to run and should render the MapBox map.
IMPORTANT: Take a look at the very first line in the Custom Code block:
const mapboxgl = await BackendlessUI.requireModule( "https://api.mapbox.com/mapbox-gl-js/v2.5.0/mapbox-gl.js" )
This is the line of code that loads the external JS library. The rest of the code comes directly from the MapBox tutorial.