Skip to content

Javascript 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 Javascript 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 "XMLHttpRequest.open() function" with three parameters:

  • the "POST" parameter describing the HTTP method
  • the URL of the endpoint
  • FALSE, as we do not use async mode

To make the example simpler, we use synchronous server communication. In a real web site you would commit a callback function to "xhttp.onreadystatechange".

Also we set two request headers, indicating that the format of the message body and the expected response format are JSON.

The data to send to the server is a JSON object with user and password. It will be transmitted by the "send" function.

function getToken()
{
    var param = {"user" : "user@example.com", "password" : "secret"};
    var xhttp = new XMLHttpRequest();

    xhttp.open("POST", "https://api.maptrip.de/v1/authenticate/", false);
    xhttp.setRequestHeader("Accept", "application/json");
    xhttp.setRequestHeader("Content-Type", "application/json");
    xhttp.send(JSON.stringify(param));

    if (xhttp.readyState == 4 && xhttp.status == 200)
    {
        const obj = JSON.parse(xhttp.responseText);
        return obj.token;
    }
    else
    {
        console.log("could not obtain demo token!");
        return "";
    }
}

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

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

function getDemoToken()
{
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "https://api.maptrip.de/token/demo", false);
    xhttp.send();
    if (xhttp.readyState == 4 && xhttp.status == 200)
    {
        return xhttp.responseText;
    }
    else if (xhttp.readyState == 4 && xhttp.status != 200)
    {
        console.log("could not obtain demo token!");
        return "";
    }
}

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 an empty string. 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.

function geocode(address)
{
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "https://api.maptrip.de/v1/geocoder/?provider=TomTom&" + "address=" + encodeURIComponent(address), false);
    xhttp.setRequestHeader("Accept", "application/json");
    xhttp.setRequestHeader("Authorization", "Bearer " + demoToken);
    xhttp.send();
    if (xhttp.readyState == 4 && xhttp.status == 200)
    {
        return xhttp.responseText;
    }
    else
    {
        console.log("could not geocoder address!");
        return "";
    }
}

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

test = geocode("Weiherstr. 38, Bonn");
json = JSON.parse(test);
console.log(json[0].address.coordinate.lat + " / " + json[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.

function route(coord1, coord2)
{
    var xhttp = new XMLHttpRequest();
    xhttp.open("GET", "https://api.maptrip.de/v1/route/?provider=TomTom&limit=1&" + "from=" + coord1 + "&to=" + coord2, false);
    xhttp.setRequestHeader("Accept", "application/json");
    xhttp.setRequestHeader("Authorization", "Bearer " + demoToken);
    xhttp.send();
    if (xhttp.readyState == 4 && xhttp.status == 200)
    {
        return xhttp.responseText;
    }
    else if (xhttp.readyState == 4 && xhttp.status != 200)
    {
        console.log("an error occured while calling the routing server!");
        return "";
    }
}

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.

demoToken = getDemoToken();

start = geocode("Weiherstr. 38, Bonn");
dest = geocode("Köln");

if (start.length > 0 && dest.length > 0)
{
    json = JSON.parse(start);
    coord1 = json[0].address.coordinate.lat + "," + json[0].address.coordinate.lon;
    json = JSON.parse(dest);
    coord2 = json[0].address.coordinate.lat + "," + json[0].address.coordinate.lon;

    result = route(coord1, coord2);

    if (result.length > 0)
    {
        const obj = JSON.parse(result);
        if (obj.length > 0)
        {
            drivingtime = (parseInt(obj[0].summary.drivingTime) / 60).toFixed(0);
            routelength = (parseInt(obj[0].summary.length) / 1000).toFixed(1);
            console.log("route length: " + routelength + ", driving duration: " + drivingtime);
        }
        else
        {
            console.log("no route found!");
        }
    }
    else
    {
        console.log("failed to calculate route!");
    }
}
else
{
  console.log("failed to geocode addresses!");
}
route length: 28.5, driving duration: 33.7