- Published on
- Updated on
- Updated on
How to Add XYZ Tile Layers to an ArcGIS API for JavaScript 3.x Map
This article teaches you how to create a simple ArcGIS API for JavaScript 3.x application with XYZ tile layers. You can use any of the layers on our categorized layer list to add to the application.
Here is a CodePen of the resulting application:
First, let's create an index.html
file:
<!DOCTYPE html>
<html>
<head>
<title>ArcGIS API for JavaScript 3.x - XYZ Tiles Demo</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1, user-scalable=no" />
<link rel="stylesheet" href="https://js.arcgis.com/3.39/esri/css/esri.css" />
<link rel="stylesheet" href="style.css" />
<script src="https://js.arcgis.com/3.39/"></script>
</head>
<body>
<div id="map"></div>
<script src="main.js"></script>
</body>
</html>
What's happening here:
- We include ArcGIS JS API CSS file on line 7.
- We include a CSS file on line 8 that we will create later.
- We include ArcGIS JS API JavaScript file on line 9.
- We create a container for the map on line 12, defining
'map'
as theid
(you can use anyid
you want). - We include a JavaScript file on line 13 that we will create later.
Now, let's create a style.css
file to style the map:
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
These rules will make our map appear full screen.
Finally, we'll create a main.js
file that will handle creating layers and adding them to the map:
require([
'esri/map',
'esri/layers/WebTiledLayer',
'dojo/domReady!'
], (Map, WebTiledLayer) => {
const map = new Map('map', {
center: [-1.5, 52.2],
zoom: 8
});
const cartoDBDarkMatter = new WebTiledLayer(
'https://{subDomain}.basemaps.cartocdn.com/dark_all/{level}/{col}/{row}.png', {
subDomains: ['a', 'b', 'c', 'd'],
copyright: '© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors © <a href="https://carto.com/attributions">CARTO</a>'
}
);
map.addLayer(cartoDBDarkMatter);
});
Let's break it down:
- As the ArcGIS JS API contains AMD modules, we have to reference the
map
andWebTiledLayer
modules in the require statement at the beginning of the file. We also usedojo/domReady!
to ensure the DOM is available before executing any code. - We initialize the map on lines 6-9 and set its view to our chosen geographical coordinates and zoom level (here we use coordinates for some place in England). We use
'map'
to refer to the map container that we added to the HTML file. - We define the tile layer on lines 11-16 (the highlighted part) and save it to a variable.
- Lastly, we add the created layer to the map.
You can pick any of the layers from our categorized layer list to add to your application. Just copy the code to create the layer in the preview application, paste it into your JavaScript file in place of the highlighted part and add the map.addLayer(layer)
command.