loading...

. . . . . .

Let’s make something together

KAISPE has been providing solutions and services to customers using Microsoft Dynamics, Azure, Power platform, Oracle NetSuite, mobile and web app development.

    • US OFFICE
    • +1 315 791 4472
    • KAISPE LLC
      590 Madison Avenue 21st Floor Manhattan, NY 10022 USA.

 

  • PAKISTAN OFFICE
  • +92 213 432 6085
  • M/S KAISPE
    Suite#213 Sumya Business Avenue MACHS Karachi, Pakistan.

Route Optimization Using Google Maps Routes API

  • July 26, 2023
  • 539 Views

In today’s fast-paced business landscape, efficient route optimization plays a pivotal role in ensuring seamless deliveries and maximizing operational productivity. For enterprises involved in delivery services, logistics, or any industry where transportation is critical, leveraging the power of Google Maps Routes API for route planning based on distance becomes paramount.

By harnessing advanced technologies and data-driven approaches provided by the Google Maps Routes API, businesses can significantly reduce delivery costs, improve customer satisfaction, and minimize environmental impact. This blog will explore the importance of efficient route optimization in enterprises, primarily focusing on distance-based route planning empowered by the Google Maps Routes API.

Pricing of Google Maps API

Google Maps Routes API follows a pay-as-you-go pricing model, with usage tracked by each SKU. Each API or SDK can possess multiple SKUs. For example, the Routes API services Compute Routes and Compute Route Matrix have three SKU options affecting cost depending on the requested features. We will use the basic SKU for this blog.

Compute Routes

– Monthly Volume Range: 0-100,000 requests

– Price per Request: $0.005 USD per each (or $5.00 USD per 1000 requests)

Compute Route Matrix

– Monthly Volume Range: 0-100,000 requests

– Price per Element: USD 0.005 per each (or USD 5.00 per 1000 elements)

Architecture

Route optimization using Google Maps Routes API involves two key services: Compute Route and Compute Route Matrix. The blend of these two services empowers developers with nuanced control over routing decisions based on various factors like distance, time, and traffic conditions.

Compute Route API

Compute Route is a powerful tool in the APIs suite that calculates the most efficient route between a source and a destination. The guiding factor for route calculation could be the shortest path, fastest time, or even the least complex route. The API supports multiple waypoints, which allows for complex, multi-stop routes.

Compute Route excels at formulating the shortest possible path between stops in a context with distance as the prime concern.

Compute Route Matrix API

This, on the other hand, focuses on calculating a matrix of route data between multiple origins and multiple destinations. In scenarios where the source is singular but there are multiple destinations or vice versa, Compute Route Matrix is invaluable.

From a distance-optimization perspective, Compute Route Matrix gives you a distance map between your given points. It calculates the distance and estimated travel time from each origin to all destinations provided, then structures this data as an easy-to-read matrix.

Route Optimization

Here’s a simple architecture about how to implement route optimization:

  1. Use Compute Route Matrix to calculate the distances from the source to all the destinations. This results in a matrix of distances.
  2. Determine the closest destination to the source using the generated distance matrix. This is your first waypoint.
  3. Repeat this process, setting the first waypoint as the source each time we proceed. Find the closest destination from the waypoint, marking it as the next.
  4. Continue refining the waypoints until all destinations have been accounted for. The final waypoint will be your last destination.
  5. The resulting sequence of waypoints represents the optimized route from the source to all destinations, ensuring the shortest distance traveled.

Though this process involves multiple API calls, the output is a highly-optimized route that can save time and resources, which is critical for logistics operations or trip planning.

Usage

To use these APIs, first, we need an API key. The API key is a unique identifier that authenticates requests associated with your project for usage and billing purposes.

To get an API key:

  1. Go to the Cloud Console (https://console.cloud.google.com/)
  2. Create or select a project
  3. Click on ‘Enable APIs and Services’
  4. Search for ‘Routes API’ and enable it
  5. Go to the ‘Credentials’ tab and click on ‘Create Credentials’
  6. Select ‘API key’ from the dropdown menu

This will generate an API key that can be used to authenticate your requests to the Routes API developers.google.com.

Using the APIs in Android

Start by adding the Retrofit and Kotlin Coroutine Libraries to your build.gradle:

“`gradle

dependencies {

    implementation ‘com.squareup.retrofit2:retrofit:2.9.0’

    implementation ‘com.squareup.retrofit2:converter-gson:2.9.0’

    Then, implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.7’

    implementation ‘org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.7’

}

“`

Thereafter, create data classes for parsing JSON responses from Google’s Compute Route and Compute Route Matrix APIs:

“`kotlin

// Data classes for Compute Route Matrix API

data class ComputeRouteMatrixRequestBody(

    val origin: LatLng,

    val destinations: List<LatLng>

)

data class ComputeRouteMatrixResponse(

    val originIndex: Int,

    val destinationIndex: Int,

    Then, val status: Map<String, Any>,

    val distanceMeters: Int,

    val duration: String,

    Last, val condition: String

)

// Data classes for Compute Route API

data class ComputeRouteRequestBody(

    val origin: LatLng,

    val destinations: List<LatLng>

)

data class ComputeRouteResponse(

    val routes: List<Route>

)

data class Route(

    val distanceMeters: Int,

    val duration: String,

    Last, val polyline: EncodedPolyline

)

data class EncodedPolyline(

    val encodedPolyline: String

)

“`

Initialize Retrofit and create an instance of your API service:

“`kotlin

import retrofit2.Retrofit

import retrofit2.converter.gson.GsonConverterFactory

val retrofit = Retrofit.Builder()

    .baseUrl(“https://routes.googleapis.com/”)

    .addConverterFactory(GsonConverterFactory.create())

    .build()

val googleMapsApiService = retrofit.create(GoogleMapsApiService::class.java)

“`

Retrofit service interface:

“`kotlin

interface GoogleRouteApi {

    @POST(“distanceMatrix/v2:computeRouteMatrix”)

    suspend fun computeRouteMatrix(

        @Header(“X-Goog-Api-Key”) apiKey: String,

        @Body request: ComputeRouteMatrixRequestBody

    ): List<ComputeRouteMatrixResponse>

    @POST(“directions/v2:computeRoutes”)

    suspend fun computeRoute(

        @Header(“X-Goog-Api-Key”) apiKey: String,

        @Body request: ComputeRouteRequestBody

    ): ComputeRouteResponse

}

“`

Pseudocode to get the shortest route function:

“`

Function calculateShortestRoute(api, key, origin, destinations):

    Initialize visited as an empty list

    Set currentOrigin as origin

    While the size of visited is less than the size of destinations:

        Call the Compute Route Matrix API with currentOrigin and destinations that are not in visited

        Get the response and extract the matrix from the response body

        Initialize closestDestinationIndex as 0

        Initialize shortestDistance as the distance value of the first element in the matrix

        For i from 1 to the size of elements in the matrix:

            If the distance value of the i-th element is less than shortestDistance:

                Set closestDestinationIndex as i

                Set shortestDistance as the distance value of the i-th element

        Get the closestDestination from the destination addresses in the matrix using closestDestinationIndex

        Add closestDestination to visited

        Set currentOrigin as closestDestination

    Return visited

End Function

“`

Conclusion

Efficient route optimization is a crucial aspect of modern business operations, especially for delivery services and logistics enterprises. The Google Maps Routes API, with its Compute Route and Compute Route Matrix services, provides powerful tools for distance-based route planning, helping businesses reduce costs, enhance customer satisfaction, and minimize environmental impact. By implementing the route optimization architecture described in this blog, developers can create highly-optimized routes that save time and resources, making it a valuable asset for logistics operations and trip planning.

Following the guidelines above, developers can efficiently use the Google Maps Routes API in Android applications, leveraging technologies like Retrofit and Kotlin Coroutines to retrieve optimized routes and deliver seamless user experiences. With its pay-as-you-go pricing model, the Google Maps Routes API offers a cost-effective solution for businesses of all sizes seeking to enhance their delivery efficiency and overall operational productivity.

Ready to supercharge your logistics? Embrace the power of route optimization with our expert Google Maps Routes API consultation services. Unlock cost savings, faster deliveries, and seamless navigation.

Contact KAISPE today!!