3.6 KiB
| layout | title | published |
|---|---|---|
| page | Display Map with Mapbox GL | true |
Display Map with Mapbox GL
To display a custom Mapbox GL based map you need to create a HTML file and reference the public vector tile CDN. You are free to download and host the vector tiles yourself but we provide a fast and distributed CDN service for serving the PBFs for you.
Clone example Repository
The easiest way to get started is using the mapbox-gl-js-exmaple repository.
Clone the repository and change into the directory.
git clone https://github.com/osm2vectortiles/mapbox-gl-js-example.git
Configure Source, Fonts and Sprites
In order for Mapbox GL JS to work you also need to provide the
fonts and
sprites.
These resources are contained in the folder assets.
The Mapbox GL Style JSON of OSM Bright is located at bright-v8.json.
You can create your own styles with Mapbox Studio.
If you want to serve the Mapbox GL Style JSON without Mapbox you need to configure three URLs.
- Change the
sourcesURL to the free CDN server or use your own server - Change the
spriteURL to the location of your sprites - Change the
glyphsURL to the location of your fonts
"sources": {
"mapbox": {
"url": "http://osm2vectortiles.tileserver.com/v1.json",
"type": "vector"
}
},
"sprite": "/assets/sprite",
"glyphs": "/assets/font/{fontstack}/{range}.pbf"
Initialize the Map
In order to serve a MapboxGL based map you need a Mapbox GL style JSON created with Mapbox Studio. In this example we will serve the free OSM Bright style provided by Mapbox.
The HTML file defines a full screen map and the CSS and JavaScript files required by Mapbox GL JS.
The bright-v8.json style is loaded from the local directory.
Because we use the local sprites and fonts we don't need a Mapbox API key.
{% highlight html %}
<html> <head> </head> </html> {% endhighlight %}Serve the Map
You need a simple HTTP server for serving the HTML and assets.
If you have Python installed you can run python -m SimpleHTTPServer
in the working directory and visit the map at localhost:8000.
If you have NodeJS installed you can install a simple http server with npm install http-server -g
and run it in the working directory with http-server and visit the map at localhost:8080.
Or if you are using Docker you can run a container serving the static files at localhost:8000
with docker run --rm -v $(pwd):/usr/share/nginx/html:ro -p 8000:80 nginx.
It is even possible to host the map on GitHub Pages.