androidgoogle-mapsgoogle-maps-urls

set From location to current location in google maps android programmatically


I am creating an app where it requires opening google maps to navigate to a place in walking mode and to set source/from location to current location.

Here is the code I use.

String url = "https://maps.google.co.in/maps?q=" + destination + "&mode=walking";
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(intent);

How do I set "From location" to "current location"?? Thanks.


Solution

  • I would suggest using a Google Maps URLs instead of the link you provided in the example. The Google Maps URLs is an official and recommended way to launch Google Maps app on mobile devices and web browsers.

    Please note that if you omit the origin parameter in the Google Maps URLs, the API will use your current location if available

    origin: Defines the starting point from which to display directions. Defaults to most relevant starting location, such as user location, if available. If none, the resulting map may provide a blank form to allow a user to enter the origin. The value can be either a place name, address, or comma-separated latitude/longitude coordinates. A string should be URL-escaped.

    So, you should rewrite your code as

    String url = "https://www.google.com/maps/dir/?api=1&destination=" + destination + "&travelmode=walking&dir_action=navigate";
    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    getApplicationContext().startActivity(intent);
    

    I hope this helps!