Routing¶
Setup¶
Routing entry point¶
URL: |
|
Example¶
These are complete working examples in several different languages, showing how to use the REST API routing. You can try them right now.
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:
1{
2 "transport": "bike",
3 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
4 "avoid": ["unpaved","highway"],
5 "debug": true
6}
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:
1{
2 "transport": "bike",
3 "type": "fastest",
4 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
5 "avoid": ["unpaved","highway"],
6 "details": "full",
7 "alternatives": 0,
8 "profile": "city",
9 "terrain": false,
10 "hillskip": 0.5,
11 "emergency": false,
12 "debug": true,
13 "locale": "en"
14}
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;
1import requests
2import json
3url = "https://routes.magiclaneapis.com/v1"
4headers = {"Content-Type": "application/json", "Authorization": "YOUR_API_KEY_TOKEN" }
5payload = {
6 "transport": "bike",
7 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
8 "avoid": ["unpaved","highway"],
9}
10response = requests.post(url, json=payload, headers=headers)
11r = response.json()
12print(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:
1import requests
2import json
3url = "https://routes.magiclaneapis.com/v1"
4headers = {"Content-Type": "application/json", "Authorization": "YOUR_API_KEY_TOKEN" }
5payload = {
6 "transport": "bike",
7 "type": "fastest",
8 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
9 "avoid": ["unpaved","highway"],
10 "details": "full",
11 "alternatives": 0,
12 "profile": "city",
13 "terrain": False,
14 "hillskip": 0.5,
15 "emergency": False,
16 "debug": True,
17 "locale": "en"
18}
19response = requests.post(url, json=payload, headers=headers)
20r = response.json()
21print(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:
1#include <curl/curl.h>
2
3int main (int argc, char *argv[])
4{
5 CURL *curl;
6 CURLcode res;
7
8 curl_global_init(CURL_GLOBAL_ALL);
9 curl = curl_easy_init();
10 if (curl == NULL) { return 128; }
11
12 char* jsonObj = "{"
13 "\"transport\": \"bike\","
14 "\"type\": \"fastest\","
15 "\"waypoints\": [[2.24559,48.88562],[2.27670,48.77927]],"
16 "\"avoid\": [\"unpaved\",\"highway\"],"
17 "\"details\": \"full\","
18 "\"alternatives\": 0,"
19 "\"profile\": \"city\","
20 "\"terrain\": false,"
21 "\"hillskip\": 0.5,"
22 "\"emergency\": false,"
23 "\"debug\": true,"
24 "\"locale\": \"en\""
25 "}";
26 struct curl_slist *headers = NULL;
27 curl_slist_append(headers, "Content-Type: application/json");
28 curl_slist_append(headers, "Authorization: YOUR_API_KEY_TOKEN");
29
30 curl_easy_setopt(curl, CURLOPT_URL, "https://routes.magiclaneapis.com/v1");
31 curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "PUT");
32 curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
33 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, jsonObj);
34
35 res = curl_easy_perform(curl);
36
37 curl_easy_cleanup(curl);
38 curl_global_cleanup();
39 return res;
40}
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
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:
1import std.stdio;
2import std.net.curl;
3void main()
4{
5 string payload = '{
6 "transport": "bike",
7 "type": "fastest",
8 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
9 "avoid": ["unpaved","highway"],
10 "details": "full",
11 "alternatives": 0,
12 "profile": "city",
13 "terrain": false,
14 "hillskip": 0.5,
15 "emergency": false,
16 "debug": true,
17 "locale": "en"
18 }';
19 auto http = HTTP();
20 http.addRequestHeader("Content-Type", "application/json");
21 http.addRequestHeader("Authorization", "YOUR_API_KEY_TOKEN");
22 auto content = post("https://routes.magiclaneapis.com/v1", payload, http);
23 writeln(content);
24}
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
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:
1using JSON, HTTP
2req = """{
3 "transport": "bike",
4 "type": "fastest",
5 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
6 "avoid": ["unpaved","highway"],
7 "details": "full",
8 "alternatives": 0,
9 "profile": "city",
10 "terrain": false,
11 "hillskip": 0.5,
12 "emergency": false,
13 "debug": true,
14 "locale": "en"
15 }"""
16ans = HTTP.request("POST", "https://routes.magiclaneapis.com/v1",
17 ["Content-Type" => "application/json",
18 "Authorization" => "YOUR_API_KEY_TOKEN"], req);
19str = String(ans.body);
20print(str)
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:
1package kot.routing.post
2
3import java.net.URI
4import java.net.http.HttpClient
5import java.net.http.HttpRequest
6import java.net.http.HttpResponse
7
8fun main()
9{
10 val request: String = """
11 {
12 "transport": "bike",
13 "type": "fastest",
14 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
15 "avoid": ["unpaved","highway"],
16 "details": "full",
17 "alternatives": 0,
18 "profile": "city",
19 "terrain": false,
20 "hillskip": 0.5,
21 "emergency": false,
22 "debug": true,
23 "locale": "en"
24 }"""
25 print(request)
26 val client = HttpClient.newBuilder().build();
27 val postrequest = HttpRequest.newBuilder()
28 .uri(URI.create("https://routes.magiclaneapis.com/v1"))
29 .header("Content-Type", "application/json")
30 .header("Authorization", "YOUR_API_KEY_TOKEN")
31 .POST(HttpRequest.BodyPublishers.ofString(request))
32 .build()
33 val response = client.send(postrequest, HttpResponse.BodyHandlers.ofString());
34 println(response.statusCode())
35 println(response.body())
36}
kotlin
routing request!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.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:
1static void main(String[] args)
2{
3 def post = new URL("https://routes.magiclaneapis.com/v1").openConnection();
4 def message = '''
5 {
6 "transport": "bike",
7 "type": "fastest",
8 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
9 "avoid": ["unpaved","highway"],
10 "details": "full",
11 "alternatives": 0,
12 "profile": "city",
13 "terrain": false,
14 "hillskip": 0.5,
15 "emergency": false,
16 "debug": true,
17 "locale": "en"
18 }
19 '''
20 post.setRequestMethod("POST")
21 post.setDoOutput(true)
22 post.setRequestProperty("Content-Type", "application/json")
23 post.setRequestProperty("Authorization", "YOUR_API_KEY_TOKEN")
24 post.getOutputStream().write(message.getBytes("UTF-8"));
25 def postRC = post.getResponseCode();
26 println(postRC);
27 if (postRC.equals(200)) {
28 println(post.getInputStream().getText());
29 }
30}
groovy
routing request!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:
1import scalaj.http.{Http, HttpOptions}
2object Main
3{
4 def main(args: Array[String]): Unit =
5 {
6 val request = s"""
7 {
8 "transport": "bike",
9 "type": "fastest",
10 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
11 "avoid": ["unpaved","highway"],
12 "details": "full",
13 "alternatives": 0,
14 "profile": "city",
15 "terrain": false,
16 "hillskip": 0.5,
17 "emergency": false,
18 "debug": true,
19 "locale": "en"
20 }
21 """
22 val result = Http("https://routes.magiclaneapis.com/v1")
23 .header("Content-Type", "application/json")
24 .header("Authorization", "YOUR_API_KEY_TOKEN")
25 .header("Accept-Encoding", "text")
26 .postData(request)
27 .option(HttpOptions.method("POST"))
28 .option(HttpOptions.readTimeout(10000)).asString
29 println(result)
30 println(result.code)
31 }
32}
scala
routing request!JSONPostReq.java
and then
compiled; at the commandline on either a Linux terminal or Windows command prompt type:javac JSONPostReq.java
java JSONPostReq
complete minimal java route request - 2 waypoints, the first for departure and the second for destination:
1import java.net.HttpURLConnection;
2import java.net.URL;
3import java.nio.charset.StandardCharsets;
4import java.io.BufferedReader;
5import java.io.InputStreamReader;
6import java.io.OutputStream;
7import java.io.IOException;
8public class JSONPostReq
9{
10 public static void main(String[] args) throws IOException
11 {
12 URL url = new URL("https://routes.magiclaneapis.com/v1");
13 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
14 connection.setRequestMethod("POST");
15 connection.setDoOutput(true);
16 connection.setRequestProperty("Content-Type","application/json");
17 connection.setRequestProperty("Authorization","YOUR_API_KEY_TOKEN");
18 String payload = "{"
19 +"\"transport\": \"bike\","
20 +"\"waypoints\": [[2.24559,48.88562],[2.27670,48.77927]],"
21 +"\"avoid\": [\"unpaved\",\"highway\"],"
22 +"\"debug\": true"
23 +"}";
24 byte[] out = payload.getBytes(StandardCharsets.UTF_8);
25 OutputStream stream = connection.getOutputStream();
26 stream.write(out);
27 int responseCode = connection.getResponseCode();
28 System.out.println("response code: "+responseCode);
29 if (responseCode == HttpURLConnection.HTTP_OK)
30 {
31 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
32 String inputLine;
33 while ((inputLine = in.readLine()) != null)
34 {
35 System.out.println(inputLine.toString());
36 }
37 in.close();
38 }
39 connection.disconnect();
40 }
41}
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:
1import java.net.HttpURLConnection;
2import java.net.URL;
3import java.nio.charset.StandardCharsets;
4import java.io.BufferedReader;
5import java.io.InputStreamReader;
6import java.io.OutputStream;
7import java.io.IOException;
8public class JSONPostReq
9{
10 public static void main(String[] args) throws IOException
11 {
12 try
13 {
14 URL url = new URL("https://routes.magiclaneapis.com/v1");
15 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
16 connection.setRequestMethod("POST");
17 connection.setDoOutput(true);
18 connection.setRequestProperty("Content-Type","application/json");
19 connection.setRequestProperty("Authorization","YOUR_API_KEY_TOKEN");
20 String payload = "{"
21 +"\"transport\": \"bike\","
22 +"\"type\": \"fastest\","
23 +"\"waypoints\": [[2.24559,48.88562],[2.27670,48.77927]],"
24 +"\"avoid\": [\"unpaved\",\"highway\"],"
25 +"\"details\": \"full\","
26 +"\"alternatives\": 0,"
27 +"\"profile\": \"city\","
28 +"\"terrain\": false,"
29 +"\"hillskip\": 0.5,"
30 +"\"emergency\": false,"
31 +"\"debug\": true,"
32 +"\"locale\": \"en\""
33 +"}";
34 byte[] out = payload.getBytes(StandardCharsets.UTF_8);
35 OutputStream stream = connection.getOutputStream();
36 stream.write(out);
37 int responseCode = connection.getResponseCode();
38 System.out.println("response code: "+responseCode);
39 System.out.println(connection.getResponseMessage());
40 if (responseCode == HttpURLConnection.HTTP_OK)
41 {
42 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
43 StringBuffer response = new StringBuffer();
44 String inputLine;
45 while ((inputLine = in.readLine()) != null)
46 {
47 response.append(inputLine);
48 System.out.println(inputLine.toString());
49 }
50 in.close();
51 //System.out.println(response.toString());
52 }
53 else
54 {
55 System.out.println("POST request FAILED");
56 }
57 connection.disconnect();
58 }
59 catch (Exception e)
60 {
61 System.out.println(e);
62 System.out.println("FAILED");
63 }
64 }
65}
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
npm install xhr2
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:
1var XMLHttpRequest = require("xhr2");
2const xhr = new XMLHttpRequest();
3xhr.open("POST", "https://routes.magiclaneapis.com/v1");
4xhr.setRequestHeader("Content-Type","application/json");
5xhr.setRequestHeader("Authorization","YOUR_API_KEY_TOKEN");
6const body = JSON.stringify({
7 "transport": "bike",
8 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
9 "avoid": ["unpaved","highway"],
10 "debug": true
11});
12xhr.onload = () => {
13 console.log((xhr.responseText));
14};
15xhr.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:
1var XMLHttpRequest = require("xhr2");
2const xhr = new XMLHttpRequest();
3xhr.open("POST", "https://routes.magiclaneapis.com/v1");
4xhr.setRequestHeader("Content-Type","application/json");
5xhr.setRequestHeader("Authorization","YOUR_API_KEY_TOKEN");
6const body = JSON.stringify({
7 "transport": "bike",
8 "type": "fastest",
9 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
10 "avoid": ["unpaved","highway"],
11 "details": "full",
12 "alternatives": 0,
13 "profile": "city",
14 "terrain": false,
15 "hillskip": 0.5,
16 "emergency": false,
17 "debug": true,
18 "locale": "en"
19});
20xhr.onload = () => {
21 if (xhr.readyState == 4 && xhr.status == 200) {
22 console.log((xhr.responseText));
23 } else {
24 console.log(`error: ${xhr.status}`);
25 }
26};
27xhr.send(body);
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
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:
1package main
2import (
3 "fmt"
4 "bytes"
5 "net/http"
6 "io/ioutil"
7)
8
9func main() {
10 reqUrl := "https://routes.magiclaneapis.com/v1"
11 var data = []byte(`{
12 "transport": "bike",
13 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
14 "avoid": ["unpaved","highway"],
15 "debug": true
16 }`)
17 req, _ := http.NewRequest("POST", reqUrl, bytes.NewBuffer(data))
18 req.Header.Add("Content-Type", "application/json")
19 req.Header.Add("Authorization", "YOUR_API_KEY_TOKEN")
20 res, _ := http.DefaultClient.Do(req)
21 defer res.Body.Close()
22 body, _ := ioutil.ReadAll(res.Body)
23 fmt.Println(res)
24 fmt.Println(string(body))
25}
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:
1package main
2import (
3 "fmt"
4 "bytes"
5 "net/http"
6 "io/ioutil"
7)
8
9func main() {
10 reqUrl := "https://routes.magiclaneapis.com/v1"
11 var data = []byte(`{
12 "transport": "bike",
13 "type": "fastest",
14 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
15 "avoid": ["unpaved","highway"],
16 "details": "full",
17 "alternatives": 0,
18 "profile": "city",
19 "terrain": false,
20 "hillskip": 0.5,
21 "emergency": false,
22 "debug": true,
23 "locale": "en"
24 }`)
25 req, _ := http.NewRequest("POST", reqUrl, bytes.NewBuffer(data))
26 req.Header.Add("Content-Type", "application/json")
27 req.Header.Add("Authorization", "YOUR_API_KEY_TOKEN")
28 res, _ := http.DefaultClient.Do(req)
29 defer res.Body.Close()
30 body, _ := ioutil.ReadAll(res.Body)
31 fmt.Println(res)
32 fmt.Println(string(body))
33}
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:
1import 'dart:io';
2import 'dart:async';
3import 'dart:convert';
4import 'package:http/http.dart' as http;
5
6calculate() async
7{
8 try
9 {
10 var sendString =
11 {
12 "transport": "bike",
13 "type": "fastest",
14 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
15 "avoid": ["unpaved","highway"],
16 "details": "full",
17 "alternatives": 0,
18 "profile": "city",
19 "terrain": false,
20 "hillskip": 0.5,
21 "emergency": false,
22 "debug": true,
23 "locale": "en"
24 };
25 final response = await http.post(
26 Uri.parse("https://routes.magiclaneapis.com/v1"),
27 headers: {
28 "Content-Type": "application/json",
29 "Authorization": "YOUR_API_KEY_TOKEN"
30 //"Access-Control-Allow-Origin": "*"
31 },
32 body: jsonEncode(sendString)
33 );
34 print("${response.statusCode}");//2 equivalent ways to print output
35 //print("${response.body}");
36 //print(response.statusCode);
37 print(response.body);
38 }
39 catch(e)
40 {
41 print(e);
42 }
43}
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
sudo apt install perl
sudo cpan JSON
route.pl
(without the line numbers - those are for reference)
and run it:perl route.pl
1#! /usr/bin/env perl
2use strict;
3use warnings;
4use LWP::UserAgent;
5use HTTP::Request;
6use JSON;
7
8my $url = 'https://routes.magiclaneapis.com/v1';
9my $json = '{
10 "transport": "bike",
11 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
12 "avoid": ["unpaved","highway"],
13 "debug": true
14 }';
15my $req = HTTP::Request->new( 'POST', $url );
16$req->header( 'Content-Type' => 'application/json',
17'Authorization' => 'YOUR_API_KEY_TOKEN');
18$req->content( $json );
19my $ua = LWP::UserAgent->new;
20my $res = $ua->request( $req );
21print $res->decoded_content;
route.pl
(without the line numbers - those are for reference)
and run it:perl route.pl
1#! /usr/bin/env perl
2use strict;
3use warnings;
4use LWP::UserAgent;
5use HTTP::Request;
6use JSON;
7
8my $url = 'https://routes.magiclaneapis.com/v1';
9my $json = '{
10 "transport": "bike",
11 "type": "fastest",
12 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
13 "avoid": ["unpaved","highway"],
14 "details": "full",
15 "alternatives": 0,
16 "profile": "city",
17 "terrain": false,
18 "hillskip": 0.5,
19 "emergency": false,
20 "debug": true,
21 "locale": "en"
22 }';
23my $req = HTTP::Request->new( 'POST', $url );
24$req->header( 'Content-Type' => 'application/json',
25'Authorization' => 'YOUR_API_KEY_TOKEN');
26$req->content( $json );
27my $ua = LWP::UserAgent->new;
28my $res = $ua->request( $req );
29print $res->decoded_content;
route.php
and run at the commandline using php.php
is not installed, it can be installed at the terminal commandline like this:sudo apt install php php-curl
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:
1<?php
2$mycurl = curl_init("https://routes.magiclaneapis.com/v1");
3if ($mycurl === false) {
4 print "curl initialization FAILED\n";
5}
6$payload = array(
7 "transport" => "bike",
8 "waypoints" => array(array(2.24559,48.88562),array(2.27670,48.77927)),
9 "avoid" => array("unpaved","highway"),
10 "debug" => true
11 );
12$data_string = json_encode($payload);
13curl_setopt($mycurl, CURLOPT_CUSTOMREQUEST, "POST");
14curl_setopt($mycurl, CURLOPT_POSTFIELDS, $data_string);
15curl_setopt($mycurl, CURLOPT_RETURNTRANSFER, true);
16curl_setopt($mycurl, CURLOPT_FOLLOWLOCATION, true);
17curl_setopt($mycurl, CURLOPT_HTTPHEADER, array(
18 "Content-Type: application/json",
19 "Authorization: YOUR_API_KEY_TOKEN"
20 ));
21$result = curl_exec($mycurl);
22
23if ($result === false) {
24 print "POST request FAILED " . curl_error($mycurl) . " errno: " . curl_errno($mycurl) . "\n";
25}
26else { var_dump($result); }
27
28$httpReturnCode = curl_getinfo($mycurl, CURLINFO_HTTP_CODE);
29if ($httpReturnCode != "200") {
30 print "HTTP return code should be 200, got: " . $httpReturnCode . "\n";
31}
32if (is_resource($mycurl)) {
33 curl_close($mycurl);
34}
35?>
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:
1<?php
2$mycurl = curl_init("https://routes.magiclaneapis.com/v1");
3if ($mycurl === false) {
4 print "curl initialization FAILED\n";
5}
6$payload = array(
7 "transport" => "bike",
8 "type" => "fastest",
9 "waypoints" => array(array(2.24559,48.88562),array(2.27670,48.77927)),
10 "avoid" => array("unpaved","highway"),
11 "details" => "full",
12 "alternatives" => 0,
13 "profile" => "city",
14 "terrain" => false,
15 "hillskip" => 0.5,
16 "emergency" => false,
17 "debug" => true,
18 "locale" => "en"
19 );
20$data_string = json_encode($payload);
21//curl_setopt($mycurl, CURLOPT_URL, "https://routes.magiclaneapis.com/v1");
22curl_setopt($mycurl, CURLOPT_CUSTOMREQUEST, "POST");
23curl_setopt($mycurl, CURLOPT_POSTFIELDS, $data_string);
24curl_setopt($mycurl, CURLOPT_RETURNTRANSFER, true);
25curl_setopt($mycurl, CURLOPT_FOLLOWLOCATION, true);
26curl_setopt($mycurl, CURLOPT_HTTPHEADER, array(
27 "Content-Type: application/json",
28 "Authorization: YOUR_API_KEY_TOKEN"
29 ));
30$result = curl_exec($mycurl);
31
32if ($result === false) {
33 print "POST request FAILED " . curl_error($mycurl) . " errno: " . curl_errno($mycurl) . "\n";
34}
35else { var_dump($result); }
36
37$httpReturnCode = curl_getinfo($mycurl, CURLINFO_HTTP_CODE);
38if ($httpReturnCode != "200") {
39 print "HTTP return code should be 200, got: " . $httpReturnCode . "\n";
40}
41if (is_resource($mycurl)) {
42 curl_close($mycurl);
43}
44?>
sudo apt install r-base-dev
R
httr
package within R like this:install.packages("httr")
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)
1require(httr)
2require(jsonlite)
3body = '{
4 "transport": "bike",
5 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
6 "avoid": ["unpaved","highway"]
7 }'
8result <- POST("https://routes.magiclaneapis.com/v1", body = body,
9add_headers(.headers = c("Content-Type"="application/json", "Authorization"="YOUR_API_KEY_TOKEN")))
10toJSON(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:
1require(httr)
2require(jsonlite)
3body = '{
4 "transport": "bike",
5 "type": "fastest",
6 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
7 "avoid": ["unpaved","highway"],
8 "details": "full",
9 "alternatives": 0,
10 "profile": "city",
11 "terrain": false,
12 "hillskip": 0.5,
13 "emergency": false,
14 "debug": true,
15 "locale": "en"
16 }'
17result <- POST("https://routes.magiclaneapis.com/v1", body = body,
18add_headers(.headers = c("Content-Type"="application/json", "Authorization"="YOUR_API_KEY_TOKEN")))
19toJSON(content(result), pretty = TRUE)
To exit the R environment, type q()
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
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:
1require "json"
2require "uri"
3require "net/http"
4require "openssl"
5
6url = URI("https://routes.magiclaneapis.com/v1")
7http = Net::HTTP.new(url.host, url.port)
8http.use_ssl = true
9request = Net::HTTP::Post.new(url)
10request["Content-Type"] = "application/json"
11request["Accept-Encoding"] = "text"
12request["Authorization"] = "YOUR_API_KEY_TOKEN"
13request.body =
14{
15 "transport": "bike",
16 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
17 "avoid": ["unpaved","highway"],
18 "debug": true
19}.to_json
20puts "sent"
21response = http.request(request)
22puts 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:
1require "json"
2require "uri"
3require "net/http"
4require "openssl"
5
6url = URI("https://routes.magiclaneapis.com/v1")
7http = Net::HTTP.new(url.host, url.port)
8http.use_ssl = true
9request = Net::HTTP::Post.new(url)
10request["Content-Type"] = "application/json"
11request["Accept-Encoding"] = "text"
12request["Authorization"] = "YOUR_API_KEY_TOKEN"
13request.body =
14{
15 "transport": "bike",
16 "type": "fastest",
17 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
18 "avoid": ["unpaved","highway"],
19 "details": "full",
20 "alternatives": 0,
21 "profile": "city",
22 "terrain": false,
23 "hillskip": 0.5,
24 "emergency": false,
25 "debug": true,
26 "locale": "en"
27}.to_json
28puts "sent"
29response = http.request(request)
30puts response.read_body
Save the following in a text file named Cargo.toml
(case-sensitive).
This contains the configuration and dependencies required for compilation.
1[package]
2name = "restpost"
3version = "0.1.0"
4edition = "2018"
5
6[[bin]]
7name = "route"
8path = "route.rs"
9
10[dependencies]
11json = { version = "0.12.4" }
12reqwest = { version = "0.11.18", features = ["json", "blocking"] }
13serde_json = { version = "1.0.44" }
14tokio = { 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
1extern crate reqwest;
2#[tokio::main]
3async fn main() -> Result<(), reqwest::Error>
4{
5 let response = reqwest::Client::new()
6 .post("https://routes.magiclaneapis.com/v1")
7 .header("Authorization", "YOUR_API_KEY_TOKEN")
8 .header("Content-Type", "application/json")
9 .header("Accept-Encoding", "text")
10 .json(&serde_json::json!({
11 "transport": "bike",
12 "type": "fastest",
13 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
14 "avoid": ["unpaved","highway"],
15 "details": "full",
16 "alternatives": 0,
17 "profile": "city",
18 "terrain": false,
19 "hillskip": 0.5,
20 "emergency": false,
21 "debug": true,
22 "locale": "en"
23 }))
24 .send().await?;
25 println!("{:?}",response.text().await?);
26 Ok(())
27}
sudo apt install cargo rustc
Cargo.toml
and route.rs
:cargo b
cd target/debug
./route
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:
1method = matlab.net.http.RequestMethod.POST
2f0 = matlab.net.http.HeaderField('Content-Type','application/json')
3f1 = matlab.net.http.HeaderField('Authorization','')
4header = [f0 f1]
5str = [ ...
6'{', ...
7 + '"transport": "bike",', ...
8 + '"type": "fastest",', ...
9 + '"waypoints": [[2.24559,48.88562],[2.27670,48.77927]],', ...
10 + '"avoid": ["unpaved","highway"],', ...
11 + '"details": "full",', ...
12 + '"alternatives": 0,', ...
13 + '"profile": "city",', ...
14 + '"terrain": false,', ...
15 + '"hillskip": 0.5,', ...
16 + '"emergency": false,', ...
17 + '"debug": true,', ...
18 + '"locale": "en"', ...
19 + '}' ]
20request = matlab.net.http.RequestMessage( method, header, jsondecode(str) );
21response = request.send( 'https://routes.magiclaneapis.com/v1' );
22jsonencode(response.Body.Data,"PrettyPrint",true)
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.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)
1jsondata = ...
2"{" ...
3+"transport: bike," ...
4+"waypoints: [[2.24559,48.88562],[2.27670,48.77927]]," ...
5+"avoid: [unpaved,highway]" ...
6+"}"
7[result, status] = http_post("https://routes.magiclaneapis.com/v1", toJSON(fromJSON(jsondata)), format="json", auth="YOUR_API_KEY_TOKEN" );
8toJSON(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:
1jsondata = ...
2"{" ...
3+"transport: bike," ...
4+"type: fastest," ...
5+"waypoints: [[2.24559,48.88562],[2.27670,48.77927]]," ...
6+"avoid: [unpaved,highway]," ...
7+"details: full," ...
8+"alternatives: 0," ...
9+"profile: city," ...
10+"terrain: false," ...
11+"hillskip: 0.5," ...
12+"emergency: false," ...
13+"debug: true," ...
14+"locale: en" ...
15+"}"
16
17[result, status] = http_post("https://routes.magiclaneapis.com/v1", toJSON(fromJSON(jsondata)), format="json", auth="YOUR_API_KEY_TOKEN" );
18
19toJSON(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:
1{
2 "transport": "bike",
3 "type": "fastest",
4 "waypoints": [[2.24559,48.88562],[2.27670,48.77927]],
5 "avoid": ["unpaved","highway"],
6 "details": "full",
7 "alternatives": 2,
8 "profile": "city",
9 "terrain": false,
10 "hillskip": 0.8,
11 "emergency": false,
12 "debug": true,
13 "locale": "fr",
14 "track":
15 {
16 "accurate": false,
17 "restrictions": false,
18 "waypoint_index": 1,
19 "coords": [
20 [2.24388, 48.88392, 0.00000],
21 [2.24388, 48.88392, 0.00000],
22 [2.24388, 48.88392, 0.00000],
23 [2.24346, 48.88390, 0.00000],
24 [2.24304, 48.88387, 0.00000],
25 [2.24261, 48.88385, 0.00000],
26 [2.24135, 48.88378, 0.00000],
27 [2.24009, 48.88371, 0.00000],
28 [2.24009, 48.88371, 0.00000],
29 [2.23882, 48.88363, 0.00000],
30 [2.23756, 48.88356, 0.00000],
31 [2.23419, 48.88337, 0.00000],
32 [2.23124, 48.88320, 0.00000],
33 [2.22955, 48.88311, 0.00000],
34 [2.22786, 48.88301, 0.00000],
35 [2.22618, 48.88292, 0.00000],
36 [2.22491, 48.88285, 0.00000],
37 [2.22491, 48.88285, 0.00000],
38 [2.22281, 48.88273, 0.00000],
39 [2.22112, 48.88263, 0.00000],
40 [2.21986, 48.88256, 0.00000],
41 [2.21817, 48.88246, 0.00000],
42 [2.21648, 48.88237, 0.00000],
43 [2.21522, 48.88230, 0.00000],
44 [2.21396, 48.88222, 0.00000],
45 [2.21269, 48.88215, 0.00000],
46 [2.21185, 48.88210, 0.00000],
47 [2.21055, 48.88231, 0.00000],
48 [2.21055, 48.88231, 0.00000],
49 [2.20886, 48.88221, 0.00000],
50 [2.20675, 48.88209, 0.00000]
51 ]
52 }
53}
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)
1curl "https://routes.magiclaneapis.com/v1" -X POST -H "Content-Type: application/json" -H "Authorization: YOUR_API_KEY_TOKEN" -d \
2'{
3...
4}'
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: |
|
---|---|
key |
value |
|
Specify the transportation mode to be used on the route Type: Default value: Possible values: “car”, “bike”, “pedestrian”, “lorry” (truck), “public” (transport) |
|
Specify the route evaluation type Type: Default value: Possible values: “fastest”, “shortest” (car/lorry), “economic” (bike) |
(mandatory parameter) |
The route waypoints specified in visit order Type: array of coords in format 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 |
|
The routing avoidance - what to avoid along the route Type: Default value: empty Possible values: “highway”, “ferry”, “toll”, “unpaved”, “turnaround”, “traffic” (car/lorry), “roadblocks” (car/lorry) |
|
Route result details Type: Default value: Possible values: “full” - route path + instructions “path” - route path only “timedistance” - route time + distance |
|
The number of requested alternate routes to be computed, not including the main route result Type: Default value: Internally the services will trim the requested alternatives to max 2 for car/lorry/bike/pedestrian, 10 for public (transport) |
|
Specify the route transport profile Type: Default value: Possible values: “city”, “road”, “cross”, “mountain” (bike); “walk”, “hike” (pedestrian) |
|
Include terrain information in the result Type: Default value: |
|
Hill avoidance factor (bike only) Type: Default value: |
|
Route over existing input track - options Type: structure |
track: { (property within track structure) |
Apply accurate route match on map data for track points Type: Default value: Should be Should be |
track: {
(property within track structure) |
Apply map restrictions when routing over track Type: Default value: |
track: { (property within track structure) |
List of 2 or more coordinates to include in route Type: array of coords in format Track coordinates in lon, lat, alt (optional). At least 2 track coordinate entries should be provided. |
track: {
(property within track structure) |
The track waypoint 0-based index in the route waypoints Type: Default value: track waypoint is added at end of route waypoints Inserting the track in the route |
|
Apply emergency profile to the route Type: Default value: Vehicle will be allowed on emergency tagged links, CDMs with emergency tag will be ignored, etc. |
|
If true, the JSON output is formatted for easy reading Type: Default value: |
|
The ISO 639-1 language for the routing result Type: Default value: |
Response¶
MagicLane header
1{
2 "info": {
3 "copyrights": [
4 "MagicLane"
5 ]
6 },
7 "routes": [
8 {
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.
1 "distance": 16552,
2 "time": 3709,
3 "bbox": [
4 2.2274959375000000783,
5 48.779269999999996799,
6 2.2944959374999998047,
7 48.885850625000003333
8 ],
Route path points
The longitude,latitude coordinate pair of points along the route.
1 "points": {
2 "type": "LineString",
3 "coordinates": [
4 [
5 2.2456190624999998739,
6 48.885588437499997383
7 ],
8 [
9 2.2459999999999999964,
10 48.885763124999996876
11 ],
12 // ...
13 ]
14 },
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);
1 "instructions": [
2 {
3 "id": 22,
4 "distance": 0,
5 "time": 0,
6 "heading": 55.10716878309646205,
7 "turn": "",
8 "follow": "Follow Rue Roque de Fillol for 50 m.",
9 "street": [
10 "Rue Roque de Fillol"
11 ]
12 },
13 // ...
14 ],
Terrain/topography elevation
elevation in meters above sealevel, at a 30 meter horizontal sample resolution;
1"terrain": {
2 "elevations": [
3 38.69173431396484375,
4 39.398284912109375,
5 39.90000152587890625,
6 // ...
7 ],
8 "total_up": 112.6616668701171875,
9 "total_down": 42.85340118408203125
special climb sections
1 "climb_sections": [
2 {
3 "start": 9360,
4 "end": 12450,
5 "slope": 6.2290167808532714844,
6 "grade": 3
7 }
8 ]
9 }
10
11 }
12 ]
13}