<- Back

Show the path a Vehicle takes for a Trip on a Mapbox map

The Mobilitybox provides a MultiLineString GeoJSON for a Trip which describes the path that a vehicle takes on a map. With the help of Mapbox you can visualize it on a map. In this example the path is visualized as simple blue line on the map. Also the stops are shown and colorized based on their status (whether the vehicle has already passed them or not). Note: You need a valid Mapbox Access Token, which requires an account on www.mapbox.com

Demo

Code excerpt

          
            mapboxgl.accessToken = 'pk.eyJ1IjoidmVzcHV0aSIsImEiOiJja21kZTd2amgyazlpMm5udzFmYTE4MXVzIn0.bLiLrYNkqWfToUYz8Jz72A'; // please use your own Mapbox Access Token. 
var map = new mapboxgl.Map({
  container: 'map', // container ID
  style: 'mapbox://styles/mapbox/dark-v10', // style URL
  center: [6.77018, 51.40565], // starting position [lng, lat]
  zoom: 11.5 // starting zoom
});

jQuery(function($){
  const mobilitybox_access_token = '---LOGIN_OR_REGISTER_FOR_FREE_TO_INSERT_API_KEY_HERE---';

  const mobilitybox = new Mobilitybox(mobilitybox_access_token);
  mobilitybox.get_attributions().then((attributions)=>{
    $(".attributions").html(attributions.html);
  })

  mobilitybox.find_stations_by_name({query: "Duisburg Kalkweg"}).then((stations)=>{
    var station = stations[0];
    station.get_next_departures().then((departures)=>{
      var trip_id = departures.find((departure) => departure.line_name == "934" && departure.headsign == "Betr. Am Unkelstein").id

      mobilitybox.get_trip({id: trip_id}).then((trip)=>{
        window.trip = trip
        if(map.loaded){
          addTripToMap(trip)
        }else{
          map.on('load', function(){ addTripToMap(trip) })
        }
      });
    }, Date.now() + 25*60*1000);
  })
});

function addTripToMap(trip){
  const trip_feature = {
    'type': 'Feature',
    'properties': {},
    'geometry': trip.geojson
  };
  const station_feature_collection = {
    'type': 'FeatureCollection',
    'features': trip.stops.map(function(stop){
      return {
        'type': 'Feature',
        'properties': {
          'name': stop.station.name,
          'status': stop.status
        },
        'geometry': {
          'type': 'Point',
          'coordinates': [stop.station.position.longitude, stop.station.position.latitude]
        }
      }
    })
  };
  map.addSource("trip_path", {type: 'geojson', data: trip_feature});
  map.addSource("stations", {type: 'geojson', data: station_feature_collection});

  addTripMapLayer()
  addStationsMapLayer()

}

function addTripMapLayer(){
  map.addLayer({
    'id': 'trip_path_direction',
    'source': 'trip_path',
    'type': 'symbol',
    'layout': {
      'symbol-placement': 'line',
      'symbol-spacing': 50,
      'text-field': '→',
      'text-offset': [0, -0.1],
      'text-size': 20,
      'text-keep-upright': false
    },
    'paint': {
      'text-color': 'white',
      'text-halo-width': 1,
      'text-halo-color': 'black'
    }
  }, 'road-label');
  map.addLayer({
    'id': 'trip_path',
    'source': 'trip_path',
    'type': 'line',
    'paint': {
      'line-width': 3,
      'line-color': 'blue'
    }
  }, 'trip_path_direction');
  map.addLayer({
    'id': 'trip_path_background',
    'source': 'trip_path',
    'type': 'line',
    'paint': {
      'line-width': 5,
      'line-blur': 2,
      'line-color': 'white'
    }
  }, 'trip_path');
}

function addStationsMapLayer(){
  map.addLayer({
    'id': 'stations_label',
    'source': 'stations',
    'type': 'symbol',
    'layout': {
      'text-anchor': 'top',
      'text-size': 12,
      'text-offset': [0, 0.5],
      'text-field': ['get', 'name']
    },
    'paint': {
      'text-color': 'white',
      'text-halo-color': 'black',
      'text-halo-width': 1,
    }
  });
  map.addLayer({
    'id': 'stations_icon',
    'source': 'stations',
    'type': 'circle',
    'paint': {
      'circle-radius': 4,
      'circle-color': ['case',
        ['==', ['get', 'status'], 'future'], 'green',
        ['==', ['get', 'status'], 'current'], 'yellow',
        ['==', ['get', 'status'], 'past'], 'red',
        'gray'
      ]
    }
  }, 'stations_label');
  map.addLayer({
    'id': 'stations_icon_background',
    'source': 'stations',
    'type': 'circle',
    'paint': {
      'circle-radius': 7,
      'circle-color': 'black',
      'circle-blur': 1
    }
  }, 'stations_icon');
}
          
        

Full HTML-Code


<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>Show the path a Vehicle takes for a Trip on a Mapbox map</title>
		<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />

		<!-- CSS only -->
		<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
		
		<!-- JS, Popper.js, and jQuery -->
		<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
		<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
		<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
		<script src="https://unpkg.com/mobilitybox/dist/mobilitybox.min.js"></script>
		
		<!-- Mapbox GL JS -->
		<script src='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.js'></script>
		<link href='https://api.mapbox.com/mapbox-gl-js/v2.1.1/mapbox-gl.css' rel='stylesheet' />

		<style>
			body {
			  background-color: silver;
			  padding-bottom: 30px;
			}
			
			.attributions {
			  border-radius: 0 3px 0 0;
			  background-color: white;
			  border-left: 0;
			  border-bottom: 0;
			  padding: 5px;
			  font-size: 10px;
			}
		</style>
	</head>
	<body>
		<div class="map" id="map" style="width: 100%; height: 800px;"></div>
		<span class="fixed-bottom">
		  <span class="attributions border text-muted font-weight-light"></span>
		</span>

		<script type="text/javascript">
      mapboxgl.accessToken = 'pk.eyJ1IjoidmVzcHV0aSIsImEiOiJja21kZTd2amgyazlpMm5udzFmYTE4MXVzIn0.bLiLrYNkqWfToUYz8Jz72A'; // please use your own Mapbox Access Token. 
			var map = new mapboxgl.Map({
			  container: 'map', // container ID
			  style: 'mapbox://styles/mapbox/dark-v10', // style URL
			  center: [6.77018, 51.40565], // starting position [lng, lat]
			  zoom: 11.5 // starting zoom
			});
			
			jQuery(function($){
			  const mobilitybox_access_token = '---LOGIN_OR_REGISTER_FOR_FREE_TO_INSERT_API_KEY_HERE---';
			
			  const mobilitybox = new Mobilitybox(mobilitybox_access_token);
			  mobilitybox.get_attributions().then((attributions)=>{
			    $(".attributions").html(attributions.html);
			  })
			
			  mobilitybox.find_stations_by_name({query: "Duisburg Kalkweg"}).then((stations)=>{
			    var station = stations[0];
			    station.get_next_departures().then((departures)=>{
			      var trip_id = departures.find((departure) => departure.line_name == "934" && departure.headsign == "Betr. Am Unkelstein").id
			
			      mobilitybox.get_trip({id: trip_id}).then((trip)=>{
			        window.trip = trip
			        if(map.loaded){
			          addTripToMap(trip)
			        }else{
			          map.on('load', function(){ addTripToMap(trip) })
			        }
			      });
			    }, Date.now() + 25*60*1000);
			  })
			});
			
			function addTripToMap(trip){
			  const trip_feature = {
			    'type': 'Feature',
			    'properties': {},
			    'geometry': trip.geojson
			  };
			  const station_feature_collection = {
			    'type': 'FeatureCollection',
			    'features': trip.stops.map(function(stop){
			      return {
			        'type': 'Feature',
			        'properties': {
			          'name': stop.station.name,
			          'status': stop.status
			        },
			        'geometry': {
			          'type': 'Point',
			          'coordinates': [stop.station.position.longitude, stop.station.position.latitude]
			        }
			      }
			    })
			  };
			  map.addSource("trip_path", {type: 'geojson', data: trip_feature});
			  map.addSource("stations", {type: 'geojson', data: station_feature_collection});
			
			  addTripMapLayer()
			  addStationsMapLayer()
			
			}
			
			function addTripMapLayer(){
			  map.addLayer({
			    'id': 'trip_path_direction',
			    'source': 'trip_path',
			    'type': 'symbol',
			    'layout': {
			      'symbol-placement': 'line',
			      'symbol-spacing': 50,
			      'text-field': '→',
			      'text-offset': [0, -0.1],
			      'text-size': 20,
			      'text-keep-upright': false
			    },
			    'paint': {
			      'text-color': 'white',
			      'text-halo-width': 1,
			      'text-halo-color': 'black'
			    }
			  }, 'road-label');
			  map.addLayer({
			    'id': 'trip_path',
			    'source': 'trip_path',
			    'type': 'line',
			    'paint': {
			      'line-width': 3,
			      'line-color': 'blue'
			    }
			  }, 'trip_path_direction');
			  map.addLayer({
			    'id': 'trip_path_background',
			    'source': 'trip_path',
			    'type': 'line',
			    'paint': {
			      'line-width': 5,
			      'line-blur': 2,
			      'line-color': 'white'
			    }
			  }, 'trip_path');
			}
			
			function addStationsMapLayer(){
			  map.addLayer({
			    'id': 'stations_label',
			    'source': 'stations',
			    'type': 'symbol',
			    'layout': {
			      'text-anchor': 'top',
			      'text-size': 12,
			      'text-offset': [0, 0.5],
			      'text-field': ['get', 'name']
			    },
			    'paint': {
			      'text-color': 'white',
			      'text-halo-color': 'black',
			      'text-halo-width': 1,
			    }
			  });
			  map.addLayer({
			    'id': 'stations_icon',
			    'source': 'stations',
			    'type': 'circle',
			    'paint': {
			      'circle-radius': 4,
			      'circle-color': ['case',
			        ['==', ['get', 'status'], 'future'], 'green',
			        ['==', ['get', 'status'], 'current'], 'yellow',
			        ['==', ['get', 'status'], 'past'], 'red',
			        'gray'
			      ]
			    }
			  }, 'stations_label');
			  map.addLayer({
			    'id': 'stations_icon_background',
			    'source': 'stations',
			    'type': 'circle',
			    'paint': {
			      'circle-radius': 7,
			      'circle-color': 'black',
			      'circle-blur': 1
			    }
			  }, 'stations_icon');
			}
		</script>
	</body>
</html>