Optimize path with waypoints based on least distance google directions android - android

I was using google directions api to get the route between two latlng points and plotting it on a google map. The issue is that i can optimize the route when adding waypoints but i can't control the optimization criteria. The code i am using for creating the request url is :
private String getDirectionsUrl(LatLng origin, LatLng dest) {
// Origin of route
String str_origin = "origin=" + origin.latitude + "," + origin.longitude;
// Destination of route
String str_dest = "destination=" + dest.latitude + "," + dest.longitude;
// Sensor enabled
String sensor = "sensor=false";
// Waypoints
String waypoints = "";
for (int i = 0; i < markerPoints.size(); i++) {
LatLng point = (LatLng) markerPoints.get(i);
if (i == 0)
waypoints = "waypoints=optimize:true|";
if (i == markerPoints.size() - 1) {
waypoints += point.latitude + "," + point.longitude;
} else {
waypoints += point.latitude + "," + point.longitude + "|";
}
}
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor + "&" + waypoints + "&mode=driving&key=YOUR_API_KEY";
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
return url;
}
In short, i want to add optimization criteria in this string. Is it possible or do i have to enable alternate routes and manually calculate the travel distance of each path and choose the shortest?

Related

I have two latlong values. one for source and other for destination..In which format latlong value should pass to find distance between them

DIRECTION_URL_API = "https://maps.googleapis.com/maps/api/directions/json?"
DIRECTION_URL_API + "origin=" + origin + "&destination=" + destination + "&sensor=true" + "&mode=" +typeOpt+"&key=" + GOOGLE_API_KEY ;
I am using this format but its not working
Please suggest me :)
You can find distance following way
http://maps.googleapis.com/maps/api/directions/json?origin=21.1702,72.8311&destination=21.7051,72.9959&sensor=false&units=metric&mode=driving
origin=lat1,long1
destination=lat2,long2
Please use the below method to calculate the distance between two points
/**
* Returns Distance in kilometers (km)
*/
public static String distance(double startLat, double startLong, double endLat, double endLong) {
Location startPoint = new Location("locationA");
startPoint.setLatitude(startLat);
startPoint.setLongitude(startLong);
Location endPoint = new Location("locationA");
endPoint.setLatitude(endLat);
endPoint.setLongitude(endLong);
return String.format("%.2f", startPoint.distanceTo(endPoint) / 1000); //KMs
}
Method usage -
String mDistance = distance(startLat,
startLong,
endLat,endLng)).concat("km");

Android: Google Maps - draw path between multiple points

What I want to do is this:
I receive a list of directions/paths (that the user will have to follow using my app).
I am having trouble drawing the path on the map. The directions/paths contains the name of the streets, the coordinates of the streets and the segments of the streets.
I cant figure out how to draw the path/route on the map and make the route update - for example when the user moves (on the way) an icon to move indicating the progress of the user or the line drawn for the route gets shorter this really doesn't matter that much. So can you point me to tutorials which I can refer to?
I've seen a lot so far, but most of them get the directions from Google maps or the lines drawn are just straight lines from Start point to end point and doesn't fit the streets at all.
To achieve this, follow the below steps
Get list of ArrayList markerPoints;
Create your markers for it
single path,
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
for multiple destination path, for example A-B-D-C etc
private List<String> getDirectionsUrl(ArrayList<LatLng> markerPoints) {
List<String> mUrls = new ArrayList<>();
if (markerPoints.size() > 1) {
String str_origin = markerPoints.get(0).latitude + "," + markerPoints.get(0).longitude;
String str_dest = markerPoints.get(1).latitude + "," + markerPoints.get(1).longitude;
String sensor = "sensor=false";
String parameters = "origin=" + str_origin + "&destination=" + str_dest + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
mUrls.add(url);
for (int i = 2; i < markerPoints.size(); i++)//loop starts from 2 because 0 and 1 are already printed
{
str_origin = str_dest;
str_dest = markerPoints.get(i).latitude + "," + markerPoints.get(i).longitude;
parameters = "origin=" + str_origin + "&destination=" + str_dest + "&" + sensor;
url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters;
mUrls.add(url);
}
}
return mUrls;
}
Call the above method from
List<String> urls = getDirectionsUrl(markerPoints);
if (urls.size() > 1) {
for (int i = 0; i < urls.size(); i++) {
String url = urls.get(i);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
}
the above code will call for to create multiple paths, like A-B, B-D, D-C etc
try following this tutorial. You should draw between user location and marker. On user side call function onLocationChange to get the actual position and redraw the line. http://wptrafficanalyzer.in/blog/driving-route-from-my-location-to-destination-in-google-maps-android-api-v2/
Follow this:Android Google Map V3 PolyLine cannot be drawn
It'll help.
You just need to parse the data received after hitting Google Directions API

Track route on google map Android

I want to develop an Android application with track my route on google map.is it possible?if yes please can you tell me what is the API and any sample code link?
Follow this link Google Maps Android: How can i draw a route line to see directions & save all the latitude longitude valu for tracking the location .
Use api for getting direction
"http://maps.googleapis.com/maps/api/directions/json?"
+ "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode=driving";
or
If you only want to track the location use
public void onLocationChanged(Location location) {
if (lastLocationloc == null) {
lastLocationloc = location;
}
//public void setPoints (List<LatLng> points)
LatLng LatLng_origin = new LatLng( 13.133333, 78.133333); //kolar
LatLng LatLng3 = new LatLng(21.4949767, 86.942657999); // bbsr
TextView tvLocation = (TextView) findViewById(R.id.add);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10));
tvLocation.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
Any more doubt ??

rankby=distance in Google Places Android API

I have written some code to search nearby places based on their prominence. Next, I'd like to have my app search places based on ascending distance from the user. In order to do that, I learned that I need to use rankby=distance but rankby does not allow a value for radius - so the following radius-based search doesn't work:
nearPlaces = googlePlaces.search(
gps.getLatitude(),
gps.getLongitude(),
radius,
types
);
I've seen several blogs and articles where people asked similar questions, but none of them provided an answer which seems to work. What should I be using, if not the above?
correct is rankBy=distance...
Keep the B capital in rankBy...
private static final String PLACES_SEARCH_URL = "https://maps.googleapis.com/maps/api/place/search/json?rankby=distance&";
public PlacesList search(double latitude, double longitude, double radius, String types)
throws Exception {
this._latitude = latitude;
this._longitude = longitude;
this._radius = radius;
//this._rankby=_rankby;
try {
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request = httpRequestFactory
.buildGetRequest(new GenericUrl(PLACES_SEARCH_URL));
request.getUrl().put("key", API_KEY);
request.getUrl().put("location", _latitude + "," + _longitude);
// request.getUrl().put("radius", _radius);
request.getUrl().put("rankBy", _radius);
// in meters
request.getUrl().put("sensor", "false");
//request.getUrl().put("rankby", _rankby);
if(types != null)
request.getUrl().put("types", types);
PlacesList list = request.execute().parseAs(PlacesList.class);
// Check log cat for places response status
Log.d("Places Status", "" + list.status);
return list;
} catch (HttpResponseException e) {
Log.e("Error:", e.getMessage());
return null;
}
}
You can bypass it. I used 'GOOGLE PLACES WEB SERVICES'
https://developers.google.com/places/webservice/search :
get a JSON of all your places using PLACES API (use HttpURLConnection to send the request) :
String nearByPlaceSearchURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?"
+ "location=" + myLatPosition + "," + myLonPosition
+ "&radius=" + myPlaceDistanceMeters
+ "&types=" + myPlaceName
+ "&key=" + MyConstants.KEY_FOR_PLACES_AND_DISTANCES_API;
Parse the returned JSON and get the coordinates, LAT/LON, of each one of the places.
Get a JSON of all the distances from your current position to each one of the places using DISTANCE MATRIX API:
String distancesSearchURL = "https://maps.googleapis.com/maps/api/distancematrix/json?"
+ "origins=" + myLatPosition + "," + myLonPosition
+ "&destinations=" + allPlacesCoordinates
+ "&mode=walking"
+ "&key=" + MyConstants.KEY_FOR_PLACES_AND_DISTANCES_API;
Note that the distance is a walking,driving or cycling distance, which is the distance we are interested in. The radius distance (air distance) is not relevant. The walking/driving/cycling distances are bigger than the air distance.Therefore, for example, you can search for a place in radius of 10 km but the walking distance to it will be 11 km.
Create an Object for each one of the places with its name and distance from your current position as internal variables.
Generate an ArrayList containing all your Objects places.
Sort the ArrayList using the method comparator according to the distance.

Passing current location ( longitude and latitude ) in the Google Places API

am trying to integrate Google Places API into my app.
Now I am finding out my current location of the Phone, how do I embed the longitude and latitude which I have got into the following URL instead of "location=34.0522222,-118.2427778"
"https://maps.googleapis.com/maps/api/place/search/xml?location=34.0522222,-118.2427778&radius=500&types=restaurants&sensor=false&key=Your_API_Key"
Do you mean how do you do string manipulation such as (untested):
int latitude = ...;
int longitude = ...;
String preamble = "https://maps.googleapis.com/maps/api/place/search/xml?location=";
String postamble = "&radius=500&types=restaurants&sensor=true&key=";
String key = "Your_api_key";
String latStr = latitude + "";
String longStr = longitude + "";
String url = preamble + latStr + "," + longStr + postamble + key;
$lat = location[0];
$long = location[1];
Should work, but I use json for geting long and lat from google. Is better. I can check it again if not working.
Here is better json solution:
http://maps.googleapis.com/maps/api/geocode/json?address=Atlantis&sensor=true&oe=utf-8
You should change Atlantis to address

Categories

Resources