How to import the MapBox component into a UI Builder page

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:

  1. 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 page

    Here’s the codeless logic rendering to import the CSS:

  2. On the page where you will be rendering MapBox map, add the Block component and type in map in the Anchor property:

    IMPORTANT: whenever you need to assign an id to a <div> that would render the component, use the Anchor property.

  3. 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).

  4. Add the Custom Code block to the event:

  5. 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
    });
    
  6. Make sure to substitute YOUR-MAPBOX-ACCESS-TOKEN-GOES-HERE with your own access token from MapBox.

  7. 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.

1 Like

I have followed this recipe and sucessfully load the map.
For next step, how do I add geo points from Backendless database to mapbox map?