NextBillion.ai Maps SDK Examples

The NextBillion.ai Maps SDK empowers developers with a robust JavaScript library designed to seamlessly integrate map-based functionality into web applications.

This JavaScript library, effortlessly incorporable into web applications, boasts an array of features, including:

  1. Displaying maps enriched with custom markers, polygons, and diverse shapes.
  2. Routing services for optimal navigation.
  3. Distance Matrix Services for precise distance calculations.
  4. Snap to Road/Map Matching Services for accurate location tracking.
  5. Customizable map and marker appearances.
  6. Support for multiple map data providers, including but not limited to OpenStreetMap, TomTom, and more.

By leveraging the NextBillion.ai Maps SDK, developers can expedite the integration of maps and location-based functionalities into their web applications, eliminating the complexities associated with interacting with various map providers and APIs.

Getting Started

To initiate the NextBillion.ai maps SDK in this notebook, load version 2.3.3 or above for optimal performance.

Input your assigned API key to activate the map panels below as you scroll through the page. If you require an API key, kindly reach out to us at [email protected].

Access the NB.ai v2 SDK stylesheet (CSS) via the provided link.

Setup

Initialize the NextBillion.ai (NB.ai) SDK with your API key. This step is a one-time process.


// Set API key
nextbillion.setApiKey(....);

To obtain your NextBillion.ai API key, reach out to [email protected].

Adding Stylesheet for NB.ai SDK


// Add the stylesheet for the NB.ai SDK 
link href="https://maps-gl.nextbillion.io/maps/v2/api/css" rel="stylesheet"

Map Styles

For map tiling services, various styles cater to different scenarios:

  • Day Style: Ideal for daylight hours, featuring bright colors and high contrast for readability and navigation.
  • Night Style: Tailored for nighttime, employing darker colors and lower contrast to reduce glare and enhance readability in low-light conditions.
  • Hybrid Style: A blend of day and night styles, incorporating both bright and dark colors. Additionally, it includes a satellite imagery layer for added context.

Selecting Map Style and Area of Interest (AOI)

Choose your preferred map style (Day, Night, Hybrid with satellite imagery). Any changes in map style will be reflected across all maps in the notebook.

Next, specify your Area of Interest (AOI) for each map. Altering the ‘aoi’ will be mirrored in all example maps.

  • Map Style – Day

Select the city for focus. For this notebook instance, we have set the city to Los Angeles.

Example 1: Hello Map

Let’s dive into the basics of map creation using the NextBillion.ai (NB.ai) Web SDK. In this example, we’ll craft a straightforward map that enables users to effortlessly navigate to various global cities using a city selector.


// Example Object
const mapStyle = {
  name: "Day",
  value: "https://api.nextbillion.io/maps/streets/style.json"
};

Here, the `mapStyle` object encapsulates the configuration for our map. The style named “Day” is associated with the URL pointing to the relevant style JSON file.

The following image visualizes the map generated with the help of Maps SDK.

Example 1 : Hello Map

This minimalistic example lays the foundation for more intricate map interactions. Stay tuned as we explore further functionalities and features within the NB.ai Web SDK.

Example 2: Directions

Let’s now venture into creating an interactive map that facilitates route planning between an origin, destination, and any waypoints you desire. With a simple click, you can set the origin and destination, and with subsequent clicks, introduce waypoints along the route. Feel free to adjust the route by moving each marker.

  1. Set Origin and Destination: Click on two locations to establish the initial origin and destination.
  1. Add Waypoints: Click again to include intermediate waypoints between the origin and destination.
  1. Route Adjustment: Each marker is movable, allowing you to fine-tune the route according to your preferences.

Note: Truck routing functionality is presently available in specific geographic regions, namely the United States and India.

Select Route Profile

Choose the preferred route profile, For this example, we set the route profile to “Automobile.”

Generated Output

This output provides detailed information about the generated route, including geometry, distance, duration, and legs.


// Example Object for the Global Route
const globalRoute = {
  geometry: "grm|_A`xlp`FjEiFyHcLgClCwHhInMjOrFjGbSnTdPfR|E`FbD…I?jE@zC?xWBjWBbX?dtAm@|lAgR_@{Gy@gGmBoUoOiHjMaErI",
  distance: 61668.9,
  duration: 2370.9,
  legs: [
    {
      distance: { value: 61668 },
      duration: { value: 2370 },
      steps: []
    }
  ]
};

The following code snippet is a part of a JavaScript program that utilizes the NextBillion.ai (NB.ai) mapping functionality to create an interactive map for directions.


directionsMap = {
  apiKey;
  yield container;
  let routePolyline = null;
  let originMarker = null;
  let destinationMarker = null;
  let waypoints = [];
  let pos = {
    lat: panel.city.centroid.split(",")[0],
    lng: panel.city.centroid.split(",")[1]
  };
  const mapDir = (container.value = new nextbillion.maps.Map({
    container: document.getElementById("mapDir"),
    center: pos,
    zoom: 8,
    maxZoom: 15,
    minZoom: 5,
    style: panel.styles.value,
    scrollZoom: true
  }));

  loadMapActions(mapDir);

  document.getElementById("clearMap").onclick = function () {
    clearMap(mapDir, originMarker, destinationMarker, waypoints);
    originMarker = null;
    destinationMarker = null;
    waypoints = [];
  };
  // click on map actions - create origin or destination
  mapDir.map.on("click", (e) => {
    if (!originMarker) {
      originMarker = new nextbillion.maps.Marker({
        color: "green",
        draggable: true,
       scale: 0.6
      })
        .setLngLat({
          lat: e.lngLat.lat,
          lng: e.lngLat.lng
        })
        .addTo(mapDir.map);
      originMarker.on("dragend", (e) => {
        routeMe(mapDir, originMarker, destinationMarker, waypoints, false);
      });
    } else if (!destinationMarker) {
      destinationMarker = new nextbillion.maps.Marker({
        color: "red",
        draggable: true,
        scale: 0.6
      })
        .setLngLat({
          lat: e.lngLat.lat,
          lng: e.lngLat.lng
        })
        .addTo(mapDir.map);
      destinationMarker.on("dragend", (e) => {
        routeMe(mapDir, originMarker, destinationMarker, waypoints, false);
      });
    } else {
      // waypoint
      var waypointMarker = new nextbillion.maps.Marker({
        color: "blue",
        draggable: true,
        scale: 0.6
      })
        .setLngLat({
          lat: e.lngLat.lat,
          lng: e.lngLat.lng
        })
        .addTo(mapDir.map);
      waypointMarker.on("dragend", (e) => {
        routeMe(mapDir, originMarker, destinationMarker, waypoints, false);
      });
      waypoints.push(waypointMarker);
    }
    if (originMarker && destinationMarker) {
      routeMe(mapDir, originMarker, destinationMarker, waypoints, false);
    }
  });
}

Let’s break down the key components:

1. Initialization

  • The `yield container;` statement suggests that this code might be part of a generator function.
  • Various variables (`routePolyline`, `originMarker`, `destinationMarker`, `waypoints`, and `pos`) are initialized.
  • The `pos` variable is set based on the latitude and longitude values obtained from the `panel.city.centroid` property.

2. Map Initialization

The NextBillion.ai map (`mapDir`) is instantiated with specified properties, such as the container, center position, zoom level, style, and interaction settings.

3. Map Actions

  • The `loadMapActions` function is called, implying the setup of additional map-related actions not explicitly provided in this snippet.
  • A “Clear Map” button is configured to trigger the `clearMap` function when clicked. This function clears the map, markers, and waypoints.

4. Event Listeners

  • The code establishes an event listener for clicks on the map (`mapDir.map`).
  • Depending on the existence of `originMarker` and `destinationMarker`, it creates markers for the origin, destination, and waypoints. These markers are draggable, allowing users to adjust their positions.
  • The `routeMe` function is invoked to calculate and display the route when necessary.

This code is part of a larger system for interactive map-based route planning. It effectively manages user interactions, such as setting origin and destination points, adding waypoints, and updating the route accordingly.

Example 3: Distance Matrix

In the realm of vehicle routing problems, a distance matrix emerges as a pivotal tool. It’s a tabular representation detailing the distances and travel times between an array of locations. Specifically, in scenarios like vehicle routing problems, this matrix serves to delineate the distances amid diverse customers or delivery points slated for a fleet of vehicles.

Select the origin and destination points on the map. 

The following Distance Matrix represents the distance and the travel time between each pair of locations.

Utilization in Vehicle Routing Algorithms

  1. Input Data

The distance matrix operates as a crucial input for vehicle routing algorithms. It encapsulates the fundamental data regarding the spatial relationships between destinations.

  1. Efficient Routing

Vehicle routing algorithms leverage this matrix to orchestrate an optimal route for the fleet. Optimization factors span a spectrum, encompassing metrics like total distance traversed, the requisite number of vehicles, and the temporal demands for completing deliveries.

  1. Consideration of Constraints

The algorithm’s power extends beyond distance calculation. It ingeniously integrates constraints like vehicle capacity and delivery time windows, ensuring a nuanced and refined optimization of the overall route.

In a nutshell, the distance matrix plays a pivotal role in the orchestration of efficient and optimized vehicle routes. Its intricate interplay with algorithms, considering multifaceted constraints, underscores its significance in tackling real-world logistics challenges.

Example 4: Snap to Road

The “Snap to Road” service stands as a solution that transforms raw GPS coordinates (latitude and longitude) into meaningful data by aligning them with established roads or streets on the digital map. This process, commonly referred to as “map matching” or “GPS snapping,” employs a fusion of advanced algorithms and data gleaned from the road network database.

Functional Dynamics

  1. GPS Point Matching

Leveraging a combination of algorithms and robust road network data, the service adeptly identifies the nearest match for a given GPS point. The outcome is a precise association with the corresponding address or road segment.

  1. Versatile Applications

The versatility of Snap to Road extends across diverse applications, spanning navigation, transportation, and logistics domains. It becomes a linchpin in scenarios where accurate spatial alignment is paramount.

Logistics Optimization

  1. Goods and Vehicles Tracking

In logistics orchestration, the service proves invaluable for tracking and optimizing the movement of goods and vehicles. By capturing GPS data from vehicles, the system meticulously aligns them with the road network, pinpointing exact locations and routes.

  1. Route Planning Enhancement

The amalgamation of GPS data and road network mapping provides a robust foundation for route planning refinement. This information becomes pivotal in strategizing and optimizing delivery schedules for enhanced operational efficiency.

The “Snap to Road” service represents the synergy of technological precision and logistical optimization. Its application extends beyond spatial alignment, empowering industries to fine-tune operations, streamline routes, and elevate overall performance in navigation, transportation, and logistics realms.

Example 5: Navigation - Turn-By-Turn Instructions

Dive into the intricacies of turn-by-turn navigation with the NB.ai Navigation API service. This example foregoes the conventional map-centric approach, opting instead for a text-based instruction paradigm. Users receive explicit guidance at predefined trigger points, strategically positioned based on distance from maneuver locations.

Functional Dynamics

  1. Text-Based Navigation

The NB.ai Navigation API seamlessly delivers turn-by-turn instructions in textual form. Absent the visual map, users receive precise directions via verbal cues.

  1. Trigger Points

Navigation instructions trigger at strategic points along the route, providing users with timely guidance on when and where to turn. These trigger points are meticulously calculated based on distance from maneuver locations.

  1. Instruction Details

The instructions furnish comprehensive details, including the street or road name and the directional command. For instance, users might encounter instructions like “Turn left onto Main Street” or “Turn right onto Elm Street.”

User Guide

  1. Setting Origin and Destination

Initiate the navigation experience by configuring the origin and destination through the provided search boxes.

  1. Navigation Input Parameters

Customize navigation input parameters to tailor the experience to your specific requirements.

  1. Initiate Navigation

Click ‘Navigate’ to kickstart the turn-by-turn maneuver instructions.

After setting all the necessary parameters, the notebook returns navigation steps in the following format.

 

Instruction

 

Speed Limit

Distance (Total = 32.5 km )

Duration (Total = 0H 35 Min)

Head south, then turn right onto Labin Ct

 

65

51 m

 

Turn right onto Labin Ct, then turn left to stay on Labin Ct

 

65

16 m

0.2 min


Turn left to stay on Labin Ct

 

65

168 m

1.0 min

Turn left onto Nogales St, then take the ramp towards Pomona

 

65

51 m

0.4 min

Take the ramp towards Pomona

 

65

1.8 km

2.1 min

Keep left onto CA-60 E

 

65

3.1 km

3.5 min

Keep left onto CA-60 E

  

4.9 km

4.3 min

Make a slight left to stay on CA-60 E

  

2.5 km

1.4 min

Keep left onto CA-60 E

  

12.9 km

10.4 min

Make a slight right towards Grove Avenue

  

445 m 

0.7 min

Use the left lane to turn left towards Los Angeles

  

3.4 km

6.0 min

Turn right towards Rental Car Return

  

2.6 km

2.9 min

Turn right towards Terminals

  

536 m

1.4 min

You have arrived at E Terminal Way, on the left

  

0 m

0.0 min

This approach offers a distinctive navigation experience, divorcing itself from conventional visual aids and embracing a streamlined, text-centric paradigm.

Example 6: Decode Route Polyline Geometry

In this example, we delve into the process of decoding an encoded polyline, unveiling the geographical intricacies of a route. The encoded polyline in question is:

 

The following is the Encoded Polyline geometry from Griffith Observatory to Downtown LA. 


u`viFvaqzUlw@lqAxLzGdGhE~XzJbUvKpHvDbCfBrJkAzM`DrChQjC`CdI~YjLx|@rSrRhJz`@hHjZ

Decoding Process

Upon decoding, the result manifests as a GeoJSON object, encapsulated in the `decodedPoly` variable. A snippet of the decoded GeoJSON appears below.


decodedPoly = {
  type: "FeatureCollection",
  features: [
    {
      // ... GeoJSON properties of the decoded route feature
    }
  ]
}

The following image visualizes the decoded route geometry.

Polyline decode

Bounding Box Information

Additionally, the decoded route provides bounding box coordinates, specifying the geographical extent of the route.


bbox = [
  -119.9118, // Minimum longitude
  38.4181,   // Minimum latitude
  -119.85964, // Maximum longitude
  38.45659   // Maximum latitude
]

These coordinates delineate the rectangular region encompassing the route.

This example showcases the transformation of encoded polyline data into a tangible geographical representation, laying the groundwork for further spatial analysis and visualization.

In this exploration of the NextBillion.ai Maps SDK, we’ve navigated through a spectrum of technical examples unveiling the capabilities inherent in location-based solutions. From map integration and turn-by-turn navigation to distance matrices and road snapping, the SDK serves as a robust toolkit for developers grappling with diverse spatial challenges.

These examples illustrate the SDK’s versatility in handling intricate geospatial tasks, providing developers with the means to craft dynamic applications tailored to real-world logistics and mapping scenarios. As we conclude this journey, the technical prowess exhibited by the SDK underscores its potential as a cornerstone for building sophisticated and efficient location-based systems.