0% found this document useful (0 votes)
9 views3 pages

Draw Route Between Locations in Android

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)
9 views3 pages

Draw Route Between Locations in Android

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

Practical 32

Q1) Write a program to draw a route between two locations.


XML CODE:

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


<LinearLayout xmlns:android="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<fragment
android:id="@+id/mapNearBy"
android:name="[Link]"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_below="@+id/rvToolbar"
android:layout_weight="1" />

<Button
android:id="@+id/btnGetDirection"
android:text="Get Direction"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/selectableItemBackground" />
</LinearLayout>

JAVA CODE:

package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

/**
* Created by Vishal on 10/20/2018.
*/

public class MapActivity extends AppCompatActivity implements OnMapReadyCallback,


TaskLoadedCallback {
private GoogleMap mMap;
private MarkerOptions place1, place2;
Button getDirection;
private Polyline currentPolyline;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].map_activity);
getDirection = findViewById([Link]);
[Link](new [Link]() {
@Override
public void onClick(View view) {
new FetchURL([Link]).execute(getUrl([Link](), [Link](),
"driving"), "driving");
}
});
//27.658143,85.3199503
//27.667491,85.3208583
place1 = new MarkerOptions().position(new LatLng(27.658143, 85.3199503)).title("Location 1");
place2 = new MarkerOptions().position(new LatLng(27.667491, 85.3208583)).title("Location 2");
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById([Link]);
[Link](this);
}

@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.d("mylog", "Added Markers");
[Link](place1);
[Link](place2);
}

private String getUrl(LatLng origin, LatLng dest, String directionMode) {


// Origin of route
String str_origin = "origin=" + [Link] + "," + [Link];
// Destination of route
String str_dest = "destination=" + [Link] + "," + [Link];
// Mode
String mode = "mode=" + directionMode;
// Building the parameters to the web service
String parameters = str_origin + "&" + str_dest + "&" + mode;
// Output format
String output = "json";
// Building the url to the web service
String url = "[Link] + output + "?" + parameters +
"&key=" + getString([Link].google_maps_key);
return url;
}

@Override
public void onTaskDone(Object... values) {
if (currentPolyline != null)
[Link]();
currentPolyline = [Link]((PolylineOptions) values[0]);
}
}

MANIFEST FILE:
<manifest xmlns:android="[Link]
package="[Link]">

<uses-permission android:name="[Link]" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<meta-data
android:name="[Link]"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="[Link].API_KEY"
android:value="@string/google_maps_key" />

<activity android:name=".MapActivity">
<intent-filter>
<category android:name="[Link]" />
<action android:name="[Link]" />
</intent-filter>
</activity>
</application>
</manifest>

Common questions

Powered by AI

The 'getUrl' method constructs the URL required to interact with the Google Directions API by concatenating the route origin, destination, and mode parameters along with the API key. This URL is used to fetch route data. The method ensures all necessary data align with the API's requirements, facilitating accurate and seamless data retrieval and integration for route directions .

The imports such as 'android.support.v7.app.AppCompatActivity' from the legacy Android support libraries may lead to compatibility issues as newer versions of Android and AndroidX libraries are adopted. These challenges can be addressed by migrating to AndroidX libraries which are the recommended library support set by Google, offering enhanced features and better maintenance .

The MapActivity implements the 'OnMapReadyCallback' interface to handle the asynchronous nature of map rendering. When the map is ready to be used, the 'onMapReady' method is called. This method is essential for initializing the GoogleMap object to add markers and configure map settings, ensuring that any operations depending on the map being ready, such as adding markers or drawing routes, are performed after this callback is invoked .

Storing the API key directly in the application’s manifest file poses a security risk because it's easily accessible through reverse engineering, potentially exposing it to unauthorized use. Best practices suggest storing the key securely, for example using remote server calls where the key isn’t exposed in the client-side application, or utilizing encrypted configurations and calls to limit unauthorized access to your API quota and functionalities .

The design places emphasis on rendering the map as the primary focus by setting it as a fragment with significant layout weight, ensuring it occupies most of the screen for clear visibility. The 'Get Direction' button is placed strategically below the map for quick access, thus streamlining user interaction. This design prioritizes ease of use and intuitive navigation, improving the overall user experience .

The app's dependency on internet access, due to its reliance on the Google Maps API and directions fetching, limits usability offline. To mitigate this, options such as pre-downloading map data and caching directions for areas of interest, using fallback options like offline preferences storage, or integrating additional tools that offer offline map functionalities can be employed to maintain usability .

The LinearLayout in the XML layout code organizes the layout's components vertically, allowing the fragment (MapFragment) that displays the map and a Button for getting directions to be placed on top of each other. This provides a structured way to manage the UI elements that correspond to map interaction and user control .

Drawing complex routes with multiple stops can significantly increase the app's processing load as each additional waypoint adds complexity to the route calculation and display process. This could potentially slow down response times, increase latency, or even exceed API query limits, impacting user experience. To optimize, batching requests, simplifying paths visually, caching results, and performing background operations can alleviate performance degradation .

The app uses the FetchURL class to execute a network call to the Google Directions API with specified parameters, including origin and destination coordinates along with the travel mode (driving). The 'execute' method in FetchURL initiates this call. Upon receiving the response, the TaskLoadedCallback interface's 'onTaskDone' method processes the resultant data, which contains polyline points, and these points are used to draw the route by adding them as a Polyline to the GoogleMap object .

Handling user location data necessitates strict adherence to privacy regulations like GDPR or CCPA. It involves only collecting necessary data, ensuring data anonymization, securing transmission via encryption, and providing clear terms of use. Users should have control over their data, the option to opt-in, and the ability to revoke permissions at will. Transparency about data usage and retention policies must be communicated to build trust .

You might also like