Create a circuit route by passing waypoints to GoogleMaps android - android

I am working on functionality where I send waypoints to Gmapsapp through Intent so that use can navigate to the destination by the custom waypoints that I send
I when I plot this route in my embedded Google Maps , I can see Circuit route , but when I see the same route in Gmapsapp , the Circuit is broken.
My code :
String srcAdd = "saddr="+latLngArrayList.get(0).latitude+","+latLngArrayList.get(0).longitude;
String desAdd = "&daddr="+latLngArrayList.get(latLngArrayList.size() - 1).latitude+","+latLngArrayList.get(latLngArrayList.size() - 1).longitude;
String wayPoints = "";
for (int j = 1; j < latLngArrayList.size() - 1; ++j) {
wayPoints =wayPoints+"+to:"+latLngArrayList.get(j).latitude+","+latLngArrayList.get(j).longitude;
}
String link="https://maps.google.com/maps?"+srcAdd+desAdd+wayPoints;
final Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(link));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
circuit route
no circuit route

I would suggest having a look at Google Maps URLs API that was launched in May 2017. This API provides universal cross-platform links that you can use in your applications to launch intents for Google Maps. One of the supported modes is directions mode. You can read about it here.
As you use Directions API and posted sample coordinates of waypoints, I was able to test the results in web service and in Google Maps URLs.
The web service results are tested in Directions calculator tool:
https://directionsdebug.firebaseapp.com/?origin=19.07598304748535%2C72.87765502929688&destination=19.07598304748535%2C72.87765502929688&waypoints=18.7284%2C73.4815%7C18.6876%2C73.4827%7C18.5839587%2C73.5125092%7C18.5369444%2C73.4861111%7C18.480567%2C73.491658
The route that we get via Directions API is the following:
The Google Maps URLs link for these waypoints is the following:
https://www.google.com/maps/dir/?api=1&origin=19.07598304748535,72.87765502929688&destination=19.07598304748535,72.87765502929688&waypoints=18.7284,73.4815%7C18.6876,73.4827%7C18.5839587,73.5125092%7C18.5369444,73.4861111%7C18.480567,73.491658&travelmode=driving
The route that you get using Google Maps URLs is shown in this screenshot.
As you can see both routes are the same, so Directions API and Google Maps URLs work as expected. I believe you should change your code for intents to use Google Maps URLs:
String srcAdd = "&origin=" + latLngArrayList.get(0).latitude + "," + latLngArrayList.get(0).longitude;
String desAdd = "&destination=" + latLngArrayList.get(latLngArrayList.size() - 1).latitude + "," + latLngArrayList.get(latLngArrayList.size() - 1).longitude;
String wayPoints = "";
for (int j = 1; j < latLngArrayList.size() - 1; j++) {
wayPoints = wayPoints + (wayPoints.equals("") ? "" : "%7C") + latLngArrayList.get(j).latitude + "," + latLngArrayList.get(j).longitude;
}
wayPoints = "&waypoints=" + wayPoints;
String link="https://www.google.com/maps/dir/?api=1&travelmode=driving"+srcAdd+desAdd+wayPoints;
final Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(link));
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
startActivity(intent);
In addition you can use dir_action=navigate parameter in order to open turn-by-turn navigation directly.

Related

Show Direction Between two location in Android

I am developing application to track user location. In that I need to know how to show shortest direction from one location to another in Map Activity.I should not be a straight line. It should be like a road path.
If you want to draw a polyline between 2 points and following road, you can try with the library Google-Directions-Android
You can add the library on gradle with compile 'com.github.jd-alexander:library:1.0.7'
You can use all your point (Latlng) and use them into the waypoint method.
Routing routing = new Routing.Builder()
.travelMode(/* Travel Mode */)
.withListener(/* Listener that delivers routing results.*/)
.waypoints(/*waypoints*/)
.build();
routing.execute();
actual code
start = new LatLng(18.015365, -77.499382);
waypoint= new LatLng(18.01455, -77.499333);
end = new LatLng(18.012590, -77.500659);
Routing routing = new Routing.Builder()
.travelMode(Routing.TravelMode.WALKING)
.withListener(this)
.waypoints(start, waypoint, end)
.build();
routing.execute();
String uri = String.format(Locale.ENGLISH, "http://maps.google.com/maps?saddr=%s&daddr=%s", "Malakwal", "Lahore");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
intent.setPackage("com.google.android.apps.maps");
startActivity(intent);

Google map direction intent with multiple location on route and starting point as current location, android

I want to start Google map intent for direction with current location as starting position, one location as entry position and other location as destination.
After googling for this, following is the closest query I came with
https://maps.google.com/maps?f=d&daddr=41.3951982,-72.855568 to: 41.279386, -72.825098
OR
"https://www.google.com/maps/dir//41.3951982,-72.855568/41.279386,-72.825098"
Both of them work good when I paste on browser, but not on my mobile device. I just get source and destination. Any ideas?
EDIT:
Actually the second one works. Unlike browser, it only shows starting location and first point, but has a full navigation route. :)
There isn't any google approved way of doing it (as far as I looked to documentation). But I found this solution working pretty good
private void navigate(List<LatLng> latLngs) {
String uri = "";
for (LatLng latLng : latLngs) {
if (TextUtils.isEmpty(uri)) {
uri = String.format(
"http://maps.google.com/maps?saddr=%s, %s",
String.valueOf(latLng.latitude).replace(",", "."),
String.valueOf(latLng.longitude).replace(",", ".")
);
} else {
if (!uri.contains("&daddr")) {
uri += String.format(
"&daddr=%s, %s",
String.valueOf(latLng.latitude).replace(",", "."),
String.valueOf(latLng.longitude).replace(",", ".")
);
} else {
uri += String.format(
"+to:%s, %s",
String.valueOf(latLng.latitude).replace(",", "."),
String.valueOf(latLng.longitude).replace(",", ".")
);
}
}
}
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
}
Google Maps app on Android doesn't support multiple destinations. You can try to draw on the map by using native Google Maps Android API. You can get the directions from Google Maps Directions API.

Open map at specific coordinates not working on Android

I'm building an application with the functionality of sending specific pre-determined (but dynamic) coordinates to the user's map app so he can trace a route to it.
Currently, I'm using:
String coordinates = String.format("geo:0,0?q=" + latitude + "," + longitude);
Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse(coordinates) );
startActivity( intent );
However, when it does open the map, instead of the requested location I get a "no results for [latitude], [longitude]" toast and my current location instead.
It's certainly not an issue with the coordinates themselves as manually searching for them work just fine and printing the request Uri show that it's correctly constructed. Surprisingly, only sending the first two digits of both coords sort of works and, while doesn't send me where I want to, does not give the toast error message.
Do I need to do any extra formatting when passing the values or some other thing?
I'm using them raw, -23.561261 and -46.681212 for example, am located in Brazil if that makes any difference and, yes, I do have to send the coordinates as sadly the data is inconsistent with the formatting of the actual addresses.
UPDATE: As it turns out, the code is fine, it works on my razr-i, however, in the Galaxy Express I used for the original tests, it's still a no go.
Any idea of what is going on? Both devices are running Android 4.1.2
Don't quite remember what the error was since it's been so long ago, but long story short, here's the working code:
String coordinates = "http://maps.google.com/maps?daddr=" + latitude + "," + longitude;
Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse(coordinates) );
startActivity( intent );
Your code is correct,
the values that you send are double?
double latitude = -23.561261;
double longitude = -46.681212;
String coordinates = String.format("geo:0,0?q=" + latitude + "," + longitude);
Intent intentMap = new Intent( Intent.ACTION_VIEW, Uri.parse(coordinates) );
startActivity( intentMap );
must be something similar to load directly in your browser the url:
http://www.google.com/maps?q=-23.561261+-46.681212
The problem is in locale. Your code will work on any phone if you call format() like this:
String coordinates = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);

How to center Google maps driving directions between destination and source

I am using google maps URL commands to draw driving directions from a source to destination using the following commands:
String geoUriString = "http://maps.google.com/maps?" +
"saddr=" + latitude + "," + longitude + "&daddr=" + destLAT+ "," + destLONG;
then
Intent mapCall = new Intent(Intent.ACTION_VIEW, Uri.parse(geoUriString));
startActivity(mapCall);
This opens a list of options, when I choose google maps, it shows me the driving directions from the source to destination.
I have this question:
how can I zoom the map out to fit the drawn path from source to destination? (because now it is zoomed in too much, the full path is not shown at once)
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(18.49866955, 73.8957357166667),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);

Is there a way to show road directions in Google Map API v2? [duplicate]

This question already has answers here:
Get driving directions using Google Maps API v2
(4 answers)
Closed 3 years ago.
I was looking for an answer using Google and here, and the only relevant posts I have found are:
Google Maps Android V2 and Direction API
Get driving directions using Google Maps API v2
but there is no answer there. So I have already mentioned it but I will say that again. I am looking for a solution for the Google Map API v2 using FragmentActivity and a SupportMagFragment and LatLng objects and not using MapView ,MapActivity and GeoPoint.
In addition I don't have the Overlay object to use so I can't paint the direction on the map, is there an alternative for that?
So is there a way to do that?
Try this solution here. You can get driving or walking direction on V2.
The Overlay is indeed something to forget.
Polylines can easily be drawn
https://developers.google.com/maps/documentation/android/lines#add_a_polyline
Just loop through yourr points after you parsed tjhe JSON response:
PolylineOptions rectOptions = new PolylineOptions()
.add(new LatLng(37.35, -122.0))
.add(new LatLng(37.45, -122.0)) // North of the previous point, but at the same longitude
.add(new LatLng(37.45, -122.2)) // Same latitude, and 30km to the west
.add(new LatLng(37.35, -122.2)) // Same longitude, and 16km to the south
.add(new LatLng(37.35, -122.0)); // Closes the polyline.
// Set the rectangle's color to red
rectOptions.color(Color.RED);
// Get back the mutable Polyline
Polyline polyline = myMap.addPolyline(rectOptions);
Your question title is much more general than your requirements, so I will answer this in a way that I think will benefit those viewing this question and hopefully meet your requirements in perhaps a different way.
If you are not showing directions in the context of a map already being a loaded fragment and something having been done to show directions over the map (which is probably similar to what the OP is doing), it's easier and I believe standard to do this with an Intent.
This launches a map pathing activity (through a separate application - where the app launched depends on the user's compatible apps, which by default is Google Maps) that plots directions from the origin address (String originAddress) to the
destination address (String destinationAddress) via roadways:
// Build the URI query string.
String uriPath = "https://www.google.com/maps/dir/";
// Format parameters according to documentation at:
// https://developers.google.com/maps/documentation/directions/intro
String uriParams =
"?api=1" +
"&origin=" + originAddress.replace(" ", "+")
.replace(",", "") +
"&destination=" + destinationAddress.replace(" ", "+")
.replace(",", "") +
"&travelmode=driving";
Uri queryURI = Uri.parse(uriPath + uriParams);
// Open the map.
Intent intent = new Intent(Intent.ACTION_VIEW, queryURI);
startActivity(activity, intent, null);
(Where activity is simply the currently active Activity - obtained through whatever means are appropriate in the current programming context).
The following code gets an address String from a LatLng object (which must then be processed for the URI query String as above):
/**
* Retrieves an address `String` from a `LatLng` object.
*/
private void getAddressFromLocation(
final StringBuilder address, final LatLng latlng) {
// Create the URI query String.
String uriPath =
"https://maps.googleapis.com/maps/api/geocode/json";
String uriParams =
"?latlng=" + String.format("%f,%f",
latlng.latitude, latlng.longitude) +
"&key=" + GOOGLE_MAPS_WEB_API_KEY;
String uriString = uriPath + uriParams;
// Issue the query using the Volley library for networking.
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JSONObject response = null;
// Required for JsonObjectRequest, but not important here.
Map<String, String> jsonParams = new HashMap<String, String>();
JsonObjectRequest request =
new JsonObjectRequest(Request.Method.POST,
uriString,
new JSONObject(jsonParams),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
if (response != null) {
String resultString =
response.getJSONArray("results")
.getJSONObject(0)
.getString("formatted_address");
// Assumes `address` was empty.
address.append(resultString);
} // end of if
// No response was received.
} catch (JSONException e) {
// Most likely, an assumption about the JSON
// structure was invalid.
e.printStackTrace();
}
} // end of `onResponse()`
}, // end of `new Response.Listener<JSONObject>()`
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(LOG_TAG, "Error occurred ", error);
}
});
// Add the request to the request queue.
// `VolleyRequestQueue` is a singleton containing
// an instance of a Volley `RequestQueue`.
VolleyRequestQueue.getInstance(activity)
.addToRequestQueue(request);
}
This request is asynchronous, but it can be made synchronous.
You will need to call toString() on the actual parameter passed to address to obtain originAddress.
Q:I was looking for an answer using Google and here, and the only
relevant posts i have found are: Google Maps Android V2 and Direction
API Google map API v2 - get driving directions
Answer: Your saying, "but there is no answer there." is not absolutely right. In this site, you can find just only a few clues about that. I think you will not get the perfect code and concrete implement KNOW-HOWs here. In fact, many developers want to make the app to display the routing or directions on Google Maps. But I think there is no solution to get directions just only with the pure Google Maps API v2.
Q: So I have already mentioned it but I will say that again. I am
looking for a solution for the Google Map API v2 using
FragmentActivity and a SupportMagFragment and LatLng objects and not
using MapView ,MapActivtiy and GeoPoint.
Answer: Here are a few good sample tutorials (click here). You can find what you want.
Q: In addition i don't have the Overlay object to use so i can't paint
the direction on the map, is there an alternative for that? So is
there a way to do that?
Answer: In the Google Maps API v2, the annoying Overlay and so on are not any more required. For this, you can find the answer in my linked site above.

Categories

Resources