Display a map on a webpage
Initialize a map in an HTML element with Mapbox GL JS. See the example: https://docs.mapbox.com//mapbox-gl-js/example/simple-map/
by cheeaun
HTML
<script src="https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css">
<div id="map"></div>
CSS
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }
JavaScript
const styleURL = 'https://www.arcgis.com/sharing/rest/content/items/3e1a00aeae81496587988075fe529f71/resources/styles/root.json?f=json';
mapboxgl.accessToken = 'pk.eyJ1IjoiY2hlZWF1biIsImEiOiJja2prcTc1YW8wZ3BrMnpzMjNuYjY0OG13In0.ik6WPvf5osAWJqKvvEqqWQ';
function formatStyle(style, metadata) {
// ArcGIS Pro published vector services dont prepend tile or tileMap urls with a /
style.sources.esri = {
type: 'vector',
scheme: 'xyz',
tilejson: metadata.tilejson || '2.0.0',
format: (metadata.tileInfo && metadata.tileInfo.format) || 'pbf',
/* mapbox-gl-js does not respect the indexing of esri tiles
because we cache to different zoom levels depending on feature density, in rural areas 404s will still be encountered.
more info: https://github.com/mapbox/mapbox-gl-js/pull/1377
*/
// index: metadata.tileMap ? style.sources.esri.url + '/' + metadata.tileMap : null,
maxzoom: 15,
tiles: [
style.sources.esri.url + '/' + metadata.tiles[0]
],
description: metadata.description,
name: metadata.name
};
return style;
}
fetch(styleURL).then(res => res.json()).then(style => {
console.log({style});
const metadataURL = style.sources.esri.url;
fetch(metadataURL).then(res => res.json()).then(metadata => {
console.log({metadata});
const finalStyle = formatStyle(style, metadata);
const map = new mapboxgl.Map({
container: 'map',
style: finalStyle,
center: [-74.5, 40],
zoom: 9,
});
})
})