Routing
In this guide you will learn how to request navigation instructions for a route, as well as statistics about the route.
Setup
First, get an API key token, see the Getting Started guide.
Routing entry point
URL: https://routes.magiclaneapis.com/v1
EXAMPLE
These are complete working examples in several different languages, showing how to use the REST API routing. You can try them right now.
- curl
- python3
- C
- D
- Julia
- Kotlin
- Groovy
- Scala
- Java
- JavaScript
- Go
- Dart
- Perl
- PHP
- R
- Ruby
- Rust
- Matlab
- Scilab
Linux terminal / Windows command prompt:
curl "https://routes.magiclaneapis.com/v1" -X POST -H "Content-Type: application/json" -H "Authorization: YOUR_API_KEY_TOKEN" -d @payload.json
Linux note - do not use @~/payload.json instead of @/home/user/payload.json
because ~
does not resolve due to the @
; use only relative path @payload.json
or absolute path @/home/user/payload.json
where
payload.json
is a text file containing the following:
complete minimal payload.json
file - 2 waypoints, the first for departure and the second for destination:
{
"transport": "bike",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"debug": true
}
complete payload.json
file - 2 waypoints, the first for departure and the second for destination; all default values shown explicitly - this json is equivalent to, and produces the same output as, the previous json above; no intermediate track version:
{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
}
complete minimal python route request - 2 waypoints, the first for departure and the second for destination: note that the debug
parameter is omitted, as the json is stored in the response variable, not printed directly, so formatting the json output is done locally by the json.dumps()
function instead;
import requests
import json
url = "https://routes.magiclaneapis.com/v1"
headers = {"Content-Type": "application/json", "Authorization": "YOUR_API_KEY_TOKEN" }
payload = {
"transport": "bike",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
}
response = requests.post(url, json=payload, headers=headers)
r = response.json()
print(json.dumps(r, indent=3))
route request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above; there are 2 waypoints, the first for departure and the second for destination; note that in python, True
and False
are case-sensitive; the json module is part of python, but the requests module may need to be installed (linux terminal: pip install requests
) no intermediate track request version:
import requests
import json
url = "https://routes.magiclaneapis.com/v1"
headers = {"Content-Type": "application/json", "Authorization": "YOUR_API_KEY_TOKEN" }
payload = {
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": False,
"hillskip": 0.5,
"emergency": False,
"debug": True,
"locale": "en"
}
response = requests.post(url, json=payload, headers=headers)
r = response.json()
print(json.dumps(r, indent=3))
This C example uses libcurl
which can be installed on Linux (debian/ubuntu flavors), for example, like this:
sudo apt install libcurl4-gnutls-dev
Save the following code in a text file named routing.c
using your favorite text editor, such as vi
or geany
, without the line numbers, those are only for reference:
complete route request in C
with all default values shown explicitly - there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
#include <curl/curl.h>
int main (int argc, char *argv[])
{
CURL *curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_ALL);
curl = curl_easy_init();
if (curl == NULL) { return 128; }
char* jsonObj = "{"
"\"transport\": \"bike\","
"\"type\": \"fastest\","
"\"waypoints\": [[2.24559,48.88562],[2.27670,48.77927]],"
"\"avoid\": [\"unpaved\",\"highway\"],"
"\"details\": \"full\","
"\"alternatives\": 0,"
"\"profile\": \"city\","
"\"terrain\": false,"
"\"hillskip\": 0.5,"
"\"emergency\": false,"
"\"debug\": true,"
"\"locale\": \"en\""
"}";
struct curl_slist *headers = NULL;
curl_slist_append(headers, "Content-Type: application/json");
curl_slist_append(headers, "Authorization: YOUR_API_KEY_TOKEN");
curl_easy_setopt(curl, CURLOPT_URL, "https://routes.magiclaneapis.com/v1");
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
curl_global_cleanup();
return res;
}
Compile the program - for example, on Linux, at the terminal/command prompt type:
gcc routing.c -lcurl -o routing
A binary executable named routing
is created which can be run like this to send the JSON POST request to the REST API endpoint, receive, and print the response:
./routing
To install D on Linux (debian/ubuntu flavors), at a terminal/command prompt type:
sudo apt install gdc
https://dlang.org/download.html
D can be downloaded for other platforms from this link
complete route request in D
with all default values shown explicitly - there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version - copy and paste this code in a text file named route.d
, without the line numbers - those are for reference:
import std.stdio;
import std.net.curl;
void main()
{
string payload = '{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
}';
auto http = HTTP();
http.addRequestHeader("Content-Type", "application/json");
http.addRequestHeader("Authorization", "YOUR_API_KEY_TOKEN");
auto content = post("https://routes.magiclaneapis.com/v1", payload, http);
writeln(content);
}
Compile the program - for example, on Linux, at the terminal/command prompt type:
gdc route.d -o route
A binary executable named route
is created which can be run like this to send the JSON POST request to the REST API endpoint, receive, and print the response:
./route
To install Julia on Linux (debian/ubuntu flavors), at a terminal/command prompt type:
sudo apt install julia
https://julialang.org/downloads/
Julia can be downloaded for other platforms from this link
To start Julia, type:
julia
To install the JSON and HTTP packages, at the Julia prompt type:
import Pkg; Pkg.add("JSON"); Pkg.add("HTTP")
complete route request in Julia
with all default values shown explicitly - there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version - copy and paste this code at the Julia prompt, without the line numbers - those are for reference:
using JSON, HTTP
req = """{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
}"""
ans = HTTP.request("POST", "https://routes.magiclaneapis.com/v1",
["Content-Type" => "application/json",
"Authorization" => "YOUR_API_KEY_TOKEN"], req);
str = String(ans.body);
print(str)
https://www.jetbrains.com/idea/download
The free IntelliJ IDEA Community Edition IDE can be downloaded from this link
Create a new kotlin
project in IntelliJ.
In your new kotlin project, browse to src
-> main
-> kotlin
-> Main.kt
Delete all the code in Main.kt
and replace it with the kotlin routing request code shown below: (without the line numbers - those are only for reference)
complete route request in kotlin
with all default values shown explicitly - there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
package kot.routing.post
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
fun main()
{
val request: String = """
{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
}"""
print(request)
val client = HttpClient.newBuilder().build();
val postrequest = HttpRequest.newBuilder()
.uri(URI.create("https://routes.magiclaneapis.com/v1"))
.header("Content-Type", "application/json")
.header("Authorization", "YOUR_API_KEY_TOKEN")
.POST(HttpRequest.BodyPublishers.ofString(request))
.build()
val response = client.send(postrequest, HttpResponse.BodyHandlers.ofString());
println(response.statusCode())
println(response.body())
}
Click the green triangle play button to compile and run the kotlin
routing request!
If there is a problem compiling because of a missing standard library, go in the menu to File->Project Structure
and in the left panel select Modules
and then in the right panel select the Dependencies
tab and make sure the [x] KotlinJavaRuntime
box is checked, then click Apply and OK, and run the example again.
https://www.jetbrains.com/idea/download
The free IntelliJ IDEA Community Edition IDE can be downloaded from this link
Create a new groovy
project in IntelliJ.
In your new groovy project, browse to src
-> Main.groovy
Delete all the code in Main.groovy
and replace it with the groovy routing request code shown below: (without the line numbers - those are only for reference)
complete route request in groovy
with all default values shown explicitly - there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
static void main(String[] args)
{
def post = new URL("https://routes.magiclaneapis.com/v1").openConnection();
def message = '''
{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
}
'''
post.setRequestMethod("POST")
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.setRequestProperty("Authorization", "YOUR_API_KEY_TOKEN")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if (postRC.equals(200)) {
println(post.getInputStream().getText());
}
}
Click the green triangle play button to compile and run the groovy
routing request!
https://www.jetbrains.com/idea/download
The free IntelliJ IDEA Community Edition IDE can be downloaded from this link
Create a new scala
project in IntelliJ.
If Language: Scala is not listed in the create new project dialog, click on + to the right of the listed languages and select Scala
to install the plugin, then restart intellij, create a new project and select Language: Scala.
In your new scala project, browse to the build.sbt
file and add this line:
libraryDependencies += "org.scalaj" % "scalaj-http_2.13" % "2.4.2"
Note - at the time of this writing, the latest scala version is 2.13
; the scalaVersion
you see in build.sbt must match the scalaj-http_2.13
version; if the scalaVersion
you see in build.sbt is newer than 2.13
, such as 2.18 for example, then go to
https://mvnrepository.com/artifact/org.scalaj/scalaj-http
to see the latest scalaj-http_2.18 version, such as 2.5.6 for example, and replace 2.4.2 with that version, as well as scalaj-http_2.13 with scalaj-http_2.18
A notification button appears within the window to the right - Load sbt Changes
- click this floating button to update.
In your new scala project, browse to src
-> Main.scala
Delete all the code in Main.scala
and replace it with the scala routing request code shown below: (without the line numbers - those are only for reference)
complete route request in scala
with all default values shown explicitly - there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
import scalaj.http.{Http, HttpOptions}
object Main
{
def main(args: Array[String]): Unit =
{
val request = s"""
{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
}
"""
val result = Http("https://routes.magiclaneapis.com/v1")
.header("Content-Type", "application/json")
.header("Authorization", "YOUR_API_KEY_TOKEN")
.header("Accept-Encoding", "text")
.postData(request)
.option(HttpOptions.method("POST"))
.option(HttpOptions.readTimeout(10000)).asString
println(result)
println(result.code)
}
}
Click the green triangle play button to compile and run the scala
routing request!
The java code shown has to be saved in a text file named JSONPostReq.java
and then compiled; at the commandline on either a Linux terminal or Windows command prompt type:
javac JSONPostReq.java
to compile the program making the json POST request to the Maps REST API, and then run it:
java JSONPostReq
complete minimal java route request - 2 waypoints, the first for departure and the second for destination:
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.IOException;
public class JSONPostReq
{
public static void main(String[] args) throws IOException
{
URL url = new URL("https://routes.magiclaneapis.com/v1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("Authorization","YOUR_API_KEY_TOKEN");
String payload = "{"
+"\"transport\": \"bike\","
+"\"waypoints\": [[2.24559,48.88562],[2.27670,48.77927]],"
+"\"avoid\": [\"unpaved\",\"highway\"],"
+"\"debug\": true"
+"}";
byte[] out = payload.getBytes(StandardCharsets.UTF_8);
OutputStream stream = connection.getOutputStream();
stream.write(out);
int responseCode = connection.getResponseCode();
System.out.println("response code: "+responseCode);
if (responseCode == HttpURLConnection.HTTP_OK)
{
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine.toString());
}
in.close();
}
connection.disconnect();
}
}
route request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above; there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.IOException;
public class JSONPostReq
{
public static void main(String[] args) throws IOException
{
try
{
URL url = new URL("https://routes.magiclaneapis.com/v1");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type","application/json");
connection.setRequestProperty("Authorization","YOUR_API_KEY_TOKEN");
String payload = "{"
+"\"transport\": \"bike\","
+"\"type\": \"fastest\","
+"\"waypoints\": [[2.24559,48.88562],[2.27670,48.77927]],"
+"\"avoid\": [\"unpaved\",\"highway\"],"
+"\"details\": \"full\","
+"\"alternatives\": 0,"
+"\"profile\": \"city\","
+"\"terrain\": false,"
+"\"hillskip\": 0.5,"
+"\"emergency\": false,"
+"\"debug\": true,"
+"\"locale\": \"en\""
+"}";
byte[] out = payload.getBytes(StandardCharsets.UTF_8);
OutputStream stream = connection.getOutputStream();
stream.write(out);
int responseCode = connection.getResponseCode();
System.out.println("response code: "+responseCode);
System.out.println(connection.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK)
{
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer response = new StringBuffer();
String inputLine;
while ((inputLine = in.readLine()) != null)
{
response.append(inputLine);
System.out.println(inputLine.toString());
}
in.close();
//System.out.println(response.toString());
}
else
{
System.out.println("POST request FAILED");
}
connection.disconnect();
}
catch (Exception e)
{
System.out.println(e);
System.out.println("FAILED");
}
}
}
The javascript code shown can be saved in a text file such as route.js
and run at the commandline using nodejs. In Linux, for example, if nodejs is not installed, it can be installed at the terminal commandline like this:
sudo apt install nodejs
also XMLHttpRequest needs to be installed:
npm install xhr2
Then route.js
can be run at the commandline like this:
nodejs route.js
complete minimal javascript route request - 2 waypoints, the first for departure and the second for destination:
var XMLHttpRequest = require("xhr2");
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://routes.magiclaneapis.com/v1");
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Authorization","YOUR_API_KEY_TOKEN");
const body = JSON.stringify({
"transport": "bike",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"debug": true
});
xhr.onload = () => {
console.log((xhr.responseText));
};
xhr.send(body);
route request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above; there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
var XMLHttpRequest = require("xhr2");
const xhr = new XMLHttpRequest();
xhr.open("POST", "https://routes.magiclaneapis.com/v1");
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Authorization","YOUR_API_KEY_TOKEN");
const body = JSON.stringify({
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
});
xhr.onload = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log((xhr.responseText));
} else {
console.log(`error: ${xhr.status}`);
}
};
xhr.send(body);
The go code shown can be saved in a text file such as route.go
and run at the commandline using go. In Linux, for example, if go is not installed, it can be installed at the terminal commandline like this:
sudo apt install golang
Then route.go
can be run at the commandline like this:
go run route.go
complete minimal go route request - 2 waypoints, the first for departure and the second for destination:
package main
import (
"fmt"
"bytes"
"net/http"
"io/ioutil"
)
func main() {
reqUrl := "https://routes.magiclaneapis.com/v1"
var data = []byte(`{
"transport": "bike",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"debug": true
}`)
req, _ := http.NewRequest("POST", reqUrl, bytes.NewBuffer(data))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "YOUR_API_KEY_TOKEN")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}
route request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above; there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
package main
import (
"fmt"
"bytes"
"net/http"
"io/ioutil"
)
func main() {
reqUrl := "https://routes.magiclaneapis.com/v1"
var data = []byte(`{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
}`)
req, _ := http.NewRequest("POST", reqUrl, bytes.NewBuffer(data))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "YOUR_API_KEY_TOKEN")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
fmt.Println(res)
fmt.Println(string(body))
}
https://dart.dev/get-dart Dart can be downloaded from here
To install dart on Linux (debian/ubuntu flavors), for example, it is best to download the .deb
package from the Linux tab in the above link, such as dart_3.0.5-1_amd64.deb
and install it like this:
sudo dpkg -i dart_3.0.5-1_amd64.deb
At a terminal/command prompt, type:
dart create myapp
to create a new dart application named myapp
. A directory named myapp
is created in the current directory, containing all necessary files. Go into this new directory:
cd myapp
User your favorite text editor, such as vim
, geany
or notepad
to edit the pubspec.yaml
file and add this dependency to the dependencies section as shown, then save it:
dependencies:
http: ^1.0.0
Next, edit the dart source code in lib/myapp.dart
to look like this, without the line numbers - those are for reference only:
complete route request in dart
with all default values shown explicitly - there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
import 'dart:io';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
calculate() async
{
try
{
var sendString =
{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
};
final response = await http.post(
Uri.parse("https://routes.magiclaneapis.com/v1"),
headers: {
"Content-Type": "application/json",
"Authorization": "YOUR_API_KEY_TOKEN"
//"Access-Control-Allow-Origin": "*"
},
body: jsonEncode(sendString)
);
print("${response.statusCode}");//2 equivalent ways to print output
//print("${response.body}");
//print(response.statusCode);
print(response.body);
}
catch(e)
{
print(e);
}
}
You should replace the string “YOUR_API_KEY_TOKEN” with your actual API key token string. Now save the lib/myapp.dart
file shown above, go to the myapp
directory, and run it like this:
dart run
In Linux (debian/ubuntu flavors), for example, if perl is not installed, it can be installed at the terminal commandline like this:
sudo apt install perl
The JSON perl module can be installed like this:
sudo cpan JSON
complete minimal perl route request - 2 waypoints, the first for departure and the second for destination:
save this code in a text file named route.pl
(without the line numbers - those are for reference) and run it:
perl route.pl
#! /usr/bin/env perl
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use JSON;
my $url = 'https://routes.magiclaneapis.com/v1';
my $json = '{
"transport": "bike",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"debug": true
}';
my $req = HTTP::Request->new( 'POST', $url );
$req->header( 'Content-Type' => 'application/json',
'Authorization' => 'YOUR_API_KEY_TOKEN');
$req->content( $json );
my $ua = LWP::UserAgent->new;
my $res = $ua->request( $req );
print $res->decoded_content;
route request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above; there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
save this code in a text file named route.pl
(without the line numbers - those are for reference) and run it:
perl route.pl
#! /usr/bin/env perl
use strict;
use warnings;
use LWP::UserAgent;
use HTTP::Request;
use JSON;
my $url = 'https://routes.magiclaneapis.com/v1';
my $json = '{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
}';
my $req = HTTP::Request->new( 'POST', $url );
$req->header( 'Content-Type' => 'application/json',
'Authorization' => 'YOUR_API_KEY_TOKEN');
$req->content( $json );
my $ua = LWP::UserAgent->new;
my $res = $ua->request( $req );
print $res->decoded_content;
The php code shown can be saved in a text file such as route.php
and run at the commandline using php.
In Linux (debian/ubuntu flavors), for example, if php
is not installed, it can be installed at the terminal commandline like this:
sudo apt install php php-curl
Then route.php
can be run at the commandline like this:
php route.php
complete minimal php route request - 2 waypoints, the first for departure and the second for destination:
<?php
$mycurl = curl_init("https://routes.magiclaneapis.com/v1");
if ($mycurl === false) {
print "curl initialization FAILED\n";
}
$payload = array(
"transport" => "bike",
"waypoints" => array(array(2.24559,48.88562),array(2.27670,48.77927)),
"avoid" => array("unpaved","highway"),
"debug" => true
);
$data_string = json_encode($payload);
curl_setopt($mycurl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($mycurl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($mycurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($mycurl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($mycurl, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Authorization: YOUR_API_KEY_TOKEN"
));
$result = curl_exec($mycurl);
if ($result === false) {
print "POST request FAILED " . curl_error($mycurl) . " errno: " . curl_errno($mycurl) . "\n";
}
else { var_dump($result); }
$httpReturnCode = curl_getinfo($mycurl, CURLINFO_HTTP_CODE);
if ($httpReturnCode != "200") {
print "HTTP return code should be 200, got: " . $httpReturnCode . "\n";
}
if (is_resource($mycurl)) {
curl_close($mycurl);
}
?>
route request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above; there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
<?php
$mycurl = curl_init("https://routes.magiclaneapis.com/v1");
if ($mycurl === false) {
print "curl initialization FAILED\n";
}
$payload = array(
"transport" => "bike",
"type" => "fastest",
"waypoints" => array(array(2.24559,48.88562),array(2.27670,48.77927)),
"avoid" => array("unpaved","highway"),
"details" => "full",
"alternatives" => 0,
"profile" => "city",
"terrain" => false,
"hillskip" => 0.5,
"emergency" => false,
"debug" => true,
"locale" => "en"
);
$data_string = json_encode($payload);
//curl_setopt($mycurl, CURLOPT_URL, "https://routes.magiclaneapis.com/v1");
curl_setopt($mycurl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($mycurl, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($mycurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($mycurl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($mycurl, CURLOPT_HTTPHEADER, array(
"Content-Type: application/json",
"Authorization: YOUR_API_KEY_TOKEN"
));
$result = curl_exec($mycurl);
if ($result === false) {
print "POST request FAILED " . curl_error($mycurl) . " errno: " . curl_errno($mycurl) . "\n";
}
else { var_dump($result); }
$httpReturnCode = curl_getinfo($mycurl, CURLINFO_HTTP_CODE);
if ($httpReturnCode != "200") {
print "HTTP return code should be 200, got: " . $httpReturnCode . "\n";
}
if (is_resource($mycurl)) {
curl_close($mycurl);
}
?>
In Linux (debian/ubuntu flavors), for example, if R is not installed, it can be installed at the terminal commandline like this:
sudo apt install r-base-dev
Then start the R interpreter environment like this:
R
install the httr
package within R like this:
install.packages("httr")
and answer y to the two installation-related questions that follow;
complete minimal R route request - 2 waypoints, the first for departure and the second for destination: note that the debug
parameter is omitted, as the json is stored in the response variable, not printed directly, so formatting the json output is done locally by the toJSON()
function: pretty = TRUE
; (copy and paste the code into the R interpreter, without the line numbers - those are for reference)
require(httr)
require(jsonlite)
body = '{
"transport": "bike",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"]
}'
result <- POST("https://routes.magiclaneapis.com/v1", body = body,
add_headers(.headers = c("Content-Type"="application/json", "Authorization"="YOUR_API_KEY_TOKEN")))
toJSON(content(result), pretty = TRUE)
route request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above; there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
require(httr)
require(jsonlite)
body = '{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
}'
result <- POST("https://routes.magiclaneapis.com/v1", body = body,
add_headers(.headers = c("Content-Type"="application/json", "Authorization"="YOUR_API_KEY_TOKEN")))
toJSON(content(result), pretty = TRUE)
To exit the R environment, type q()
The ruby code shown can be saved in a text file such as route.rb
and run at the commandline using ruby. In Linux, for example, if ruby is not installed, it can be installed at the terminal commandline like this:
sudo apt install ruby
Then route.rb
can be run at the commandline like this:
ruby route.rb
complete minimal ruby route request - 2 waypoints, the first for departure and the second for destination:
require "json"
require "uri"
require "net/http"
require "openssl"
url = URI("https://routes.magiclaneapis.com/v1")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request["Accept-Encoding"] = "text"
request["Authorization"] = "YOUR_API_KEY_TOKEN"
request.body =
{
"transport": "bike",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"debug": true
}.to_json
puts "sent"
response = http.request(request)
puts response.read_body
route request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above; there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
require "json"
require "uri"
require "net/http"
require "openssl"
url = URI("https://routes.magiclaneapis.com/v1")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = "application/json"
request["Accept-Encoding"] = "text"
request["Authorization"] = "YOUR_API_KEY_TOKEN"
request.body =
{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
}.to_json
puts "sent"
response = http.request(request)
puts response.read_body
Save the following in a text file named Cargo.toml
(case-sensitive). This contains the configuration and dependencies required for compilation.
[package]
name = "restpost"
version = "0.1.0"
edition = "2018"
[[bin]]
name = "route"
path = "route.rs"
[dependencies]
json = { version = "0.12.4" }
reqwest = { version = "0.11.18", features = ["json", "blocking"] }
serde_json = { version = "1.0.44" }
tokio = { version = "1.28.2", features = ["macros", "full"] }
route request with all default values shown explicitly ; there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
Save the following rust program in a text file named route.rs
extern crate reqwest;
#[tokio::main]
async fn main() -> Result<(), reqwest::Error>
{
let response = reqwest::Client::new()
.post("https://routes.magiclaneapis.com/v1")
.header("Authorization", "YOUR_API_KEY_TOKEN")
.header("Content-Type", "application/json")
.header("Accept-Encoding", "text")
.json(&serde_json::json!({
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 0,
"profile": "city",
"terrain": false,
"hillskip": 0.5,
"emergency": false,
"debug": true,
"locale": "en"
}))
.send().await?;
println!("{:?}",response.text().await?);
Ok(())
}
In Linux (debian/ubuntu flavors), for example, if rust is not installed, it can be installed at the terminal commandline like this:
sudo apt install cargo rustc
Compile the program like this at the commandline, in the directory containing both Cargo.toml
and route.rs
:
cargo b
To run the program, go to the build directory like this:
cd target/debug
and then run the route program:
./route
The Matlab code shown can be copied and pasted into Matlab, without the line numbers - those are for reference.
complete route request in Matlab
with all default values shown explicitly - there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
method = matlab.net.http.RequestMethod.POST
f0 = matlab.net.http.HeaderField('Content-Type','application/json')
f1 = matlab.net.http.HeaderField('Authorization','')
header = [f0 f1]
str = [ ...
'{', ...
+ '"transport": "bike",', ...
+ '"type": "fastest",', ...
+ '"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],', ...
+ '"avoid": ["unpaved","highway"],', ...
+ '"details": "full",', ...
+ '"alternatives": 0,', ...
+ '"profile": "city",', ...
+ '"terrain": false,', ...
+ '"hillskip": 0.5,', ...
+ '"emergency": false,', ...
+ '"debug": true,', ...
+ '"locale": "en"', ...
+ '}' ]
request = matlab.net.http.RequestMessage( method, header, jsondecode(str) );
response = request.send( 'https://routes.magiclaneapis.com/v1' );
jsonencode(response.Body.Data,"PrettyPrint",true)
The above code can also be saved in a text file named route.m
and run at the Matlab
command prompt by typing route
and pressing enter. The current working directory shown at the top of the window should be set to the directory where route.m
was saved.
The scilab code shown can be copied and pasted into scilab, without the line numbers - those are for reference.
https://www.scilab.org/ Scilab can be downloaded from here
complete minimal scilab route request - 2 waypoints, the first for departure and the second for destination: note that the debug
parameter is omitted, as the json is stored in the result variable, not printed directly, so formatting the json output is done locally by the toJSON()
function, where 3 is the number of spaces to use for indentation (if this number is 0, then the json output is not indented/pretty printed)
jsondata = ...
"{" ...
+"transport: bike," ...
+"waypoints: [[2.24559,48.88562],[2.27670,48.77927]]," ...
+"avoid: [unpaved,highway]" ...
+"}"
[result, status] = http_post("https://routes.magiclaneapis.com/v1", toJSON(fromJSON(jsondata)), format="json", auth="YOUR_API_KEY_TOKEN" );
toJSON(result,3)
route request with all default values shown explicitly - this request is equivalent to, and produces the same output as, the previous request above; there are 2 waypoints, the first for departure and the second for destination; no intermediate track request version:
jsondata = ...
"{" ...
+"transport: bike," ...
+"type: fastest," ...
+"waypoints: [[2.24559,48.88562],[2.27670,48.77927]]," ...
+"avoid: [unpaved,highway]," ...
+"details: full," ...
+"alternatives: 0," ...
+"profile: city," ...
+"terrain: false," ...
+"hillskip: 0.5," ...
+"emergency: false," ...
+"debug: true," ...
+"locale: en" ...
+"}"
[result, status] = http_post("https://routes.magiclaneapis.com/v1", toJSON(fromJSON(jsondata)), format="json", auth="YOUR_API_KEY_TOKEN" );
toJSON(result,3)
Complete json
request (json payload) - version with sample track included - 2 waypoints, the first for departure and the second for destination; additionally, track coordinates are given for matching a route between the departure and destination along the specified track if possible:
{
"transport": "bike",
"type": "fastest",
"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
"avoid": ["unpaved","highway"],
"details": "full",
"alternatives": 2,
"profile": "city",
"terrain": false,
"hillskip": 0.8,
"emergency": false,
"debug": true,
"locale": "fr",
"track":
{
"accurate": false,
"restrictions": false,
"waypoint_index": 1,
"coords": [
[2.24388, 48.88392, 0.00000],
[2.24388, 48.88392, 0.00000],
[2.24388, 48.88392, 0.00000],
[2.24346, 48.88390, 0.00000],
[2.24304, 48.88387, 0.00000],
[2.24261, 48.88385, 0.00000],
[2.24135, 48.88378, 0.00000],
[2.24009, 48.88371, 0.00000],
[2.24009, 48.88371, 0.00000],
[2.23882, 48.88363, 0.00000],
[2.23756, 48.88356, 0.00000],
[2.23419, 48.88337, 0.00000],
[2.23124, 48.88320, 0.00000],
[2.22955, 48.88311, 0.00000],
[2.22786, 48.88301, 0.00000],
[2.22618, 48.88292, 0.00000],
[2.22491, 48.88285, 0.00000],
[2.22491, 48.88285, 0.00000],
[2.22281, 48.88273, 0.00000],
[2.22112, 48.88263, 0.00000],
[2.21986, 48.88256, 0.00000],
[2.21817, 48.88246, 0.00000],
[2.21648, 48.88237, 0.00000],
[2.21522, 48.88230, 0.00000],
[2.21396, 48.88222, 0.00000],
[2.21269, 48.88215, 0.00000],
[2.21185, 48.88210, 0.00000],
[2.21055, 48.88231, 0.00000],
[2.21055, 48.88231, 0.00000],
[2.20886, 48.88221, 0.00000],
[2.20675, 48.88209, 0.00000]
]
}
}
Note that the waypoints
list contains the minimum required number of 2 coordinates, one for the departure position and one for the destination, therefore, their 0-based indexes are 0 and 1, respectively. In the track
structure, the waypoint_index
(insertion index) parameter is set to 1, which means that the track coordinates are inserted in the primary waypoints
list starting at index 1. Thus, in the above example, the departure waypoint is at index 0, followed by the track waypoints at indexes 1-31, followed by the destination waypoint at index 32.
In a linux terminal you can also send the request directly from the command line, without a file, like this: (this method does not work on windows)
curl "https://routes.magiclaneapis.com/v1" -X POST -H "Content-Type: application/json" -H "Authorization: YOUR_API_KEY_TOKEN" -d \
'{
...
}'
The only difference is the added backslash after -d, and then the filename @/home/user/payload.json
is replaced with the contents of the json file, starting with the next line - note that a single quote ‘ is added before the leading curly brace { and after the trailing curly brace } to enclose the file contents in single quotes - no backslashes are needed between the single quotes.
REQUEST PARAMETER DEFINITIONS
Request body schema: application/json
key | value |
---|---|
transport | Specify the transportation mode to be used on the route. Type: string Default value: "car" Default value: "car" |
type | Specify the route evaluation type. Type: string Default value: "fastest" Possible values: “fastest”, “shortest” (car/lorry), “economic” (bike) |
waypoints (mandatory parameter) | The route waypoints specified in visit order Type: array of coords in format [[lon, lat]] This parameter is mandatory. There must be at least 2 waypoints - the first waypoint is the departure position and the last waypoint is the destination |
avoid | The routing avoidance - what to avoid along the route Type: string array Default value: empty Possible values: “highway”, “ferry”, “toll”, “unpaved”, “turnaround”, “traffic” (car/lorry), “roadblocks” (car/lorry) |
details | Route result details Type: string Default value: "full" Possible values: “full” - route path + instructions “path” - route path only “timedistance” - route time + distance |
alternatives | The number of requested alternate routes to be computed, not including the main route result Type: integer Default value: 0 Internally the services will trim the requested alternatives to max 2 for car/lorry/bike/pedestrian, 10 for public (transport) |
profile | Specify the route transport profile Type: string Default value: "city" for bike, "walk" for pedestrianPossible values: “city”, “road”, “cross”, “mountain” (bike); “walk”, “hike” (pedestrian) |
terrain | Include terrain information in the result Type: bool Default value: false |
hillskip | Hill avoidance factor (bike only) Type: float Default value: 0.5 |
track | Route over existing input track - options Type: structure |
track: { accurate }(property within track structure) | Apply accurate route match on map data for track points Type: bool Default value: true Should be true when matching a GPS capture trackShould be false when matching a hand drawn track |
track: { restrictions }(property within track structure) | Apply map restrictions when routing over track Type: bool Default value: true if accurate == true, else false |
track: { coords }(property within track structure) | List of 2 or more coordinates to include in route Type: array of coords in format [[lon, lat, {alt}]] Track coordinates in lon, lat, alt (optional). At least 2 track coordinate entries should be provided. |
track: { waypoint_index }(property within track structure) | The track waypoint 0-based index in the route waypoints Type: integer Default value: track waypoint is added at end of route waypoints Inserting the track in the route waypoints list so that the first track waypoint is at 0-based index 2:[0]departure_waypoint, [1]first_waypoint, [2]track, waypoint_before_destination, [n]destination_waypoint |
emergency | Apply emergency profile to the route Type: bool Default value: false Vehicle will be allowed on emergency tagged links, CDMs with emergency tag will be ignored, etc. |
debug | If true, the JSON output is formatted for easy reading Type: bool Default value: false |
locale | The ISO 639-1 language for the routing result Type: string Default value: en |
RESPONSE
MagicLane header
{
"info": {
"copyrights": [
"MagicLane"
]
},
"routes": [
{
Route summary
The distance in meters, the time in seconds, and the bounding box containing the entire route, given as two longitude,latitude coordinate pairs of the diagonally opposite corners of the rectangle containing the route, are given.
"distance": 16552,
"time": 3709,
"bbox": [
2.2274959375000000783,
48.779269999999996799,
2.2944959374999998047,
48.885850625000003333
],
Route path points
The longitude,latitude coordinate pair of points along the route.
"points": {
"type": "LineString",
"coordinates": [
[
2.2456190624999998739,
48.885588437499997383
],
[
2.2459999999999999964,
48.885763124999996876
],
// ...
]
},
Route instructions list
each instruction block contains:
id; distance from beginning of route; travel time from beginning of route; heading (direction) clockwise, where 0 is north, 90 is east, 180 is south, and 270 or -90 is west; turn instruction; follow instruction; street name(s);
"instructions": [
{
"id": 22,
"distance": 0,
"time": 0,
"heading": 55.10716878309646205,
"turn": "",
"follow": "Follow Rue Roque de Fillol for 50 m.",
"street": [
"Rue Roque de Fillol"
]
},
// ...
],
Terrain/topography elevation
elevation in meters above sealevel, at a 30 meter horizontal sample resolution;
"terrain": {
"elevations": [
38.69173431396484375,
39.398284912109375,
39.90000152587890625,
// ...
],
"total_up": 112.6616668701171875,
"total_down": 42.85340118408203125
special climb sections
"climb_sections": [
{
"start": 9360,
"end": 12450,
"slope": 6.2290167808532714844,
"grade": 3
}
]
}
}
]
}