Activity - Main - XML: Exercise Program Code
Activity - Main - XML: Exercise Program Code
Activity - Main - XML: Exercise Program Code
Program Code:
activity_main.xml
MainActivity.java
package com.example.practical32ex;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import androidx.fragment.app.FragmentActivity;
class MapsActivityextends FragmentActivityimplements OnMapReadyCallback{
private GoogleMapmMap;
MarkerOptionsorigin, destination;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragmentmapFragment= (SupportMapFragment)
getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(origin.getPosition(),
10));
}
private class DownloadTaskextends 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());
}
return data;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTaskparserTask= new ParserTask();
parserTask.execute(result);
}
}
/**
* A class to parse the JSON format
*/
private class ParserTaskextends 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) {
JSONObjectjObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject= new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new
DirectionsJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
@Override
protected void onPostExecute(List<List<HashMap<String,
String>>> result) {
ArrayList points = new ArrayList();
PolylineOptionslineOptions= new
PolylineOptions();
for (int i = 0; i<result.size(); i++) {
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
if (points.size() != 0)
mMap.addPolyline(lineOptions);
}
}
private String getDirectionsUrl(LatLngorigin, LatLngdest) {
String str_origin= "origin=" + origin.latitude+ "," + origin.longitude;
String str_dest= "destination=" + dest.latitude+ "," + dest.longitude;
String sensor = "mode=driving";
String parameters = str_origin+ "&" + str_dest+ "&" + "&" + sensor;
String output = "json";
String url= "https://maps.googleapis.com/maps/api/directions/" + output + "?" +
parameters + "&key=" +
"AIzaSyD_L8g3AcwXBKnEjhvLJwBXwI3L51LjQUU";
return url;
}
DirectionsJSONParser.java
package com.example.practical32ex;
import com.google.android.gms.maps.model.LatLng;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
try {
jRoutes = jObject.getJSONArray("routes");
for (int i = 0; i<jRoutes.length(); i++) {
jLegs = ((JSONObject)
jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String,
String>>();
for (int j = 0; j <jLegs.length(); j++) {
jSteps = ((JSONObject)
jLegs.get(j)).getJSONArray("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);
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 (JSONExceptione) {
e.printStackTrace();
} catch (Exception e) {
}
return routes;
}
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;
}
}
Output: