I'm getting Latitudes and Longitudes from Google Directions API and using them to show polyline between two locations. Polyline is being drawn but not following the exact road or path that it must follow.
Here are my screenshots-
Screenshot 1
Screenshot 2
Here is my code through which i'm getting LatLngs and displaying polyline.
public void requestDirections(final String mode, String origin, String destination)
{
final ProgressDialog progress=new ProgressDialog(this);
progress.setMessage("Finding route");
progress.show();
Retrofit retrofit= new Retrofit.Builder().baseUrl("https://maps.googleapis.com/").addConverterFactory(GsonConverterFactory.create()).build();
Call<DirectionResponse> call=retrofit.create(ApiDirections.class).getDirections(mode, origin, destination);
call.enqueue(new Callback<DirectionResponse>() {
#Override
public void onResponse(Call<DirectionResponse> call, Response<DirectionResponse> response) {
for(int i=0; i<response.body().getRoutes().get(0).getLegs().get(0).getSteps().size(); i++)
{
LatLng startLoc=new LatLng(response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(i).getStartLocation().getLat(), response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(i).getStartLocation().getLng());
LatLng endLoc=new LatLng(response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(i).getEndLocation().getLat(), response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(i).getEndLocation().getLng());
Polyline polyline=response.body().getRoutes().get(0).getLegs().get(0).getSteps().get(i).getPolyline();
DataHandler.startingLocations.add(startLoc);
DataHandler.endingLocations.add(endLoc);
System.out.println("Starting Loc "+i+" "+startLoc);
System.out.println("Ending Loc "+i+" "+endLoc);
System.out.println("polyline "+i+" "+polyline.getPoints());
}
LatLng endLocation=new LatLng(response.body().getRoutes().get(0).getLegs().get(0).getEndLocation().getLat(), response.body().getRoutes().get(0).getLegs().get(0).getEndLocation().getLng());
marker=mMap.addMarker(new MarkerOptions().position(endLocation).flat(true));
marker.setTag(destinationName);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(DataHandler.startingLocations.get((response.body().getRoutes().get(0).getLegs().get(0).getSteps().size())/2), 10));
polylineOptions=new PolylineOptions();
polylineOptions.addAll(DataHandler.endingLocations);
polylineOptions.color(getResources().getColor(R.color.colorAccent));
polylineOptions.width(12);
polylineOptions.startCap(new RoundCap());
polylineOptions.endCap(new RoundCap());
mMap.addPolyline(polylineOptions);
textViewJourneyDistance.setText(response.body().getRoutes().get(0).getLegs().get(0).getDistance().getText());
textViewJourneyTime.setText(response.body().getRoutes().get(0).getLegs().get(0).getDuration().getText());
progress.dismiss();
}
#Override
public void onFailure(Call<DirectionResponse> call, Throwable t) {
progress.dismiss();
}
});
}
public interface ApiDirections{
#GET("maps/api/directions/json?key=My_API_KEY")
Call<DirectionResponse> getDirections(#Query("mode") String mode,
#Query("origin") String origin,
#Query("destination") String destination);
}
you need to get routelist
ArrayList<LatLng> routelist = new ArrayList<LatLng>();
if (response.body().getRoutes().size() > 0) {
ArrayList<LatLng> decodelist;
Route routeA = response.body().getRoutes().get(0);
Log.e("ad", "Legs length : " + routeA.getLegs().size());
if (routeA.getLegs().size() > 0) {
List<Steps> steps = routeA.getLegs().get(0).getSteps();
Log.e("ad", "Steps size :" + steps.size());
Steps step;
Location location;
String polyline;
for (int i = 0; i < steps.size(); i++) {
step = steps.get(i);
location = step.getStart_location();
routelist.add(new LatLng(location.getLat(), location.getLng()));
Log.e("ad", "Start Location :" + location.getLat() + ", " + location.getLng());
polyline = step.getPolyline().getPoints();
decodelist = RouteDecode.decodePoly(polyline);
routelist.addAll(decodelist);
location = step.getEnd_location();
routelist.add(new LatLng(location.getLat(), location.getLng()));
Log.e("ad", "End Location :" + location.getLat() + ", " + location.getLng());
Integer disInMeters = routeA.getLegs().get(0).getDistance().getValue();
int kilometers = (int) (disInMeters * 0.001);
}
}
}
if (routelist.size() > 0) {
PolylineOptions rectLine = new PolylineOptions().width(10).color(ContextCompat.getColor(SendSomethingTodayActivityThree.this, R.color.colorPrimary));
for (int i = 0; i < routelist.size(); i++) {
rectLine.add(routelist.get(i));
}}
its work for me
Related
I was able to make multiple marks on the google map on android by getting data from JSON. So NOW each of those markers has their own corresponding bukken_name, latitute and longitude.
Each time I click a specific marker on the map. I want it to display in console their retrieved JSON data.
In my current code, onMarkerClick gets the values and then displays it in System.out.println. But whenever I do so click the marker it only keeps on display the exact same value of the last JSON data.
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");
JSONArray bukken_list = data.getJSONArray("bukken_list");
for (int i = 0; i < bukken_list.length(); i++) {
JSONObject returnBukken = bukken_list.getJSONObject(i);
String latitude = returnBukken.getString("ido_hokui"); //latitude
String longitude = returnBukken.getString("keido_tokei"); //longitude
final String bukken_name = returnBukken.getString("bukken_name"); //longitude
final Double x = Double.parseDouble(latitude);
final Double y = Double.parseDouble(longitude);
System.out.println("COORDINATES: " + i);
System.out.println("LATITUDE: " + latitude);
System.out.println("LONGITUDE: " + longitude);
System.out.println("BUKKEN NAME: " + longitude);
LatLng japan = new LatLng(x, y);
MarkerOptions client_marker = new MarkerOptions().position(new LatLng(x, y));
client_marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.mapicon_rent));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(japan, 10f));
mMap.addMarker(client_marker);
mMap.moveCamera(CameraUpdateFactory.newLatLng(japan));
mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker arg0) {
//FAULT: does not get value of each marker
System.out.println("MARKER " + x + " " + y + " " + bukken_name);
return true;
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
int x = 1;
// Anything you want
}
});
Set bukken_name as marker's tag:
Marker marker = mMap.addMarker(client_marker);
marker.setTag(bukken_name);
On marker click:
public boolean onMarkerClick(Marker clickedMarker) {
LatLng location = clickedMarker.getPosition();
System.out.println("MARKER " + location.latitude + " " + location.longitude + " " + clickedMarker.getTag());
return true;
}
In my app user can insert multiple location and show in map. How can i achieve this? I know how to draw route between two location but i want to draw route between multiple marker as like image.
In image marker show location that is entered by user. I also want to calculate distance between marker like calculate distance between B to C and C to D.
How can I achieve this??
Use direction api which return multi-part directions using a series of waypoints.
Direction api Documentation
private static final LatLng LOWER_MANHATTAN = new LatLng(40.722543,-73.998585);
private static final LatLng BROOKLYN_BRIDGE = new LatLng(40.7057, -73.9964);
private static final LatLng WALL_STREET = new LatLng(40.7064, -74.0094);
private String getMapsApiDirectionsUrl() {
String origin = "origin=" + LOWER_MANHATTAN.latitude + "," + LOWER_MANHATTAN.longitude;
String waypoints = "waypoints=optimize:true|" + BROOKLYN_BRIDGE.latitude + "," + BROOKLYN_BRIDGE.longitude + "|";
String destination = "destination=" + WALL_STREET.latitude + "," + WALL_STREET.longitude;
String sensor = "sensor=false";
String params = origin + "&" + waypoints + "&" + destination + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}
}
When you get response from above request . you need to draw route from response
public void drawRoute(String result) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Polyline line = mMap.addPolyline(new PolylineOptions()
.addAll(list)
.width(12)
.color(Color.parseColor("#05b1fb"))//Google maps blue color
.geodesic(true)
);
} catch (JSONException e) {
}
}
You will get more detail of this from Draw-route-github
For Distance calculation you need to Distance Matrix API is a service that provides travel distance and time for a matrix of origins and destinations
Using direction api you can achieve this.
you just have to pass user inserted marker as waypoints as follow
https://maps.googleapis.com/maps/api/directions/json?
origin=sydney,au&destination=perth,au
&waypoints=via:-37.81223%2C144.96254%7Cvia:-34.92788%2C138.60008
&key=YOUR_API_KEY
you will get list of route which have the distance between to points
//retrofit
#GET("https://maps.googleapis.com/maps/api/directions/json")
Observable<DirectionResults> getDirectionWithWayPoints(#Query("origin") String origin, #Query("destination") String destination, #Query("waypoints") String wayPoints, #Query("key") String key);
// plotting logic
api.getDirectionWithWayPoints(startPoint, endPoint, stringBuilder.toString(), getString(R.string.API_KEY))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new Observer<DirectionResults>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(DirectionResults directionResults) {
hideDialog();
if (null == directionResults) {
return;
}
ArrayList<LatLng> routelist = new ArrayList<>();
routelist.add(latLngStart);
if (directionResults.getRoutes().size() > 0) {
List<LatLng> decodelist;
RoutesItem routeA = directionResults.getRoutes().get(0);
if (routeA.getLegs().size() > 0) {
for (int j = 0; j < routeA.getLegs().size(); j++) {
List<StepsItem> steps = routeA.getLegs().get(j).getSteps();
StepsItem step;
Location location;
String polyline;
for (int i = 0; i < steps.size(); i++) {
step = steps.get(i);
polyline = step.getPolyline().getPoints();
decodelist = DirectionsJSONParser.decodePoly(polyline);
routelist.addAll(decodelist);
}
}
}
}
if (routelist.size() > 0) {
routelist.add(latLngEnd);
rectLine = new PolylineOptions().width(12).color(
Color.CYAN);
for (int i = 0; i < routelist.size(); i++) {
rectLine.add(routelist.get(i));
}
// Adding route on the map
if (null != mMap) {
mMap.addPolyline(rectLine);
fixZoom(rectLine, mMap);
getVehicleId();
}
}
}
#Override
public void onError(Throwable e) {
hideDialog();
e.printStackTrace();
}
#Override
public void onComplete() {
}
});
}
}
Google provides libraries out of the box for solving this kind of issues.
I would structure my application in following manner.
Use Retrofit 2 for connecting to network. (https://square.github.io/retrofit/)
Use google API's, you will need more than 1 API to achieve both of the tasks.
2.a To find out distances between two points use Google Distance Matrix API (https://developers.google.com/maps/documentation/distance-matrix/start).
2.b To add multiple markers you can refer to following answer
Google Maps JS API v3 - Simple Multiple Marker Example
For draw route you can use :
PolylineOptions options = new
PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = myMap.addPolyline(options);
And calculating distance for usimg **Google Maps Direction API**
I have added a waypoint and drawn the polyline from start to destination through the waypoint. But an extra straight line is drawn from start to destination. How can I remove it ?
The code below shows the ParserTask and getDirections URL.
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = parser.parse(jObject);
Log.d("routes", routes.toString());
Log.d("jObject", jObject.toString());
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = new ArrayList<LatLng>();;
PolylineOptions lineOptions = new PolylineOptions();;
lineOptions.width(2);
lineOptions.color(Color.RED);
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
private String getDirectionsUrl(LatLng origin_start, LatLng dest, LatLng waypoint_xx) {
String origin = "origin=" + origin_start.latitude + "," + origin_start.longitude;
//String waypointss = "waypoints=optimize:true|" + waypoint_xx.latitude + "," + waypoint_xx.longitude ;
String destination = "destination=" + dest.latitude + "," + dest.longitude;
// Waypoints
String waypoints = "";
for(int i=2;i<markerPoints.size();i++){
LatLng point = (LatLng) markerPoints.get(i);
if(i==2)
waypoints = "waypoints=";
waypoints += point.latitude + "," + point.longitude + "|";
}
String sensor = "sensor=false";
String alternative = "alternatives=false";
String params = origin + "&" + destination + "&" + alternative + "&" + sensor + "&" + waypoints ;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}
This code is the Directions JSON Parser
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l <list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List decodePoly(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
This is the Download Task
private class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
Log.d("parserTask data", data.toString());
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
Log.d("parserTask result", result.toString());
parserTask.execute(result);
}
}
And finally the onMapReady method
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
UiSettings uiSettings = googleMap.getUiSettings();
//uiSettings.setCompassEnabled(false);
uiSettings.setZoomControlsEnabled(true);
//-------------
// mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
//-------------
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("location");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(MapsActivity.this)
.setSmallIcon(R.drawable.applogo)
.setContentTitle("Trip Request")
.setContentText("Click to accept trip!");
manager = (NotificationManager) MapsActivity.this.getSystemService( MapsActivity.this.NOTIFICATION_SERVICE );
manager.notify(0, builder.build());
// sendNotification();
startLatFB = (Double) dataSnapshot.child("startLat").getValue();
startLonFB = (Double) dataSnapshot.child("startLon").getValue();
endLatFB = (Double) dataSnapshot.child("endLat").getValue();
endLonFB = (Double) dataSnapshot.child("endLon").getValue();
Log.d("startLat", startLatFB.toString());
Log.d("startLon", startLonFB.toString());
Log.d("endLat", endLatFB.toString());
Log.d("endLon", endLonFB.toString());
if (markerPoints.size() > 1) {
markerPoints.clear();
mMap.clear();
}
double startLat = startLatFB; //SLIIT
double startLon = startLonFB;
double wayPointLat = 6.9040322; //FAB - Malabe
double wayPointLon = 79.948803;
double wayPointLatTwo = 6.053519; //FAB - Malabe
double wayPointLonTwo = 80.220977;
double endLat = endLatFB; //MAS
double endLon = endLonFB;
LatLng start_latLng = new LatLng(startLat, startLon);
LatLng waypoint_latLng = new LatLng(wayPointLat, wayPointLon);
LatLng end_latLng = new LatLng(endLat, endLon);
// LatLng start_latLng = new LatLng(startLatFB, startLonFB);
// LatLng waypoint_latLng = new LatLng(wayPointLat, wayPointLon);
// LatLng end_latLng = new LatLng(endLatFB, endLonFB);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(start_latLng, 11));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(start_latLng,11f));
// start_latLng = startLatFB;
// Adding new item to the ArrayList
markerPoints.add(start_latLng);
markerPoints.add(end_latLng);
markerPoints.add(waypoint_latLng);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
MarkerOptions optionsTwo = new MarkerOptions();
MarkerOptions optionsThree = new MarkerOptions();
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.startlocation);
BitmapDescriptor icon2 = BitmapDescriptorFactory.fromResource(R.drawable.endlocation);
// Setting the position of the marker
options.position(start_latLng);
optionsTwo.position(end_latLng);
optionsThree.position(waypoint_latLng);
if (markerPoints.size() == 1) {
options.icon(icon);
} else if (markerPoints.size() == 2) {
options.icon(icon2);
}
// Add new marker to the Google Map Android API V2
mMap.addMarker(options);
mMap.addMarker(optionsTwo);
mMap.addMarker(optionsThree);
// Checks, whether start and end locations are captured
if (markerPoints.size() >= 3) {
LatLng origin = (LatLng) markerPoints.get(0);
LatLng dest = (LatLng) markerPoints.get(1);
LatLng waypointss = (LatLng) markerPoints.get(2);
Log.d("origin url", origin.toString());
Log.d("dest url", origin.toString());
Log.d("waypoint url", origin.toString());
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest, waypointss);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
Log.d("DownloadTask url", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try initializing new Arraylist of Points each time while traversing.
Here is a sample:
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>(); //initialize here
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
For detail implementation Go through This Link
I am new to android. I want to draw routes between multiple markers. I a, getting latitude, longitude and datetime from server. Now i want to show route between the points. I have stored them in arraylist. Here is how i am getting the points in async task doInBackground().
newLatt= new ArrayList<String>();
newLongg= new ArrayList<String>();
newdatTime= new ArrayList<String>();
JSONArray arr = new JSONArray(strServerResponse);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonObj1 = arr.getJSONObject(i);
String status = jsonObj1.optString("status");
if (status!="false"){
Pojo pojo = new Pojo();
String latitude = jsonObj1.optString("Latitude");
String longitude = jsonObj1.optString("Longitude");
String date_time = jsonObj1.optString("date_time");
newLatt.add(latitude);
newLongg.add(longitude);
newdatTime.add(date_time);
}else {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
AlertDialog alertDialog = new AlertDialog.Builder(
MapActivity.this).create();
alertDialog.setMessage("Locations Not Available");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.show();
}
}
);
}
and in postExecute() method i am showing markers
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = supportMapFragment.getMap();
map.setMyLocationEnabled(true);
if (newLatt.size()>0){
for (int i = 0; i < newLatt.size(); i++) {
Double lati = Double.parseDouble(newLatt.get(i));
Double longi = Double.parseDouble(newLongg.get(i));
String dattme = newdatTime.get(i);
dest = new LatLng(lati, longi);
if (map != null) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(dest);
map.moveCamera(CameraUpdateFactory.newLatLng(dest));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
markerOptions.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
markerOptions.title("" + dattme);
map.addMarker(markerOptions);
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
marker.showInfoWindow();
return false;
}
});
UPDATE
PolylineOptions rectOptions = new PolylineOptions();
//this is the color of route
rectOptions.color(Color.argb(255, 85, 166, 27));
LatLng startLatLng = null;
LatLng endLatLng = null;
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = supportMapFragment.getMap();
map.setMyLocationEnabled(true);
if (newLatt.size()>0){
for (int i = 0; i < newLatt.size(); i++) {
Double lati = Double.parseDouble(newLatt.get(i));
Double longi = Double.parseDouble(newLongg.get(i));
String dattme = newdatTime.get(i);
dest = new LatLng(lati, longi);
if (map != null) {
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(dest);
map.moveCamera(CameraUpdateFactory.newLatLng(dest));
map.animateCamera(CameraUpdateFactory.zoomTo(15));
markerOptions.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED));
markerOptions.title("" + dattme);
map.addMarker(markerOptions);
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
#Override
public boolean onMarkerClick(Marker marker) {
marker.showInfoWindow();
return false;
}
});
LatLng latlng = new LatLng(lati,
longi);
if (i == 0) {
startLatLng = latlng;
}
if (i == newLatt.size() - 1) {
endLatLng = latlng;
}
rectOptions.add(latlng);
String url = getDirectionsUrl(startLatLng, endLatLng);
DownloadTask downloadTask = new DownloadTask();
downloadTask.execute(url);
}
}
map.addPolyline(rectOptions);
getDirections:
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";
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + sensor;
// 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 your postExecute add the following code to add ploylines on the map.
PolylineOptions rectOptions = new PolylineOptions();
//this is the color of route
rectOptions.color(Color.argb(255, 85, 166, 27));
LatLng startLatLng = null;
LatLng endLatLng = null;
for (int i = 0; i < newLatt.size(); i++) {
Double lati = Double.parseDouble(newLatt.get(i));
Double longi = Double.parseDouble(newLongg.get(i));
LatLng latlng = new LatLng(lati,
longi);
if (i == 0) {
startLatLng = latlng;
}
if (i == jArr.length() - 1) {
endLatLng = latlng;
}
rectOptions.add(latlng);
}
map.addPolyline(rectOptions);
Happy coding...
Android does not provide embedded direction service in google map api. To draw route between points you must use google direction services REST API .
You can get complete code and description from http://wptrafficanalyzer.in/blog/drawing-driving-route-directions-between-two-locations-using-google-directions-in-google-map-android-api-v2/
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>();
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){
HashMap<String,String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
I am trying this from quite long so is why i am here seeking for some serious help!!
In my application i am suppose to plot more than 2 alternative routes onclick of a button, say in my application i have 3 buttons such as r1,r2 and r3.When i enter the source and destination locations in my application's respective's edittexts and click enter then i shall be plotting by default r1 so now when i click on r2 button the path/route plotted on the map previously should be erased/deleted and the new alternative path/route should be plotted on the map but isnt happening that way instead of erasing the previous path/route it is plotting both the routes on the map:( can someone please help me?
Here is my code.
List<RoutesDictionary> routeDicList = new ArrayList<RoutesDictionary>();
routeTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
map.clear();
routeDicList.clear();
routeType = 2;
rout = "walking";
new TrafficData().execute();
Log.d("TH routeTwo", "In routeTwo After" +
`enter code here`routeDicList.size());
}
});
public class TrafficData extends AsyncTask<Context, String, String> {
routeTwo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
map.clear();
routeDicList.clear();
routeType = 2;
rout = "walking";
new TrafficData().execute();
}
});
#Override
protected String doInBackground(Context... params) {
try {
if (!via_route.equals("")) {
url = "http://maps.googleapis.com/maps/api/directions/json?origin="
+ sourceAdd
+ "&destination="
+ destinationAdd
+ "&waypoints=via:"
+ via_route
+ "&sensor=false&mode=" + rout;
} else {
url = "http://maps.googleapis.com/maps/api/directions/json?origin="
+ sourceAdd
+ "&destination="
+ destinationAdd
+ "&sensor=false&mode=" + rout;
}
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
result = EntityUtils.toString(httpResponse.getEntity());
Log.v("Traffic App : ", "The Traffic App result is : "
+ result);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.v("Traffic App : ", "The Traffic App resultTraffic is : "
+ resultTraffic);
try {
JSONObject routesObj = new JSONObject(result);
String status = routesObj.getString("status");
if (status.equals("OK")) {
routesDictionary = new RoutesDictionary();
allRouteDic.addSrcAddress(sourceAdd);
allRouteDic.addDesAddress(destinationAdd);
AllRoutes.allRoutes.add(allRouteDic);
Log.v("***********************", "THE ***** Array list : ");
JSONArray routesArr = routesObj.getJSONArray("routes");
JSONObject mainObj = routesArr.getJSONObject(0);
JSONArray legsArr = mainObj.getJSONArray("legs");
int legsSize = legsArr.length();
for (int i = 0; i < legsSize; i++) {
routesDictionary.addlegsDistance(legsArr.getJSONObject(
i).getJSONObject("distance"));
routesDictionary.addlegsDuration(legsArr.getJSONObject(
i).getJSONObject("duration"));
routesDictionary.addlegsEndaddress(legsArr
.getJSONObject(i).getString("end_address"));
routesDictionary
.addlegsEndlocation(legsArr.getJSONObject(i)
.getJSONObject("end_location"));
routesDictionary.addlegsStartaddress(legsArr
.getJSONObject(i).getString("start_address"));
routesDictionary.addlegsStartlocation(legsArr
.getJSONObject(i).getJSONObject(
"start_location"));
routeDicList.add(routesDictionary);
JSONArray stepsArr = legsArr.getJSONObject(i)
.getJSONArray("steps");
int stepsLen = stepsArr.length();
for (int j = 0; j < stepsLen; j++) {
routesDictionary
.addlegs_StepsDistance(stepsArr
.getJSONObject(j).getJSONObject(
"distance"));
routesDictionary
.addlegs_StepsDuration(stepsArr
.getJSONObject(j).getJSONObject(
"duration"));
routesDictionary.addlegs_StepsEndlocation(stepsArr
.getJSONObject(j).getJSONObject(
"end_location"));
routesDictionary.addlegs_StepsHtmlInstruct(stepsArr
.getJSONObject(j).getString(
"html_instructions"));
routesDictionary
.addlegs_StepsPloyline(stepsArr
.getJSONObject(j).getJSONObject(
"polyline"));
routesDictionary
.addlegs_StepsStartlocation(stepsArr
.getJSONObject(j).getJSONObject(
"start_location"));
routesDictionary.addlegs_StepsTravelmode(stepsArr
.getJSONObject(j).getString("travel_mode"));
routeDicList.add(routesDictionary);
}
}
int strLoc = routeDicList.get(0)
.getlegs_StepsStartlocation().size();
for (int k = 0; k < strLoc; k++) {
routesDictionary.addStrLatit(routeDicList.get(0)
.getlegs_StepsStartlocation().get(k)
.getString("lat"));
routesDictionary.addStrlongi(routeDicList.get(0)
.getlegs_StepsStartlocation().get(k)
.getString("lng"));
routeDicList.add(routesDictionary);
}
int endLoc = routeDicList.get(0).getlegs_StepsEndlocation()
.size();
for (int l = 0; l < endLoc; l++) {
routesDictionary.addEndLatit(routeDicList.get(0)
.getlegs_StepsEndlocation().get(l)
.getString("lat"));
routesDictionary.addEndLongi(routeDicList.get(0)
.getlegs_StepsEndlocation().get(l)
.getString("lng"));
routeDicList.add(routesDictionary);
}
int strL = routeDicList.get(0).getStrLatit().size();
for (int m = 0; m < strL; m++) {
Log.v("Traffic : ", "*** Latitude and Longi *** : "
+ routeDicList.get(0).getStrLatit().get(m)
+ " "
+ routeDicList.get(0).getStrLong().get(m));
}
int endL = routeDicList.get(0).getEndLatit().size();
for (int m = 0; m < endL; m++) {
Log.v("Traffic : ", "### Latitude and Longi ### : "
+ routeDicList.get(0).getEndLatit().get(m)
+ " "
+ routeDicList.get(0).getEndLong().get(m));
}
rectOptions = new PolylineOptions();
Log.v("*****************", "The RECTPOINTS SIZE : "
+ rectOptions.getPoints().size());
rectOptions.getPoints().clear();
switch (routeType) {
case 1:
rectOptions.color(Color.RED);
break;
case 2:
rectOptions.color(Color.BLUE);
break;
case 3:
rectOptions.color(Color.GREEN);
break;
default:
break;
}
rectOptions.width(4);
for (int i = 1; i < strL; i++) {
rectOptions.add(new LatLng(Double.valueOf(routeDicList
.get(0).getStrLatit().get(i)), Double
.valueOf(routeDicList.get(0).getStrLong()
.get(i))));
}
// Get back the mutable Polygon
map.clear();
polyline = map.addPolyline(rectOptions.geodesic(false));
polyline.remove();
polyline = map.addPolyline(rectOptions.geodesic(true));
double lng = Double.valueOf(routeDicList.get(0)
.getlegs_StepsStartlocation().get(0)
.getString("lng"));
double lat = Double.valueOf(routeDicList.get(0)
.getlegs_StepsStartlocation().get(0)
.getString("lat"));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(lat, lng), 14.0f));
// start longitude and latitude
double startlng = Double
.valueOf(routeDicList.get(0)
.getlegs_StepsEndlocation().get(0)
.getString("lng"));
double startlat = Double
.valueOf(routeDicList.get(0)
.getlegs_StepsEndlocation().get(0)
.getString("lat"));
// start location marker
addMarker(startlat, startlng);
// end longitude and latitude
double endlng = Double.valueOf(routeDicList.get(0)
.getlegs_StepsStartlocation().get(endLoc - 1)
.getString("lng"));
double endlat = Double.valueOf(routeDicList.get(0)
.getlegs_StepsStartlocation().get(endLoc - 1)
.getString("lat"));
// end location marker
addMarker(endlat, endlng);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
1- You set the OnClickListener for routeTwo button twice one in the main class and one in the AsyncTask , the one in the AsyncTask should be removed.
2- Pressing the button twice fast would produce your problem, because you will start two separably AsyncTasks each one will draw a route so both routes would be displayed, i prefer using just one AsyncTask as a global variable and before running new one check if there is a running AsyncTask ,this could be done by
if(trafficData != null && trafficData.getStatus() != AsyncTask.Status.FINISHED){
trafficData .cancel(true);
}