tomislav-b
7/3/2014 - 6:47 PM

Code used to start the Maps app to navigate the user to the provided coordinates. There are also method used to alert the user if GPS isn't

Code used to start the Maps app to navigate the user to the provided coordinates.

There are also method used to alert the user if GPS isn't active and to raise a toast if the current location couldn't be found out of some reason.

package com.blazeka.util;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.widget.Toast;

public class Utils {
	public static void navigate(Context c, String destinationLat,
			String destinationLon) {
		String currentCoordinates = getCurrentCoordiantes(c);
		if (currentCoordinates == null)
			return; // Return if GPS isn't active

		Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
				Uri.parse("http://maps.google.com/maps?saddr="
						+ currentCoordinates + "&daddr=" + destinationLat + ","
						+ destinationLon));
		c.startActivity(intent);
	}

	private static String getCurrentCoordiantes(Context c) {
		LocationManager locationManager = (LocationManager) c
				.getSystemService(Context.LOCATION_SERVICE);

		// Check if GPS is active and call buildAlertMessageNoGps if that's not
		// the case
		if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			buildAlertMessageNoGps(c);
			return null;
		}

		Criteria criteria = new Criteria();
		String bestProvider = locationManager.getBestProvider(criteria, false);
		Location location = locationManager.getLastKnownLocation(bestProvider);

		double lat = -1, lon = -1;

		try {
			lat = location.getLatitude();
			lon = location.getLongitude();
		} catch (NullPointerException e) {
			gpsFailAlert(c);
		}

		return lat + "," + lon;
	}

	// Create a dialog that asks the user to activate his GPS
	// Redirects the user to system settings if he accepts
	public static void buildAlertMessageNoGps(final Context c) {
		String message = c.getString(R.string.alert_gps_off);

		final AlertDialog.Builder builder = new AlertDialog.Builder(c);
		builder.setMessage(message)
				.setCancelable(false)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								c.startActivity(new Intent(
										android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					public void onClick(final DialogInterface dialog,
							final int id) {
						dialog.cancel();
					}
				});
		final AlertDialog alert = builder.create();
		alert.show();
	}

	public static void gpsFailAlert(Context c) {
		Toast.makeText(c, R.string.alert_gps_fail, Toast.LENGTH_SHORT).show();
	}
}