Maps API for JavaScript Developer's Guide

Routing

Route planning and navigation are the most commonly used applications of location-based services. With the Maps API, you can calculate optimal routes that match your own calculation criteria, are based on up-to-date map data, and take into account real-time traffic information.

The API offers global coverage of streets and highways, allowing you to create routes that reflect customizable modes such as fastest, shortest, avoiding toll roads or avoiding ferries, etc. There is also support for utilizing historical speed patterns as an optimization for routes depending on the time of day.

Through the service module (mapsjs-service.js), the Maps API provides direct access to the HERE Routing API to retrieve route information, including route shapes. Route information returned by the HERE Routing API can be used in a many different ways to suit the requirements of an application, although the examples below confine themselves to basic scenarios.

Displaying a Route on the Map

The following example shows how to obtain a route from Frankfurt to Berlin and display the result on a map.

The code:

  1. Obtains a Platform object, supplying the authentication and authorization credentials.
  2. Instantiates the map, specifying the map type, zoom and the location of the center.
  3. Defines a set of routing parameters to be used by the back end service when it calculates the route – the parameters indicate the fastest route, the start point and end points as geographical coordinates, and the representation mode 'display'.
  4. Defines a callback function to be called if the routing request is successful – it receives the route object as a parameter, retrieves from it the vertices of the route and converts them to a LineString object, creates a polyline to represent the route, creates markers to indicate the start and end point of the route, adds the polyline and the markers to the map, and finally adjusts the map view bounds to ensure the entire route is visible.
  5. Obtains an object representing the routing service stub.
  6. Calls the method calculateRoute() on the routing service, passing to it the parameter object and the callback functions.
// Instantiate a map and platform object:
var platform = new H.service.Platform({
  'app_id': '{YOUR_APP_ID}',
  'app_code': '{YOUR_APP_CODE}'
});
// Retrieve the target element for the map:
var targetElement = document.getElementById('mapContainer');

// Get the default map types from the platform object:
var defaultLayers = platform.createDefaultLayers();

// Instantiate the map:
var map = new H.Map(
  document.getElementById('mapContainer'),
  defaultLayers.normal.map,
  {
  zoom: 10,
  center: { lat: 52.51, lng: 13.4 }
  });

// Create the parameters for the routing request:
var routingParameters = {
  // The routing mode:
  'mode': 'fastest;car',
  // The start point of the route:
  'waypoint0': 'geo!50.1120423728813,8.68340740740811',
  // The end point of the route:
  'waypoint1': 'geo!52.5309916298853,13.3846220493377',
  // To retrieve the shape of the route we choose the route
  // representation mode 'display'
  'representation': 'display'
};

// Define a callback function to process the routing response:
var onResult = function(result) {
  var route,
    routeShape,
    startPoint,
    endPoint,
    linestring;
  if(result.response.route) {
  // Pick the first route from the response:
  route = result.response.route[0];
  // Pick the route's shape:
  routeShape = route.shape;

  // Create a linestring to use as a point source for the route line
  linestring = new H.geo.LineString();

  // Push all the points in the shape into the linestring:
  routeShape.forEach(function(point) {
    var parts = point.split(',');
    linestring.pushLatLngAlt(parts[0], parts[1]);
  });

  // Retrieve the mapped positions of the requested waypoints:
  startPoint = route.waypoint[0].mappedPosition;
  endPoint = route.waypoint[1].mappedPosition;

  // Create a polyline to display the route:
  var routeLine = new H.map.Polyline(linestring, {
    style: { strokeColor: 'blue', lineWidth: 10 }
  });

  // Create a marker for the start point:
  var startMarker = new H.map.Marker({
    lat: startPoint.latitude,
    lng: startPoint.longitude
  });

  // Create a marker for the end point:
  var endMarker = new H.map.Marker({
    lat: endPoint.latitude,
    lng: endPoint.longitude
  });

  // Add the route polyline and the two markers to the map:
  map.addObjects([routeLine, startMarker, endMarker]);

  // Set the map's viewport to make the whole route visible:
  map.setViewBounds(routeLine.getBounds());
  }
};

// Get an instance of the routing service:
var router = platform.getRoutingService();

// Call calculateRoute() with the routing parameters,
// the callback and an error callback function (called if a
// communication error occurs):
router.calculateRoute(routingParameters, onResult,
  function(error) {
    alert(error.message);
  });

Note that the member elements of the routingParameters object literal directly map to the URL parameters required by the HERE Routing API. The parameter object can include any parameters recognized by the Routing API, offering complete flexibility in defining a route calculation request.

The map below shows the result of the route calculation, with the start and end of the route from Frankfurt am Main to Berlin in Germany indicated by markers with default icons, and the route itself shown as a green polyline.

Figure 1. The map after calculating the route

Showing Route Direction Arrows

The API offers a way to render arrows on the route polyline to indicate the direction of travel. The code below enhances the onResult callback from the previous example by providing an arrows object to the Polyline constructor.

//Within the onResult callback:

// Create a polyline to display the route
routeLine = new H.map.Polyline(linestring, {
  style: { lineWidth: 10 },
  arrows: { fillColor: 'white', frequency: 2, width: 0.8, length: 0.7 }
});

The following image shows how the route appears on the map.

Figure 2. The map after adding a route line with arrows
Note: Arrow styles can also be set after the instantiation of a polyline by calling the method setArrows() on a polyline instance.

Isoline Routing

The following example shows how to calculate an isoline representing points that lie no further than a 15 minutes' car journey from the center of Berlin (in fact, the isoline describes an area – any destination in that area can be reached by car from the center of Berlin in 15 minutes or less). The example uses the RoutingService class to obtain the isoline.

In summary, the code:

  1. Creates a map instance showing the area around Berlin, Germany.
  2. Defines a routingParams object that specifies that the fastest routes for a car are to be calculated, sets the starting point and the time.
  3. Defines a callback to be invoked when the results of the routing request become available – the callback function creates a polygon, using the points of the calculated isoline, adds the polygon and a marker at the center of the isoline polygon to the map, sets the map view port so that the entire isoline is visible.
  4. Instantiates the Routing Service.
  5. Calls the Routing Service method calculateIsoline(), passing to it the parameter object and the success and error callbacks.
var routingParams = {
  'mode': 'fastest;car;',
  'start': 'geo!52.5,13.4',
  'range': '900',
  'rangetype': 'time'
};

// Define a callback function to process the isoline response.
var onResult = function(result) {
  var center = new H.geo.Point(
      result.response.center.latitude,
      result.response.center.longitude),
    isolineCoords = result.response.isoline[0].component[0].shape,
    linestring = new H.geo.LineString(),
    isolinePolygon,
    isolineCenter;

  // Add the returned isoline coordinates to a linestring:
  isolineCoords.forEach(function(coords) {
  linestring.pushLatLngAlt.apply(linestring, coords.split(','));
  });

  // Create a polygon and a marker representing the isoline:
  isolinePolygon = new H.map.Polygon(linestring);
  isolineCenter = new H.map.Marker(center);

  // Add the polygon and marker to the map:
  map.addObjects([isolineCenter, isolinePolygon]);

  // Center and zoom the map so that the whole isoline polygon is
  // in the viewport:
  map.setViewBounds(isolinePolygon.getBounds());
};

// Get an instance of the routing service:
var router = platform.getRoutingService();

// Call the Routing API to calculate an isoline:
router.calculateIsoline(
  routingParams,
  onResult,
  function(error) {
  alert(error.message);
  }
);

The resulting isoline is shown in the map image below:

Figure 3. The map after adding the isoline polygon

For additional information regarding the features and use of the Routing API, see the online documentation on developer.here.com.