Routing API

Overview

Routing API is about to work with routes and itineraries using json file format.
There are functions, which allow sending json route or itinerary for route calculation and subsequent navigation,
and functions, which allow retrieving actual route real-time status either at a detail of waypoints or even geometry.

You can create a new itinerary through AddItinerary or delete an existing one through DeleteItinerary.
Itineraries are defined with a list of waypoints, each represented primarily with gps coordinates and optionally with a time window, which defines a desired visiting time. And then you can send itinerary to navigation through SetRoute and in real time to monitor the itinerary execution through GetRouteStatus. The exact route geometry calculated by routing engine can be retrieved through GetRoute.

You can also load a route generated in an external system through LoadComputedRoute and put it to navigation. There are few json as well as other formats specified for the import. External routes are defined with a list of waypoints along with an exact geometry to be followed in between waypoints. Such route can be monitored during navigation at a waypoint level through GetRouteStatus as well as with a full geometry by GetRoute.

The itinerary and route functions operate with several json objects, namely:

  • Json itinerary object is used with AddItinerary, SetRoute
  • Json route object is used with LoadComputedRoute, GetRoute
  • Json status object is used with GetRouteStatus

Json Itinerary object

The json specification of the supported structure is shown in the diagram bellow.
The fields denoted with * are mandatory.

Table of json fields

Field Type Default value Description
name string   name of the itinerary
description string   short description
version string   file format version, supported are: 2.1, 2.2
allowItineraryEdit bool true allows or disallows manual edit of itinerary once loaded into navigation
routeComputeType string: car|truck|bus|camper|van|pedestrian car defines the vehicle routing preference applied between waypoints or for the whole itinerary
routeComputeMethod string: fastest|shortes|economical fastest defines the routing method preference applied between waypoints
avoidTollRoads bool false defines the routing attribute for toll roads
avoidSpecialArea bool false defines the routing attribute for special city zones
avoidMotorways bool false defines the routing attribute for motorways/highways
avoidUnpavedRoads bool false defines the routing attribute for unpaved roads
ignoreProhibited bool false defines the routing attribute for ignoring prohibited maneuvers
ignoreOneWays bool false defines the routing attribute for ignoring oneway driving rule
lat int 0 latitude position defined as WGS84 multiplied by 100,000
lon int 0 longitude position defined as WGS84 multiplied by 100,000
lonNavi int =lon navigable longitude position defined as WGS84 multiplied by 100,000
latNavi int =lat navigable latitude position defined as WGS84 multiplied by 100,000
hitRadius int 50 distance in meters from the waypoint considered as visiting criteria
hitSpeed int 50 reference speed at which hitRadius holds exactly, for higher speeds the hitRadius is linearly increased
type string: start|via|finish via the type of waypoint
waypointId int -1 user defined identification of the waypoint
caption string waypoint name shown in the route summary, by default the name is indicated by its exact address
startTime string   defines the starting time of a time window in the UTC format, example 2015-03-06T14:15:00Z
endTime string   defines the ending time of a time window in the UTC format, example 2015-03-06T14:30Z
stopDelay int 0 defines the service time in seconds expected to spent on the waypoint

Example of the itinerary with 3 waypoints:

{
"name":     "Itinerary-627",
"version":  "2.2",
"routeParts":
   [{
        "directives":
        {
            "routeComputeType": "car",
            "routeComputeMethod":   "fastest",
            "avoidTollRoads":       true,
            "avoidSpecialArea": false,
            "avoidMotorways":   false,
            "avoidFerries":             false,
            "avoidUnpavedRoads":    true,
            "ignoreProhibited": false,
            "ignoreOneWays":        false
        },
        "waypointFrom":
        {
            "timeWindow":
            {
                "startTime": "2015-06-16T14:00:00Z",
                "endTime": "2015-06-16T14:30:30Z",
                "stopDelay": 120
             },
            "lon":              1711001,
            "lat":              4814955,
            "type":          "via",
            "waypointId":   1,
            "hitRadius":    100
        },
        "waypointTo":
        {
            "lon":           1710758,
            "lat":           4814795,
            "type":          "via",
            "waypointId":   2,
            "hitRadius":    100
        }
   },{
        "directives":
        {
            "routeComputeType": "car",
            "routeComputeMethod":   "shortest"
        },
        "waypointTo":
        {
            "timeWindow":
            {
                "startTime": "2015-06-16T15:00:00Z",
                "endTime": "2015-06-16T15:30:30Z",
                "stopDelay": 120
            },
            "lon":              1710375,
            "lat":              4814391,
            "type":             "finish",
            "waypointId":   3,
            "hitRadius":    100
        }
    }]
}

Json status object

The specification of the supported json fields is shown in the diagram bellow. Some fields denoted by * can be omitted, which is in case the value is not valid. E.g. the field timeArrival when the waypoint is not yet visited.

Table of json fields

Field Type Default value Description
timeStamp string - the timestamp of the current status
numVisited int - number of waypoints already visited. The start waypoint is counted too.
numUnvisited int - number of waypoints not yet visited
numPredictedLateArrivals int - number of waypoints predicted to have late arrivals
numPredictedEarlyArrivals int - number of waypoints predicted to have early arrivals
timeRemaining int - time in seconds estimated to reach the finish
distanceRemaining int - distance in meters estimated to reach the finish
distancePassed int - distance in meters passed from start
lat int - latitude position defined as WGS84 multiplied by 100,000
lon int - longitude position defined as WGS84 multiplied by 100,000
lonNavi int - navigable longitude position defined as WGS84 multiplied by 100,000
latNavi int - navigable latitude position defined as WGS84 multiplied by 100,000
hitRadius int - distance in meters from the waypoint considered as visiting criteria
hitSpeed int - reference speed at which hitRadius holds exactly, for higher speeds the hitRadius is linearly increased
caption string waypoint name shown in the route summary, by default the name is indicated by its exact address
type string: start|via|invisible|finish - the type of waypoint
status string: visited|unvisited|none - the status of the waypoint
edited bool - indicates whether the waypoint was manually edited since itinerary loading into navigation
timeArrival string - defines the actual arrival time at the waypoint in the UTC format if already visited, example 2015-03-06T14:15:00Z
estimatedTimeArrival string - defines the estimated arrival time at the waypoint in the UTC format if not yet visited, example 2015-03-06T14:30Z
realtimeStatus:
timeRemaining
int - time in seconds estimated to reach the waypoint
realtimeStatus:
distanceRemaining
int - distance in meters estimated to reach the waypoint

Example of the itinerary status with 3 waypoints:

{
    "timeStamp": "2015-06-28T16:10:37Z",
    "numVisited": 1,
    "numUnvisited": 2,
    "numPredictedLateArrivals": 0,
    "numPredictedEarlyArrivals": 1,
    "timeRemaining": 1312,
    "distancePassed": 0,
    "distanceRemaining": 8610,
    "waypoints":
    [{
            "lon":  1711468,
            "lat":  4813110,
            "type": "start",
            "waypointId":   1,
            "hitRadius":    200,
            "timeWindow":
            {
                "startTime":  "2015-06-28T16:00Z",
                "endTime":  "2015-06-28T16:30Z",
                "stopDelay":  180
            },
            "realtimeStatus":
            {
                "status":  "visited",
                "edited":  false
            }
    }, {
            "lon":  1713067,
            "lat":  4816062,
            "type":  "via",
            "waypointId":  2,
            "hitRadius":  200,
            "timeWindow":
            {
                "startTime":  "2015-06-28T16:15Z",
                "endTime":  "2015-06-28T16:30Z",
                "stopDelay":  180
            },
            "realtimeStatus":
            {
                "status":  "unvisited",
                "estimatedTimeArrival": "2015-06-28T16:19:25Z",
                "timeRemaining":  528,
                "distanceRemaining":  5018,
                "edited":  false
            }
    }, {
            "lon":  1710000,
            "lat":  4814722,
            "type": "finish",
            "waypointId":   3,
            "hitRadius":    200,
            "timeWindow":
            {
                "startTime":  "2015-06-28T17:00Z",
                "endTime":  "2015-06-28T17:30Z",
                "stopDelay":  180
            },
            "realtimeStatus":
            {
                "status":  "unvisited",
                "estimatedTimeArrival":  "2015-06-28T16:29:29Z",
                "timeRemaining":  1132,
                "distanceRemaining":  8610,
                "edited":  false
            }
        }]
}

Json Route object

This json object is used with LoadComputedRoute for importing routes generated in external systems, e.g. the export of a Route Optimization software.
Currently we support two formats: Sygic-native format (sif files) and PTV-compatible format.
Sygic SDK function automatically recognizes the used format.

1. PTV-compatible format

These files can be obtained through exports from PTV route calculation services, like xServer, etc.
The json specification of the supported structure:

Table of json fields

Field Type Default value Description
x double n/a longitude position defined as WGS84 multiplied by 100,000
y double n/a latitude position defined as WGS84 multiplied by 100,000
polyIdx int n/a index reference to the points array defining the GPS point as the waypoint/station
WayPointType string  n/a the type of waypoint, possible values are START, VIA, DEST.

Example

{
  "polygon": {
    "lineString": {
      "points": [
        {
          "x": 1712571,
          "y": 4814643
        },
        {
          "x": 1712486,
          "y": 4814651.5
        },
        {
          "x": 1712461,
          "y": 4814652
        },

...
        {
          "x": 1712302,
          "y": 4814263
        },
        {
          "x": 1712355,
          "y": 4814257
        },
        {
          "x": 1712468,
          "y": 4814248
        }
      ]
    }
  },
  "stations": [
    {
      "polyIdx": 0,
      "wayPointType": "START"
    },
    {
      "polyIdx": 44,
      "wayPointType": "VIA"
    },
    {
      "polyIdx": 83,
      "wayPointType": "DEST"
    }
  ]
}

2. Sygic-native format

The json specification of the supported structure (version 1.1) :

Table of json fields

Field Type Default value Description
name string "" route name appearing in route info dialog
description string "" route description appearing in route info dialog
version string n/a used version, currently available 1.0 and 1.1
lat int n/a latitude position defined as WGS84 multiplied by 100,000
lon int n/a longitude position defined as WGS84 multiplied by 100,000
type string n/a the type of the waypoint, possible values are start, via, finish.
waypointId int -1 user defined identification of the waypoint
id int -1 user defined identification of the road

Example

{
"name":     "Route-77",
"version":  "1.1",
"routeParts":
   [{
        "waypointFrom":
        {
            "lat":          4814951,        
            "lon":          1711001,
            "type":         "start"
        },
        "waypointTo":
        {
            "lat":           4814791,       
            "lon":           1710751,
            "type":          "via"
        }
        "roads":
        [
          {  
             "id": 1, 
             "points": [ { "lat": 4814952, "lon": 1711002 }, { "lat": 4814953, "lon": 1711003 }, { "lat": 4814954, "lon": 1711004 } ... ]
          },
          {  "id": 2,
             "points": [ { "lat": 4814955, "lon": 1711005 }, { "lat": 4814956, "lon": 1711006 }, { "lat": 4814957, "lon": 1711007 } ... ]
          }
          ...
        ]
   },{
        "waypointTo":
        {
            "lat":          4814391,
            "lon":          1710371,            
            "type":         "finish"
        }
        "roads":
        [
          {  
             "id": 25, 
             "points": [ { "lat": 4814791, "lon": 1710751 }, { "lat": 4814792, "lon": 1710752 }, { "lat": 4814793, "lon": 1710753 } ... ]
          }
          ...
        ]       
   }]
}

AddItinerary

AddItinerary adds itinerary to the system database for immediate or later usage. It takes as an input json string, which defines the itinerary. The itinerary is basically a list of waypoints, each denoted as START, VIA or FINISH. Formally the itinerary is comprised of list of routeparts, while each routepart defines start and end waypoint.
Another input to the function is the name of the itinerary, which serves as a reference for function to put it into route calculation and navigation, which is SetRoute.
Check details of AddItinerary in the reference manual.
Please note AddItinerary with json support is only available with the 3D version of navigation.

Example

This example demonstrates how to create a new itinerary in a json format.
We create an itinerary with 3 waypoints, each defined with GPS coordinates, time windows and type of the waypoint.
The 3 waypoints are delivered in a ArrayList.
The result of the demo function is placing an itinerary into application ready to be used for navigation.
In the example we use the json library "json.org", which offers convenient manipulations with json strings and objects for construction and parsing.
For the definition of Sygic Json strings please refer to the section Json Itinerary object above.

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    ...

    void demo()
    {       
        ArrayList<TwWaypoint> lst = new ArrayList<TwWaypoint>();
        lst.add(new TwWaypoint(48.11468, 17.13110, "2017-06-28T16:00:00Z", "2017-06-28T16:00:00Z", "start"));
        lst.add(new TwWaypoint(48.13067, 17.16062, "2017-06-28T17:00:00Z", "2017-06-28T17:30:00Z", "via"));
        lst.add(new TwWaypoint(48.10039, 17.14722, "2017-06-28T18:00:00Z", "2017-06-28T18:30:00Z", "finish"));

        String json = CreateJsonItinerary(lst);
        String itname = "itin-63";
        try {
            ApiItinerary.addItinerary(json, itname, 0);
        } catch (GeneralException e) {
            e.printStackTrace();
        }
    }

    // Json construction and parsing helpers

    public class TwWaypoint {
        double lat;
        double lon;
        String dtStart;
        String dtEnd;
        String wpType;
        public TwWaypoint (double lat, double lon, String dtStart, String dtEnd, String wpType)
        {
            this.lat = lat;
            this.lon = lon;
            this.dtStart = dtStart;
            this.dtEnd = dtEnd;
            this.wpType = wpType;
        }
    }   

    JSONObject createWaypoint(double lat, double lon, String time1, String time2, int waypointId, String wtype)
    {
        int ilat = (int)(lat * 100000);
        int ilon = (int)(lon * 100000);

        JSONObject obj = new JSONObject();
        try {
           obj.put("lat", Integer.valueOf(ilat));
           obj.put("lon", Integer.valueOf(ilon));
           obj.put("waypointId", Integer.valueOf(waypointId));
           obj.put("hitRadius", Integer.valueOf(200));
           obj.put("type", wtype);
           if (time1 != null && time2 != null)
           {
               JSONObject tw = new JSONObject();
               tw.put("startTime", time1);
               tw.put("endTime", time2);
               tw.put("stopDelay", Integer.valueOf(180));
               obj.put("timeWindow", tw);
           }
        }
        catch (JSONException e)
        {
            obj = null;
        }
        return obj;
    }

    JSONObject createRoutepart(JSONObject wpFrom, JSONObject wpTo)
    {
        JSONObject obj = new JSONObject();
        try {
           if (wpFrom != null) obj.put("waypointFrom", wpFrom);
           obj.put("waypointTo", wpTo);
        }
        catch (JSONException e)
        {
            obj = null;
        }
        return obj;
    }

    protected String CreateJsonItinerary(ArrayList<TwWaypoint> lst)
    {
        try {
            JSONArray routeparts = new JSONArray();
            JSONObject routepart;
            JSONObject wpFrom;
            JSONObject wpTo;
            for (int i = 1; i < lst.size(); i++)
            {
               wpFrom = null;
               if (i == 1) wpFrom = createWaypoint(lst.get(0).lat, lst.get(0).lon, lst.get(0).dtStart, lst.get(0).dtEnd, 0, lst.get(0).wpType);
               wpTo = createWaypoint(lst.get(i).lat, lst.get(i).lon, lst.get(i).dtStart, lst.get(i).dtEnd, i, lst.get(i).wpType);
               routepart = createRoutepart(wpFrom, wpTo);
               if (routepart == null) return null;
               routeparts.put(routepart);
            }
            JSONObject json = new JSONObject();
            json.put("name", "Bratislava-pickup");
            json.put("version", "2.2");
            json.put("routeParts", routeparts);
            return json.toString();
        } catch (JSONException e) {
              e.printStackTrace();
        }
        return null;
   }

DeleteItinerary

DeleteItinerary deletes the given itinerary from the system database referenced by its name.
Check details of DeleteItinerary in the reference manual.

    void demo()
    {       
        try {
            ApiItinerary.deleteItinerary(json, "itin-63", 0);
        } catch (GeneralException e) {
            e.printStackTrace();
        }
    }

SetRoute

SetRoute sets the given itinerary referenced by its name for route calculation. And if successful, the navigation mode is immediately switched on and a driver is navigated over the waypoints.
Check details of SetRoute in the reference manual.

Example

    void demo()
    {       
        String json = CreateJsonItinerary(lst);
        String itname = "itin-63";
        try {
            ApiItinerary.addItinerary(json, itname, 0);
            ApiItinerary.setRoute(itname, 0);
        } catch (GeneralException e) {
            e.printStackTrace();
        }
    }

GetRouteStatus

Example

This example demonstrates how to retrieve current status of the itinerary execution, here placed into a user-defined formatted string.
When retrieving the execution status we can read out e.g. the information about the number of visited and unvisited waypoints, and then per each waypoint more detailed info such as ETA, remaining distance and time to the waypoint, etc.
In the example we used the json library json.org, which offers convenient manipulations with json strings and objects for construction and parsing.
Check details of GetRouteStatus in the reference manual.
Please note GetRouteStatus is only available with the 3D version of navigation.

   void demo()
   {
    String status;
    try {
        status = ApiNavigation.getRouteStatus(0);
    } catch (GeneralException e) {
        e.printStackTrace();
        return;
    }
    ParseRouteStatus(status);
   }

   protected String ParseRouteStatus()
   {
        try {           
            JSONObject jout = new JSONObject(ret);
            String n1 = jout.getString("numVisited");
            String n2 = jout.getString("numUnvisited");
            String n3 = jout.getString("numPredictedLateArrivals");
            String n4 = jout.getString("numPredictedEarlyArrivals");
            JSONArray jArr = jout.getJSONArray("waypoints");

            String output = "visited/unvisited/early/late:" + n1 + "/" + n2 + "/" + n3 + "/" + n4 + "\n";
            for (int i=0; i &lt; jArr.length(); i++)
            {
                JSONObject obj = jArr.getJSONObject(i);
                String waypointId = obj.getString("waypointId");              // retrieve waypoint id
                JSONObject rts = obj.getJSONObject("realtimeStatus");
                String status = rts.getString("status");                      // retrieve status
                String eta = "n/a";
                int drem = -1;
                int trem = -1;
                if (status.compareTo("unvisited") == 0)
                {
                   eta = rts.getString("estimatedTimeArrival");     // retrieve eta to the waypoint
                   drem = rts.getInt("distanceRemaining");          // retrieve remaining distance in meters
                   trem = rts.getInt("timeRemaining");              // retrieve remaining time in seconds
                }
                output += "waypointId=" + waypointId + ",";
                output += "status=" + status + "\n";
                output += "eta=" + eta + "\n";
                output += "distanceRemaining=" + String.valueOf(drem) + "\n";
                output += "timeRemaining=" + String.valueOf(trem) + "\n";
            }
            return output;

        catch (JSONException e) {
             e.printStackTrace();
        }
        return null;

   }

LoadComputedRoute

LoadComputedRoute imports a given route referenced by its filename into navigation engine. And if successful, the navigation mode is immediately switched on and a driver is navigated over the waypoints and following the route geometry in a magnetic way.
In case a deviation from route occurs the recalculation is triggered, which tries to navigate driver back to the original route in a most efficient way.
Check details of LoadComputedRoute in the reference manual.
Please note for the function to work the license file must contain the permission: precomputedRoutes=yes, otherwise the exception license error is raised.

Example

void demo()
{
    String filename = getSdcardStorage() + "/routes/route_66.json";
    try {
        ApiNavigation.loadComputedRoute(filename, 0);
    } catch (LoadRouteException e) {
        e.printStackTrace();
    }
}

GetRoute

GetRoute retrieves currently calculated route, containing waypoints and geometry, in a json string.
If there is no route calculated the functions returns exception.
Check details of GetRoute in the reference manual.

Example

The sample code retrieves the route geometry in the PTV format.

class GpsPoint
{
    double lat;
    double lon;
}

void demo()
{
    String json = null;
    try {
       json = ApiNavigation.getRoute(1, 0, 0);
       ArrayList<GpsPoint> gps = ParseToPolyline(json);
    } 
    catch (GeneralException e) {
       e.printStackTrace();
    }
}

CalculateRoute

CalculateRoute executes route calculation(s) in a background possible for multiple origins and destinations, resulting in a so called distance matrix (a.k.a distance/time matrix). The calculation is a background process and does not affect a currently calculated route used for navigation.
The input is defined as a json structure expressing origins and destinations, and the output is produced in a json structure expressing distance and duration for each origin-destination pair as shown bellow. The distance is given in meters and the duration in seconds. In case a specific origin-destination cannot be calculated (typically due to out of map problem or map discontinuity) the distance and time results are given as -1, as well as the result value is different from 1.

Please note the function is currently availabe only in a beta release and will appear in the coming release 13.7.2.

Json input and output

Example with 2x2 matrix is as follows

Input

{
  "origins": [
    {
      "lat": 48.11,
      "lon": 17.13
    },
    {
      "lat": 48.12,
      "lon": 17.12
    }
  ],
  "destinations": [
    {
      "lat": 48.13,
      "lon": 17.11
    },
    {
      "lat": 48.12,
      "lon": 17.10
    }
  ]
}

Output

{
"distanceMatrix":[
{"origin": 0, "destination": 0, "result": 1, "duration": 745, "distance": 3669},
{"origin": 0, "destination": 1, "result": 1, "duration": 487, "distance": 3946},
{"origin": 1, "destination": 0, "result": 1, "duration": 243, "distance": 1971},
{"origin": 1, "destination": 1, "result": 1, "duration": 255, "distance": 1880}
]}

Example

This example calculates 2x2 distance/time matrix. The result is parsed using JSON object library and each pair of origin-destination is reported on a log console.

void demo()
{
    String jsonin =
      "{" +
    "\"origins\":[{\"lat\": 48.11, \"lon\": 17.13}, {\"lat\": 48.12, \"lon\": 17.12}]," +
    "\"destinations\":[{\"lat\": 48.13, \"lon\": 17.11}, {\"lat\": 48.12, \"lon\": 17.10}]" +
      "}";

    String jsonout = null;
    try {
    jsonout = ApiItinerary.calculateRoute(jsonin, 0);
    } catch (GeneralException e) {
    Log.d("Error", "calculateRoute problem");
    return;
    }

    JSONObject jo = null;
    try {
    jo = new JSONObject(jsonout);
    } catch (JSONException e) {
    Log.e("Error", "json format problem");
    return;
    }

    for (int i = 0; i < 4; i++)
    {
    int time;
    int distance;
    try {
        time = jo.getJSONArray("distanceMatrix").getJSONObject(i).getInt("duration");
        distance = jo.getJSONArray("distanceMatrix").getJSONObject(i).getInt("distance");
    } catch (JSONException e) {
        Log.e("Error", "json format problem");
        continue;
    }
    Log.i("Info", "route:"+i + " time:" + time + " distance:" + distance);
    }

}

Events

API Events allow monitoring of route calculation events with a possibility to react on it.
There are various events available.

Event Description
EVENT_ROUTE_COMPUTED occurs when new route calculation or recalculation has been finished
EVENT_ROUTE_USERCANCEL occurs when user cancels navigation on a calculated route prematurely either through GUI or API function
EVENT_ITINERARY_CHANGED occurs when user manually over GUI has changed the itinerary set up, e.g. removed or modified a waypoint

Check for more on Api Events in the reference manual.

Exceptions

Problems with SetRoute function are signaled with API Exceptions.
There are various exceptions possible.

Exception Description
NavigationException -4 occurs when a destination is not reachable, meaning there is no route found to connect a start with a destination. This can e.g. happen when a country map is missing, which would otherwise make a connection possible.
NavigationException -5 occurs when a user prematurely cancels a route in calculation progress
NavigationException -6 occurs when there is no valid GPS signal to incur starting point and there is no prior knowledge of a recent position
NavigationException -9 occurs when the route calculation cannot map match one or more waypoints of the route. Possibly the destination is out of map. This can e.g. happen when latitude or longitude positions are incorrectly formatted or swapped.