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, and the like. 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.

When executed, the code performs the following operations:

  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. Instantiates the Routing Service v8.
  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({
  'apikey': '{YOUR_API_KEY}'
});
// 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.vector.normal.map,
  {
    zoom: 10,
    center: { lat: 52.51, lng: 13.4 }
  });

// Create the parameters for the routing request:
var routingParameters = {
  'routingMode': 'fast',
  'transportMode': 'car',
  // The start point of the route:
  'origin': '50.1120423728813,8.68340740740811',
  // The end point of the route:
  'destination': '52.5309916298853,13.3846220493377',
  // Include the route shape in the response
  'return': 'polyline'
};

// Define a callback function to process the routing response:
var onResult = function(result) {
  // ensure that at least one route was found
  if (result.routes.length) {
    result.routes[0].sections.forEach((section) => {
         // Create a linestring to use as a point source for the route line
        let linestring = H.geo.LineString.fromFlexiblePolyline(section.polyline);

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

        // Create a marker for the start point:
        let startMarker = new H.map.Marker(section.departure.place.location);

        // Create a marker for the end point:
        let endMarker = new H.map.Marker(section.arrival.place.location);

        // 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.getViewModel().setLookAtData({bounds: routeLine.getBoundingBox()});
    });
  }
};

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

// 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.

The map after calculating the route
Figure 1. The map after calculating the route

For additional information regarding the features and use of the Routing API v8, see the online documentation on here-tech.skawa.fun.

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 a style that describes the dash of the polyline.

//Within the onResult callback:

// Create an outline for the route polyline:
var routeOutline = new H.map.Polyline(linestring, {
  style: {
    lineWidth: 10,
    strokeColor: 'rgba(0, 128, 255, 0.7)',
    lineTailCap: 'arrow-tail',
    lineHeadCap: 'arrow-head'
  }
});
// Create a patterned polyline:
var routeArrows = new H.map.Polyline(linestring, {
  style: {
    lineWidth: 10,
    fillColor: 'white',
    strokeColor: 'rgba(255, 255, 255, 1)',
    lineDash: [0, 2],
    lineTailCap: 'arrow-tail',
    lineHeadCap: 'arrow-head' }
  }
);
// create a group that represents the route line and contains
// outline and the pattern
var routeLine = new H.map.Group();
routeLine.addObjects([routeOutline, routeArrows]);

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

The map after adding a route line with arrows
Figure 2. The map after adding a route line with arrows

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.

When executed, the code performs the following operations:

  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 v7.
  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.getViewModel().setLookAtData({bounds: isolinePolygon.getBoundingBox()});
};

// 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:

The map after adding the isoline polygon
Figure 3. The map after adding the isoline polygon

For additional information regarding the features and use of the Routing API v7, see the online documentation on here-tech.skawa.fun.

results matching ""

    No results matching ""