A Developer's Guide to Using Custom Basemaps in Your Web Apps
Tags: javascript, webdev, programming, tutorial
Published: 2024-06-25 17:35:13

***Integrate your basemaps in Leaflet, MapLibre GL JS, ArcGIS JS maps, and More***

Over the past few months, I’ve demonstrated how to create custom vector basemap styles with [quick edit options](https://dev.to/c_yatteau/map-styling-for-web-developers-quick-editing-2bbh) and [advanced techniques](https://dev.to/c_yatteau/creative-map-styling-techniques-for-web-developers-25lc). Now, let’s take those custom basemaps and integrate them into different web mapping applications, including Leaflet, MapLibre GL JS, ArcGIS Maps SDK for JavaScript, and a self-hosted JSON example.

## Table of Contents
· [Steps](#steps)
· [ID](#id)
· [Leaflet](#leaflet)
· [MapLibre](#maplibre)
· [ArcGIS](#arcgis)
· [Hosting](#hosting)
· [Conclusion](#conclusion)

## Steps
#### Common Integration Steps

Regardless of the library you choose, the fundamental steps for integrating vector basemaps are consistent. You will typically need to:

* Include the necessary library files (CSS and JavaScript) in your project.

* Initialize a map object and set its view to a specific location and zoom level.

* Add a vector tile layer to the map, specifying the item ID and/or URL to your vector tile source.

## ID
#### Getting the Item ID of your Basemap

Before integrating your custom vector basemap into different mapping applications, you need to obtain the item ID from the ArcGIS Vector Tile Style Editor (VTSE). This item ID uniquely identifies your custom basemap and allows you to reference it in your mapping applications.

### Steps to Get the Item ID

 1. **Access the VTSE**: Go to the ArcGIS Vector Tile Style Editor and log in with your ArcGIS account.

 2. **Open a Custom Style**: Open your existing style that you have previously customized (or create and save a new one).

 3. **Save the Style**: If you created a new style or made any changes, be sure to save the style. After saving, a unique item ID is generated for your custom basemap.

 4. **Locate the Item ID**: The item ID can be found in the URL of the VTSE page.

With the item ID in hand, you are now ready to integrate your custom basemap into various mapping applications.

## Leaflet

The lightweight, open-source Leaflet library is easy to use and supports a wide range of plugins for added functionality. Whether you need to add complex features like heatmaps, marker clustering, or geolocation, there’s likely a plugin available that fits your needs.

Let’s look at how to use your custom basemap built with the VTSE in a Leaflet application.

    <html>
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
        <link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css" crossorigin="" />
        <script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js" crossorigin=""></script>
        <script src="https://unpkg.com/esri-leaflet@3.0.12/dist/esri-leaflet.js"></script>
        <script src="https://unpkg.com/esri-leaflet-vector@4.2.3/dist/esri-leaflet-vector.js"></script>
        <style>
          body {
            margin: 0;
            padding: 0;
          }
          #map {
            height: 100vh;
          }
        </style>
      </head>
      <body>
        <div id="map"></div>
        <script>
          const map = L.map("map").setView([38.9, -78.9], 4);
          L.esri.Vector.vectorBasemapLayer("YOUR_BASEMAP_ID", {
            apiKey: "YOUR_API_KEY"
          }).addTo(map);
        </script>
      </body>
    </html>

In this example, include the Leaflet CSS and JS files along with the Esri Leaflet and Esri Leaflet Vector JS files in the head of the file. Set the CSS styling for the body to have no predetermined margins or padding, and ensure the map takes up the entire page (100% of the view height). Next, in the HTML body, create a div where the map will be placed and give it an id value that you’ll reference in the JS section.

In the JS section, initialize the map with the L.map function from Leaflet, referencing the id value you created in your HTML div. Set the view to the desired location (latitude, longitude), and a zoom level between 1 and 19 (0 is world view and ~18 is max zoom). Finally, use the vector basemap layer plugin from Esri Leaflet with the basemap ID or your custom basemap and an ArcGIS API Key, which you can get by signing up for free [here](https://developers.arcgis.com/sign-up).

![Custom “popcorn” basemap in a Leaflet map](https://cdn-images-1.medium.com/max/2396/1*MkcDqwglX93BkVuTExEsZw.png)

## MapLibre
#### MapLibre GL JS

MapLibre GL JS is an open-source fork of Mapbox GL JS. It provides robust support for vector tiles and offers powerful capabilities for rendering interactive maps using WebGL. Additionally, it is particularly suited for applications requiring high performance and detailed, interactive maps.

Let’s look at how to use your custom basemap built with the VTSE in a MapLibre GL JS application.

    <html>
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no" />
        <script src=https://unpkg.com/maplibre-gl@4.0.0/dist/maplibre-gl.js></script>
        <link href=https://unpkg.com/maplibre-gl@4.0.0/dist/maplibre-gl.css rel="stylesheet" />
        <style>
          body {
            margin: 0;
            padding: 0;
          }
          #map {
            height: 100vh;
          }
        </style>
      </head>
      <body>
        <div id="map"></div>
        <script>
          const map = new maplibregl.Map({
            container: "map",
            zoom: 4,
            center: [-78.5, 38.9],
            style: `https://basemapstyles-api.arcgis.com/arcgis/rest/services/styles/v2/styles/items/YOUR_BASEMAP_ID?token=YOUR_API_KEY`        
          });
        </script>
      </body>
    </html>

Just like in Leaflet, the first few steps are the same. The setup for MapLibre GL JS involves including the necessary CSS and JS files, setting the CSS for the body, and then creating a div with an id for the map.

In the JS section, initialize a MapLibre GL JS map using the maplibregl.Map instance. Set its container to the HTML id value, its zoom level to a value between 0 and 24, and its center to the longitude and latitude you wish to position the map over. Finally, set its style to a vector tile style URL with your custom basemap ID and your API key attached at the end.

![Custom “bubblegum” basemap in a MapLibre GL JS map](https://cdn-images-1.medium.com/max/2650/1*mxJ9dixW3ip4eEWtsoWXvw.png)

## ArcGIS
#### ArcGIS Maps SDK for JavaScript

ArcGIS Maps SDK for JavaScript, formerly known as ArcGIS API for JavaScript, is a toolkit that lets you develop web applications with maps. It provides tools to create interactive 2D and 3D maps, conduct spatial analysis, and integrate with other ArcGIS services. You can use it to visualize your data and build informative mapping experiences.

Let’s look at how to use your custom basemap built with the VTSE in an ArcGIS Maps SDK for JS application.

    <html>
      <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
        <link rel="stylesheet" href="https://js.arcgis.com/4.29/esri/themes/light/main.css">
        <script src="https://js.arcgis.com/4.29/"></script>
        <style>
          body {
            margin: 0;
            padding: 0;
          }
          #map {
            height: 100vh;
          }
        </style>
        <body>
          <div id="map"></div>
        </body>
        <script>
          require([
            "esri/Map",
            "esri/views/MapView",
            "esri/Basemap",
            "esri/layers/VectorTileLayer",
          ], function (Map, MapView, Basemap, VectorTileLayer) {
            const view = new MapView({
              container: "map",
              center: [-100, 40],
              zoom: 3,
              map: new Map({
                basemap: new Basemap({
                  baseLayers: [
                    new VectorTileLayer({
                      portalItem: {
                        id: "YOUR_BASEMAP_ID"
                      }                
                    })
                  ]
                }),
              }),
            });
          });
        </script>
      </head>
    </html>

Again like with Leaflet and MapLibre GL JS, the starting setup for this map is basically the same. First, we include the ArcGIS Maps SDK for JavaScript CSS and JS files. Then set the CSS styling for the body to have no predetermined margins or padding and have the map take up the entire page (100% of the view height). Next, in the HTML body, create a div for where the map will be placed. Give it an id value that you’ll reference in the JS section.

In the JS section, unlike the open-source libraries, the setup is just a bit more involved. You’ll first need to require the modules needed which include Map, MapView, Basemap, and VectorTileLayer. The Map is the placeholder for what the map will hold, and the MapView is the general holder for everything visual about the map. In the MapView, we set the container (the HTML id value), the center (to a longitude, latitude), and the zoom level to a value as low as 0 and as high as anything around 22/23 (depending on the basemap detail).

Now, within the MapView, you set the map value. This is set by using the Basemap and VectorTileLayer together. Within the VectorTileLayer is where you reference your custom basemap id.

![Dark Navigation basemap in an ArcGIS Maps SDK for JS map](https://cdn-images-1.medium.com/max/2448/1*Nj2fK9TmZPATCkiU2vAS6g.png)

## Hosting
#### Self-Hosting and Using JSON in Another Mapping App

Now, each of the previous examples has required an ArcGIS API key. However, when creating your custom basemap style in the VTSE, you can take the JSON file and use it for free. Thus, if you prefer to host your own vector tile style, you can! You can access the JSON within the VTSE left-side button labeled “Edit JSON”. Once you click the “Edit JSON” button on the left side in the VTSE, you will be able to view and edit the JSON code for your map style. You can modify this directly if further customizations are needed. After making your changes, remember to save your edits. After editing, you’ll need to download the JSON style file. To do this, manually copy the JSON code into a text editor and save it with a .json extension.

Before uploading to the web, you’ll need to add a few additional things to the JSON style file, per Mapbox style specification as the file only contains the layers styles. Label the style array “layers”, then above this include the following code below.

    {
      "version": 8,
      "name": "Name your style",
      "metadata": {},
      "sources": {
        "source name": {
          "type": "vector",
          "url": "https://example.com/data/v3.json"
        }
      },
      "sprite": "https://example.com/sprites/sprite",
      "glyphs": "https://example.com/fonts/{fontstack}/{range}.pbf",
      "layers": [
          ...
      ]
    }

Next, host the style file on a web server to make it accessible for your applications. You could use cloud services like AWS S3, Google Cloud Storage, or even GitHub Pages, depending on your preferences and requirements. This step is crucial as the location of your JSON file will need to be referenced in the applications that use the map style.

To integrate the custom style into your mapping application, use the URL where your style file is hosted. This is done by specifying the style URL when setting up the map in most mapping libraries such as Leaflet or Mapbox GL JS. For instance, in MapLibre GL JS, you would set the style by providing the URL to the style property during the map initialization, as shown in the example above.

## Conclusion

Integrating vector basemaps into your web applications is a powerful way to enhance their visual appeal and functionality. By leveraging libraries like Leaflet, MapLibre GL JS, and ArcGIS Maps SDK for JavaScript, you can create highly interactive and customized maps tailored to your specific needs.

---

*This article was written by Courtney Yatteau, a Developer Advocate at [Esri](https://www.esri.com/en-us/home). The opinions in this article are solely Courtney’s opinions and do not necessarily represent the postings, strategies, or opinions of her employer. If you have any feedback, please like and/or comment. Also, if you have any questions or comments that you’d prefer to send privately, you can contact Courtney through [LinkedIn](https://www.linkedin.com/in/courtneyyatteau/), [Twitter](https://twitter.com/c_yatteau)*, *or [email](mailto:DeveloperOutreach@esri.com). If you’re considering a career switch, looking to get into tech, or curious about what it’s like to work at Esri, then please stay tuned for my future posts! You can also check out [Esri’s careers page](https://www.esri.com/en-us/about/careers/job-search) or [this video](https://youtu.be/nV4Ec_Qe4AQ) for more information.*