0% found this document useful (0 votes)
4 views6 pages

EX 32

The document provides code for an Android application that draws a route between two locations using Google Maps API. It includes XML layout for the map and Java code for handling map interactions, marker placements, and fetching directions from the Google Directions API. The application captures user clicks to set start and end points and displays the route on the map with a polyline.

Uploaded by

Omkar Mankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views6 pages

EX 32

The document provides code for an Android application that draws a route between two locations using Google Maps API. It includes XML layout for the map and Java code for handling map interactions, marker placements, and fetching directions from the Google Directions API. The application captures user clicks to set start and end points and displays the route on the map with a polyline.

Uploaded by

Omkar Mankar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

X.

Exercise
1. Write a program to draw a route between two locations.

activity_main.xml import
com.google.android.gms.maps.OnMapReadyCallb
ack;
<?xml version="1.0" encoding="utf-8"?>
import
<fragment com.google.android.gms.maps.SupportMapFragm
xmlns:android="http://schemas.android.com/apk/r ent;
es/android"
import
com.google.android.gms.maps.model.BitmapDesc
xmlns:map="http://schemas.android.com/apk/res- riptorFactory;
auto"
import
xmlns:tools="http://schemas.android.com/tools" com.google.android.gms.maps.model.LatLng;

android:id="@+id/map" import
com.google.android.gms.maps.model.MarkerOpti
ons;
android:name="com.google.android.gms.maps.Su
pportMapFragment" import
com.example.ex3201.databinding.ActivityMapsBi
android:layout_width="match_parent" nding;
android:layout_height="match_parent" import
tools:context=".MapsActivity" /> com.google.android.gms.maps.model.PolylineOpt
ions;
import org.json.JSONObject;
MainActivity.java
import java.io.BufferedReader;
package com.example.ex3201;
import java.io.IOException;
import java.io.InputStream;
import androidx.fragment.app.FragmentActivity;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import android.graphics.Color;
import java.net.URL;
import android.os.AsyncTask;
import java.util.ArrayList;
import android.os.Bundle;
import java.util.HashMap;
import android.util.Log;
import java.util.List;
import
com.google.android.gms.maps.CameraUpdateFact
ory; public class MapsActivity extends
import FragmentActivity implements
com.google.android.gms.maps.GoogleMap; OnMapReadyCallback {

private GoogleMap mMap;


private ActivityMapsBinding binding; public void onMapClick(LatLng latLng) {
ArrayList markerPoints= new ArrayList();
if (markerPoints.size() > 1) {
@Override markerPoints.clear();
protected void onCreate(Bundle mMap.clear();
savedInstanceState) {
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Adding new item to the ArrayList
binding =
markerPoints.add(latLng);
ActivityMapsBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
// Creating MarkerOptions
MarkerOptions options = new
SupportMapFragment mapFragment =
MarkerOptions();
(SupportMapFragment)
getSupportFragmentManager()
.findFragmentById(R.id.map); // Setting the position of the marker
mapFragment.getMapAsync(this); options.position(latLng);
}

if (markerPoints.size() == 1) {
@Override
options.icon(BitmapDescriptorFactory.defaultMar
public void onMapReady(GoogleMap
ker(BitmapDescriptorFactory.HUE_GREEN));
googleMap) {
} else if (markerPoints.size() == 2) {
mMap = googleMap;

options.icon(BitmapDescriptorFactory.defaultMar
// Add a marker in Sydney and move the ker(BitmapDescriptorFactory.HUE_RED));
camera
}
LatLng sydney = new LatLng(-34, 151);
mMap.addMarker(new
// Add new marker to the Google Map
MarkerOptions().position(sydney).title("Marker in
Android API V2
Sydney"));
mMap.addMarker(options);
mMap.moveCamera(CameraUpdateFactory.newL
atLngZoom(sydney,16));
// Checks, whether start and end locations
are captured
mMap.setOnMapClickListener(new if (markerPoints.size() >= 2) {
GoogleMap.OnMapClickListener() {
LatLng origin = (LatLng)
@Override markerPoints.get(0);
LatLng dest = (LatLng) }
markerPoints.get(1);

// Getting URL to the Google


protected void onPostExecute(String result) {
Directions API
super.onPostExecute(result);
String url = getDirectionsUrl(origin,
dest);

ParserTask parserTask = new ParserTask();


DownloadTask downloadTask = new
DownloadTask();

parserTask.execute(result);
// Start downloading json data from
Google Directions API
downloadTask.execute(url); }

}
@Override

} protected Object doInBackground(Object[]


objects) {
});
return null;
}
}
}

private class DownloadTask extends AsyncTask


{ private class ParserTask extends
AsyncTask<String, Integer,
List<List<HashMap>>> {

protected String doInBackground(String... // Parsing the data in non-ui thread


url) {
@Override
protected List<List<HashMap>>
String data = ""; doInBackground(String... jsonData) {

try { JSONObject jObject;


data = downloadUrl(url[0]); List<List<HashMap>> routes = null;
} catch (Exception e) {
Log.d("Background Task", e.toString()); try {
} jObject = new
JSONObject(jsonData[0]);
return data;
DirectionsJSONParser parser = new
DirectionsJSONParser();
lineOptions.addAll(points);
lineOptions.width(12);
routes = parser.parse(jObject);
lineOptions.color(Color.RED);
} catch (Exception e) {
lineOptions.geodesic(true);
e.printStackTrace();
}
}
return routes;
}
// Drawing polyline in the Google Map for the i-th
route
@Override mMap.addPolyline(lineOptions);
protected void }
onPostExecute(List<List<HashMap>> result) {
}
ArrayList points = null;
PolylineOptions lineOptions = null;
private String getDirectionsUrl(LatLng origin,
MarkerOptions markerOptions = new LatLng dest) {
MarkerOptions();

// Origin of route
for (int i = 0; i < result.size(); i++) {
String str_origin = "origin=" + origin.latitude
points = new ArrayList(); + "," + origin.longitude;
lineOptions = new PolylineOptions();
// Destination of route
List<HashMap> path = result.get(i); String str_dest = "destination=" + dest.latitude
+ "," + dest.longitude;

for (int j = 0; j < path.size(); j++) {


// Sensor enabled
HashMap point = path.get(j);
String sensor = "sensor=false";
String mode = "mode=driving";
double lat =
Double.parseDouble(point.get("lat"));
double lng = // Building the parameters to the web service
Double.parseDouble(point.get("lng"));
String parameters = str_origin + "&" +
LatLng position = new LatLng(lat, str_dest + "&" + sensor + "&" + mode;
lng);

// Output format
points.add(position);
String output = "json";
}
data = sb.toString();
// Building the url to the web service
String url = br.close();
"https://maps.googleapis.com/maps/api/directions/
" + output + "?" + parameters;
} catch (Exception e) {
Log.d("Exception", e.toString());
} finally {
return url;
iStream.close();
}
urlConnection.disconnect();
}
private String downloadUrl(String strUrl)
throws IOException { return data;
String data = ""; }
InputStream iStream = null; }
HttpURLConnection urlConnection = null;
try { AndroidManifest.xml
URL url = new URL(strUrl);

<?xml version="1.0" encoding="utf-8"?>


urlConnection = (HttpURLConnection) <manifest
url.openConnection(); xmlns:android="http://schemas.android.com/apk/r
es/android"
package="com.example.ex3201">
urlConnection.connect();

<application
iStream = urlConnection.getInputStream();
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
BufferedReader br = new
BufferedReader(new android:label="@string/app_name"
InputStreamReader(iStream));

android:roundIcon="@mipmap/ic_launcher_roun
d"
StringBuffer sb = new StringBuffer();
android:supportsRtl="true"
android:theme="@style/Theme.EX3201">
String line = "";
while ((line = br.readLine()) != null) {
<meta-data
sb.append(line);
}
android:name="com.google.android.geo.API_KE
Y"
android:value="EMPTY" />

<activity
android:name=".MapsActivity"
android:exported="true"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />


</intent-filter>
</activity>
</application>

</manifest>

You might also like