Generate an optimized route with the Optimization API
Use the Mapbox Optimization API to generate a duration-optimized route between several points. See the example: https://docs.mapbox.com//help/tutorials/optimization-api/
by jscastro76
HTML
<script src="https://npmcdn.com/@turf/turf/turf.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://api.tiles.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.js"></script>
<link rel="stylesheet" href="https://api.tiles.mapbox.com/mapbox-gl-js/v2.2.0/mapbox-gl.css">
<div id="map" class="contain"></div>
CSS
body {
margin: 0;
padding: 0;
}
#map {
position: absolute;
top: 0;
bottom: 0;
right: 0px;
left: 0px;
background: black;
}
.truck {
width: 20px;
height: 20px;
border: 2px solid #fff;
border-radius: 50%;
background: #3887be;
pointer-events: none;
}
JavaScript
var truckLocation = [-83.093, 42.376];
var warehouseLocation = [-83.083, 42.363];
var lastQueryTime = 0;
var lastAtRestaurant = 0;
var keepTrack = [];
var currentSchedule = [];
var currentRoute = null;
var pointHopper = {};
var pause = true;
var speedFactor = 50;
// Add your access token
mapboxgl.accessToken = 'PASTE HERE YOUR TOKEN';
// Initialize a map
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/light-v10', // stylesheet location
center: truckLocation, // starting position
zoom: 12 // starting zoom
});
var warehouse = turf.featureCollection([turf.point(warehouseLocation)]);
// Create an empty GeoJSON feature collection for drop off locations
var dropoffs = turf.featureCollection([]);
// Create an empty GeoJSON feature collection, which will be used as the data source for the route before users add any new data
var nothing = turf.featureCollection([]);
map.on('load', function () {
var marker = document.createElement('div');
marker.classList = 'truck';
// Create a new marker
truckMarker = new mapboxgl.Marker(marker)
.setLngLat(truckLocation)
.addTo(map);
// Create a circle layer
map.addLayer({
id: 'warehouse',
type: 'circle',
source: {
data: warehouse,
type: 'geojson'
},
paint: {
'circle-radius': 20,
'circle-color': 'white',
'circle-stroke-color': '#3887be',
'circle-stroke-width': 3
}
});
// Create a symbol layer on top of circle layer
map.addLayer({
id: 'warehouse-symbol',
type: 'symbol',
source: {
data: warehouse,
type: 'geojson'
},
layout: {
...