Skip to content

PHP Example

Using the MapTrip Server API requires nothing but a method to send HTTP requests and to handle JSON data. This tutorial shows how to use the API from PHP code with a simple example:

Assume you have two addresses and you want to know how far it is from one of them to the other and how long it takes to go there by car.

This can be done by calculating a route with the endpoint [GET] /route of the MapTrip Server API (see endpoint and tutorial). This takes two coordinates as input, so you first have to find the coordinates for the addresses with the endpoint [GET] /geocoder. And as the API authentication is based on JWT, we will need the endpoint [GET] /authenticate as well.

Obtaining a JWT Token

If you already have a MapTrip user account, you can use the endpoint [POST] /authenticate to obtain a token to use the API.

The request is sent in the highlighted section. As this endpoint uses the HTTP method POST, we use the PHP function "file_get_contents" with a special "context" filled with following arguments:

  • the URL of the endpoint
  • the data to send (a JSON object with user and password)
  • two headers indicating that the format of the message body and the expected response format are JSON
<?php
$user = 'user@example.org';
$password = 'secret';


function getToken()
{
    global $user, $password;
    $url = "https://api.maptrip.de/v1/authenticate";
    $content = '{"user": "' . $user . '", "password": "' . $password . '"}'; 

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => 'Content-Type: application/json\r\nAccept: application/json\r\n',
            'method'  => 'POST',
            'content' => $content
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);
    if ($result === FALSE)
    { /* Handle error */ 
      return FALSE;  
    }

    $token = json_decode($result, false)->token;
    return $token;
?>

For correct user data this will obtain a new token. If you do not change the credentials the function will return FALSE as the API will return the HTTP status code 401 Unauthorized.

For the following demos we will use a free demo token:

<?php
    $token = file_get_contents("https://api.maptrip.de/token/demo");
?>

Geocoding an Address

For this example, we are not interested in the address found during geocoding and its quality, but only in the coordinate. The following function sends a string with an address to the endpoint [GET] /geocoder and checks if the request was successful. If so, this is returned, otherwise the value FALSE. The API will return the found address as a json string.

The request looks very similar to the first one, but this is a GET request, so there is no message body but parameters. For this reason, no Content-Type needs to be specified. Instead, the request must contain the header Authorization with the word Bearer and the token we queried before.

<?php
function geocode($address)
{
    global $token;
    //echo $token;
    $params = http_build_query(array('provider' => 'TomTom',
                                     'address' => $address));

    $options = array(
        'http' => array(
            'header'  => 'Accept: application/json\r\nAuthorization: Bearer ' . $token . '\r\n',
            'method'  => 'GET'
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents("https://api.maptrip.de/v1/geocoder/?".$params, false, $context);
    if ($result === FALSE)
    { /* Handle error */ 
      return FALSE;  
    }
    return $result;
}
?>

To test the function you can call it with an address string and parse the returned json string to get the coordinate:

<?php
$test = geocode("Weiherstr. 38, Bonn");
$arr = json_decode($test, false);
echo $arr[0]->address->coordinate->lat . " / " . $arr[0]->address->coordinate->lon;
?>
50.7365574 / 7.0919497

Calculating a Route

This is the most simple kind of route you can calculate: We do not use via points, traffic information, vehicle types and attributes and so on, just the start and destination.

As the coordinates for the parameters from and to have to be provided as strings, we use a helper class to format them.

<?php
class Coordinate
{
    protected $lat;
    protected $lon;

    public function __construct($lat, $lon)
    {
        $this->lat = $lat;
        $this->lon = $lon;
    }
    public function getLatitude()
    {
        return $this->lat;
    }
    public function getLongitude()
    {
        return $this->lon;
    }
    public function toString()
    {
        return strval($this->lat).",".strval($this->lon);
    }
}

function route(Coordinate $start, Coordinate $destination)
{
    global $token;

    $params = http_build_query(array('provider' => 'TomTom',
                                     'from' => $start->toString(),
                                     'to' => $destination->toString()));

    $options = array(
        'http' => array(
            'header'  => "Accept: application/json\r\nAuthorization: Bearer " . $token . "\r\n",
            'method'  => 'GET',
        )
    );
    $context  = stream_context_create($options);
    $result = file_get_contents("https://api.maptrip.de/v1/route/?".$params, false, $context);
    if ($result === FALSE)
    { /* Handle error */ 
      return FALSE;  
    }
    return $result;
}
?>

Putting all this together, we can write code to geocode two addresses, check if both were found, calculate a route between them, and output the desired output.

<?php
$st = geocode("Weiherstr. 38, Bonn");
$dest = geocode("Köln");

if ($st !== FALSE && $dest !== FALSE)
{
  $obj = json_decode($st, false);
  $start = new Coordinate(doubleval($obj[0]->address->coordinate->lat), doubleval($obj[0]->address->coordinate->lon));
  $obj = json_decode($dest, false);
  $destination = new Coordinate(doubleval($obj[0]->address->coordinate->lat), doubleval($obj[0]->address->coordinate->lon));

  $result = route($start, $destination);

  if ($result !== FALSE)
  {
    $obj = json_decode($result, false);

   if (count($obj) > 0)
    {
      $driving_time_in_seconds = $obj[0]->summary->drivingTime;
      $length_in_meter = $obj[0]->summary->length;
      $driving_time = sprintf("%.1f", $driving_time_in_seconds/60);
      $length =  sprintf("%.1f", $length_in_meter/1000);

      echo "Länge: ".$length.", Dauer: ".$driving_time;
    }
    else
    {
        echo "no route found!";
    }
  }
  else
  {
    echo "failed to calculate route!";
  }
}
else
{
  echo "failed to geocode addresses!";
}
?>
route length: 28.5, driving duration: 33.7