DrawRoute wraps Google Directions API (https://developers.google.com/maps/documentation/directions/) using RxJava for Android so developers can download, parse and draw path on the map in very fast and flexible way (For now only JSON support).

Overview

DrawRoute

Android Arsenal GitHub pull requests

DrawRoute wraps Google Directions API (https://developers.google.com/maps/documentation/directions/) using RxAndroid for Android. Now developers can easily Draw route on maps, can get the Estimated time of arrival and the Google suggested distance between two locations in a very easy and flexible. Note: You need to generate an API key at Google cloud platform also don't forget to enable Directions API. Enjoy!

read more on medium

How to add (gradle)

If you are using gradle: Step1: Add it in your root build.gradle at the end of repositories

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

Step2: Add the dependency

dependencies {
	implementation 'com.github.malikdawar:drawroute:1.5'
}

Otherwise you have to use library directly in your project.

USAGE

First we have to download the path. For this we need to provide two points (start and end) and travel mode.

	val source = LatLng(31.490127, 74.316971) //starting point (LatLng)
        val destination = LatLng(31.474316, 74.316112) // ending point (LatLng)

        googleMap?.run {
            moveCameraOnMap(latLng = source) // if you want to zoom the map to any point

            //Called the drawRouteOnMap extension to draw the polyline/route on google maps
           drawRouteOnMap(
                getString(R.string.google_map_api_key), //your API key
                source = source, // Source from where you want to draw path
                destination = destination, // destination to where you want to draw path
                context = context!! //Activity context
            )
        }

If you want more control

	fun GoogleMap.drawRouteOnMap(
	    mapsApiKey: String,  // YOur API key
	    context: Context, //App context
	    source: LatLng, //Source, from where you want to draw path
	    destination: LatLng,  //Destination, to where you want to draw path
	    color: Int = context.getColorCompat(R.color.pathColor),  //color, path/route/polygon color, specify the color if you want some other color other then default one
	    markers: Boolean = true, //If you want markers on source and destination, by default it is true
	    boundMarkers: Boolean = true, //If you want to bound the markers(start and end points) in screen with padding, by default it is true 
	    polygonWidth: Int = 13, // route/path width, by default it is 13
	    travelMode: TravelMode = TravelMode.DRIVING //Travel mode, by default it is DRIVING
	)
enum class TravelMode {
    DRIVING, WALKING, BICYCLING, TRANSIT
}

Route Estimations

(Kotlin)

In your Activity/Fragmant

class YourFragment : Fragment(), OnMapReadyCallback {

	
	//if you only want the Estimates (Distance & Time of arrival)
        getTravelEstimations(
            mapsApiKey = getString(R.string.google_map_api_key),
            source = source,
            destination = destination
        ) { estimates ->
            estimates?.let {
                //Google Estimated time of arrival
                Log.d(TAG, "ETA: ${it.duration?.text}, ${it.duration?.value}")
                //Google suggested path distance
                Log.d(TAG, "Distance: ${it.distance?.text}, ${it.distance?.text}")

            } ?: Log.e(TAG, "Nothing found")
        }


	//if you only want to draw a route on maps and also need the ETAs
        //Called the drawRouteOnMap extension to draw the polyline/route on google maps
            drawRouteOnMap(
                getString(R.string.google_map_api_key),
                source = source,
                destination = destination,
                context = context!!,
            ) { estimates ->
                estimates?.let {
                    //Google Estimated time of arrival
                    Log.d(TAG, "ETA: ${it.duration?.text}, ${it.duration?.value}")
                    //Google suggested path distance
                    Log.d(TAG, "Distance: ${it.distance?.text}, ${it.distance?.text}")

                } ?: Log.e(TAG, "Nothing found")
            }

And taking all together:

(Kotlin)

class RouteFragment : Fragment(), OnMapReadyCallback {

    private var googleMap: GoogleMap? = null

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_map_route, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //initialized google maps
        val mapFragment =
            childFragmentManager.findFragmentById(R.id.mapView) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }

    override fun onMapReady(p0: GoogleMap?) {
        this.googleMap = p0

        val source = LatLng(31.490127, 74.316971) //starting point (LatLng)
        val destination = LatLng(31.474316, 74.316112) // ending point (LatLng)

        //if you only want the Estimates (Distance & Time of arrival)
        getTravelEstimations(
            mapsApiKey = getString(R.string.google_map_api_key),
            source = source,
            destination = destination
        ) { estimates ->
            estimates?.let {
                //Google Estimated time of arrival
                Log.d(TAG, "ETA: ${it.duration?.text}, ${it.duration?.value}")
                //Google suggested path distance
                Log.d(TAG, "Distance: ${it.distance?.text}, ${it.distance?.text}")

            } ?: Log.e(TAG, "Nothing found")
        }


        googleMap?.run {
            //if you want to move the map on specific location
            moveCameraOnMap(latLng = source)

            //if you want to drop a marker of maps, call it
            drawMarker(location = source, context = requireContext(), title = "test marker")

            //if you only want to draw a route on maps
            //Called the drawRouteOnMap extension to draw the polyline/route on google maps
            drawRouteOnMap(
                getString(R.string.google_map_api_key),
                source = source,
                destination = destination,
                context = context!!
            )

            //if you only want to draw a route on maps and also need the ETAs
            //Called the drawRouteOnMap extension to draw the polyline/route on google maps
            drawRouteOnMap(
                getString(R.string.google_map_api_key),
                source = source,
                destination = destination,
                context = context!!,
            ) { estimates ->
                estimates?.let {
                    //Google Estimated time of arrival
                    Log.d(TAG, "ETA: ${it.duration?.text}, ${it.duration?.value}")
                    //Google suggested path distance
                    Log.d(TAG, "Distance: ${it.distance?.text}, ${it.distance?.text}")

                } ?: Log.e(TAG, "Nothing found")
            }
        }
    }

    companion object {
        var TAG = RouteFragment::javaClass.name
    }
}

(Java)

private final OnMapReadyCallback callback = googleMap -> {

        LatLng source = new LatLng(31.490127, 74.316971); //starting point (LatLng)
        LatLng destination = new LatLng(31.474316, 74.316112); // ending point (LatLng)

        //zoom/move cam on map ready
        MapExtensionKt.moveCameraOnMap(googleMap, 16, true, source);

        //draw route on map
       //If want to draw route on maps and also required the Estimates else just pass the null as a param for lambda
        MapExtensionKt.drawRouteOnMap(googleMap,
                getString(R.string.google_map_api_key),
                getContext(),
                source,
                destination,
                getActivity().getColor(R.color.pathColor),
                true, true, 13, TravelMode.DRIVING, null /*deprecated*/,
                //call the lambda if you need the estimates
                (estimates -> {
                    //Estimated time of arrival
                    Log.d("estimatedTimeOfArrival", "withUnit " + estimates.getDuration().getText());
                    Log.d("estimatedTimeOfArrival", "InMilliSec " + estimates.getDuration().getValue());

                    //Google suggested path distance
                    Log.d("GoogleSuggestedDistance", "withUnit " + estimates.getDistance().getText());
                    Log.d("GoogleSuggestedDistance", "InMilliSec " + estimates.getDistance().getValue());
                    return null;
                }));
	
    };


    For more please refer to the RouteFragment in sample app. Enjoy :)

Screen Shot image

Developed By

Malik Dawar - [email protected]

Mobin Munir

You might also like...
LocationPicker 2.1 0.4 Java  - A simple and easy to way to pick a location from map
LocationPicker 2.1 0.4 Java - A simple and easy to way to pick a location from map

Introduction LocationPicker is a simple and easy to use library that can be integrated into your project. The project is build with androidx. All libr

Curve-Fit is an Android library for drawing curves on Google Maps
Curve-Fit is an Android library for drawing curves on Google Maps

Curve-Fit Android library for drawing curves on Google Maps. This library uses Bezier cubic equation in order to compute all intermediate points of a

Demo de uso de google maps en Android, charla para el GDG Chimbote

mapasbasico Demo de uso de google maps en Android, charla para el GDG Chimbote Puedes usar este proyecto como base para trabajar con mapas en Android.

Membuat Custom Tooltip Marker Google Maps
Membuat Custom Tooltip Marker Google Maps

Custom-Tooltip-Marker Membuat Custom Tooltip Marker Google Maps Tutorial Build with Android Studio https://youtu.be/E8ND0YThNiU Tutorial Build with St

An app to search nearby businesses on Google Maps & Add Grocery Items to List!
An app to search nearby businesses on Google Maps & Add Grocery Items to List!

GoStore: Internship Program Project A mobile app is built where the user can search for his nearby locations based on his requirement. Whenever the us

This project allows you to  calculate the route between two locations and displays it on a map.
This project allows you to calculate the route between two locations and displays it on a map.

Google-Directions-Android This project allows you to calculate the direction between two locations and display the route on a Google Map using the Goo

typedmap is an implementation of heterogeneous type-safe map pattern in Kotlin

Typedmap typedmap is an implementation of heterogeneous type-safe map pattern in Kotlin. It is a data structure similar to a regular map, but with two

Slime loader is a map loader & saver for the file format Slime as specified here implemented in Minestom.

🗺️ SlimeLoader Slime loader is a map loader & saver for the file format Slime as specified here implemented in Minestom. Features: World loading Bloc

Interactive, thoroughly customizable maps in native Android powered by vector tiles and OpenGL.
Interactive, thoroughly customizable maps in native Android powered by vector tiles and OpenGL.

Interactive, thoroughly customizable maps in native Android powered by vector tiles and OpenGL.

Comments
  • I got these warning and the drawRouteOnMap doesn't work , what should I do , i have done some research but nothing is useful

    I got these warning and the drawRouteOnMap doesn't work , what should I do , i have done some research but nothing is useful

    W/soft.ecoshippe: Accessing hidden method Lcom/android/org/conscrypt/ConscryptEngineSocket;->setUseSessionTickets(Z)V (greylist-max-q,core-platform-api, reflection, denied)
        Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setUseSessionTickets(Z)V (greylist-max-q,core-platform-api, reflection, denied)
        Accessing hidden method Lcom/android/org/conscrypt/AbstractConscryptSocket;->setUseSessionTickets(Z)V (greylist-max-q, reflection, denied)
    W/soft.ecoshippe: Accessing hidden method Lcom/android/org/conscrypt/ConscryptEngineSocket;->setHostname(Ljava/lang/String;)V (greylist-max-q,core-platform-api, reflection, denied)
        Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setHostname(Ljava/lang/String;)V (greylist-max-q,core-platform-api, reflection, denied)
        Accessing hidden method Lcom/android/org/conscrypt/AbstractConscryptSocket;->setHostname(Ljava/lang/String;)V (greylist-max-q, reflection, denied)
        Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->setAlpnProtocols([B)V (greylist-max-q,core-platform-api, reflection, denied)
        Accessing hidden method Lcom/android/org/conscrypt/AbstractConscryptSocket;->setAlpnProtocols([B)V (greylist-max-q, reflection, denied)
    W/soft.ecoshippe: Accessing hidden method Lcom/android/org/conscrypt/OpenSSLSocketImpl;->getAlpnSelectedProtocol()[B (greylist-max-q,core-platform-api, reflection, denied)
        Accessing hidden method Lcom/android/org/conscrypt/AbstractConscryptSocket;->getAlpnSelectedProtocol()[B (greylist-max-q, reflection, denied)
    
    

    i just need to drawRoute between my 2 point but when the project run to drawRouteOnMap function these happen

    here is my maps activity :

    class TaskMapsActivity : AppCompatActivity() {
        lateinit var mapFragment: SupportMapFragment
        lateinit var mMap: GoogleMap
        lateinit var binding: ActivityTaskMapsBinding
        lateinit var client: FusedLocationProviderClient
        private var currentPosition = LatLng(0.0,0.0)
        private var newPost = LatLng(0.0,0.0)
        private val permissionRequest =
            registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted ->
                if (isGranted) {
                    mapFragment =
                        supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
                    client = LocationServices.getFusedLocationProviderClient(this)
                    getCurrentLocation()
                }
            }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivityTaskMapsBinding.inflate(layoutInflater)
            setContentView(binding.root)
            if (ActivityCompat.checkSelfPermission(
                    this,
                    android.Manifest.permission.ACCESS_FINE_LOCATION
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
                client = LocationServices.getFusedLocationProviderClient(this)
                getCurrentLocation()
            } else {
                permissionRequest.launch(android.Manifest.permission.ACCESS_FINE_LOCATION)
            }
            binding.btnBackFromMaps.setOnClickListener {
                this.finish()
            }
            binding.yourPossitionPoint.setOnClickListener {
                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentPosition,15f))
            }
            binding.targetPossitionPoint.setOnClickListener {
                if (newPost != LatLng(0.0,0.0)){
                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newPost,15f))
                }else Toast.makeText(this,"you have not select new location",Toast.LENGTH_SHORT).show()
            }
        }
        @SuppressLint("MissingPermission")
        private fun getCurrentLocation() {
            val task: Task<Location> = client.lastLocation
            task.addOnSuccessListener { location ->
                if (location != null){
                    mapFragment.getMapAsync { googleMap ->
                        mMap = googleMap
                        currentPosition = LatLng(location.latitude, location.longitude)
                        mMap.addMarker(
                            MarkerOptions().position(currentPosition).title(getString(R.string.MarkerTitle))
                                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED))
                        )
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, 15f))
                        mMap.setOnMapClickListener {
                           newPost = it
                            mMap.addMarker(
                                MarkerOptions().position(newPost).title("new position")
                                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
                            )
                            mMap.drawRouteOnMap(
                               mapsApiKey = getString(R.string.google_maps_key),
                                source = currentPosition,
                                destination =  newPost,
                                color = getColor(R.color.red),
                                travelMode = TravelMode.DRIVING,
                                context =  this@TaskMapsActivity
                            )
                        }
                    }
                }
            }
        }
    
    opened by z0ro25 4
  • Path is Not Accurate (Much like displacement between two points)

    Path is Not Accurate (Much like displacement between two points)

    Everything is working fine but path is showing like displacement route. It should looks like the path along with roads but is overlapping the roads and showing displacement.

    bug help wanted 
    opened by AonCh 1
  • Feature/Rx improvemnts

    Feature/Rx improvemnts

    Updates include: 1-Sample for java users. 2-Updated the Kotlin version. 3-Updated the SDK versions. 4-Removed the Rx dependency from the sample and made it simple for the developers to use it. (Now do need to add the dependency of RX java to use the library) 5-Code optimization. 6-Response time increased.

    opened by malikdawar 0
  • Feature request

    Feature request

    This is a very helpful library to simplify usage of the Google Maps API. Two suggestions to make this more useful :

    1)Consider if RxJava is the best choice for transparent cross-platform usage. Industry seems to be leaning towards Kotlin. personally not too familiar with RxJava support on iOS, so perhaps it works fine too 2)Fully abstract the underlying Map implementation to allow seamless (i.e. config only) switching between other providers, such as MapBox (https://www.mapbox.com/) and OSM (https://www.openstreetmap.org).

    enhancement 
    opened by stephen-kruger 2
Releases(1.5)
Owner
malik dawar
Sr. Android Developer
malik dawar
EasyRoutes allows you to easily draw routes through the google maps address api.

EasyRoutes EasyRoutes allows you to easily draw routes through the google maps address api. Note: You need to generate an API key from the google cons

Antonio Huerta Reyes 7 Jul 26, 2022
Android Maps Extensions is a library extending capabilities of Google Maps Android API v2.

Android Maps Extensions Library extending capabilities of Google Maps Android API v2. While Google Maps Android API v2 is a huge leap forward comapare

Maciej Górski 408 Dec 15, 2022
This is a repo for implementing Map pan or drag (up, down, right ,left) to load more places on the Google Map for Android

Challenge Display restaurants around the user’s current location on a map ○ Use the FourSquare Search API to query for restaurants: https://developer.

Mahmoud Ramadan 7 Jul 30, 2022
Scale bar for Android Maps (Google Maps, OSM, MapBox, Yandex)

Map Scale View Scale view for any Android Maps SDK (not only Google Maps) Contributing I encourage you to participate in this project. Feel free to op

Stas Parshin 109 Nov 18, 2022
Maps application in Android Studio using the Maps SDK for android

Google-Maps-Application Maps application in Android Studio using the Maps SDK for android. This app was initially developed in Java, but then was conv

Kyle McInnis 0 Nov 30, 2021
A view abstraction to provide a map user interface with various underlying map providers

AirMapView AirMapView is a view abstraction that enables interactive maps for devices with and without Google Play Services. It is built to support mu

Airbnb 1.8k Dec 4, 2022
🍃 Organic Maps is an Android & iOS offline maps app for travelers, tourists, hikers, and cyclists based on top of crowd-sourced OpenStreetMap data and curated with love by MapsWithMe founders.

?? Organic Maps is an Android & iOS offline maps app for travelers, tourists, hikers, and cyclists based on top of crowd-sourced OpenStreetMap data and curated with love by MapsWithMe founders. No ads, no tracking, no data collection, no crapware.

Organic Maps 4.3k Dec 31, 2022
Self-hosted map of visited places (with a very fancy stack underneath)

Tripmap Self-hosted map of visited places (with a very fancy stack underneath) Features Sharing custom map-view with pins in locations marked by user.

Igor Kurek 2 Feb 6, 2022
Google Maps Api test using marker rotation and routes.

Google Maps Api test using marker rotation and routes. Features ✔️ Kotlin ✔️ DI: Hilt ✔️ Retrofit ✔️ Gson ✔️ View binding ✔️ Coroutines ✔️ AndroidX ✔️

Carlos Adan 39 Jul 15, 2022
An android app that uses Google Maps API and SDK to track a user's location and calculate the total distance travelled

Bike Rush is an android app that uses Google Maps API and SDK to track a user's location and calculate the total distance travelled by him or her along with time and average speed.

Ishant Chauhan 21 Nov 14, 2022