Introduction to Mapbox
Mapbox is a powerful mapping and location cloud platform that provides developers with APIs and SDKs to integrate custom maps, navigation, search, and other geo-spatial features into their applications.
Mapbox GL JS
Mapbox GL JS is a JavaScript library for interactive, customizable vector maps on the web.
Basic Map
mapboxgl.accessToken = 'YOUR_MAPBOX_ACCESS_TOKEN'; const map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11', center: [-74.5, 40], zoom: 9 });
Adding a Marker
const marker = new mapboxgl.Marker() .setLngLat([-74.5, 40]) .addTo(map);
Adding a Popup
const popup = new mapboxgl.Popup({ offset: 25 }) .setText('Construction on the Washington Monument began in 1848.') .setLngLat([-77.0353, 38.8895]) .addTo(map);
Drawing a GeoJSON Line
map.on('load', () => { map.addSource('route', { 'type': 'geojson', 'data': { 'type': 'Feature', 'properties': {}, 'geometry': { 'type': 'LineString', 'coordinates': [ [-122.48369693756104, 37.83381888486939], [-122.48348236083984, 37.83317489144141], [-122.48339653015138, 37.83270036637107] ] } } }); map.addLayer({ 'id': 'route', 'type': 'line', 'source': 'route', 'layout': {}, 'paint': { 'line-color': '#888', 'line-width': 8 } }); });
Geocoding API
Mapbox also offers a Geocoding API to search for places and addresses.
const geocodingUrl = 'https://api.mapbox.com/geocoding/v5/mapbox.places/Seattle.json?access_token=YOUR_MAPBOX_ACCESS_TOKEN'; fetch(geocodingUrl) .then(response => response.json()) .then(data => console.log(data));
Directions API
The Directions API provides routes for driving, cycling, or walking directions.
const directionsUrl = 'https://api.mapbox.com/directions/v5/mapbox/driving/-122.42,37.78;-77.03,38.91?steps=true&geometries=geojson&access_token=YOUR_MAPBOX_ACCESS_TOKEN'; fetch(directionsUrl) .then(response => response.json()) .then(data => console.log(data.routes));
Static Images API
This API creates static map images for use in emails or applications.
const staticMapUrl = 'https://api.mapbox.com/styles/v1/mapbox/streets-v11/static/-122.42,37.78,14.25,0,60/600x600?access_token=YOUR_MAPBOX_ACCESS_TOKEN';
Building an Application with Mapbox
Let’s create a simple application that showcases a map with markers, popups, and interactions.
Mapbox Interactive Map
In this guide, we’ve covered several Mapbox APIs and created a basic interactive map application. Mapbox offers powerful tools to enhance location-based experiences in your applications.
Hash: b6551d554a88c3813cb17be0b8ec18d19e51f2e2e6504967122f92f9cdc1b8ef