Skip to content Skip to sidebar Skip to footer

How To Get Notified When To Turn Using Google Maps?

In my mobile app on android, user points a place where he wants to go and the path is then generated by google maps. I need to be told by Google Maps that, for example, right now t

Solution 1:

You can get the turn by turn directions from Google, however, the easiest way is to just send the start and end location to google maps and take the user out of your app, into google maps and let that give the turn by turn direction with voice:

publicvoidGoSend(View button) {
    Stringstart="";
    Stringdest="";

    try {
        start = URLEncoder.encode(startAddress, "utf-8");
        dest = URLEncoder.encode(destAddress, "utf-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    Intentintent=newIntent(android.content.Intent.ACTION_VIEW, 
            Uri.parse("http://maps.google.com/maps?saddr=" + start + "&daddr=" + dest));
    intent.setClassName("com.google.android.apps.maps", "com.google.android.maps.MapsActivity");
    startActivity(intent);
  }

Solution 2:

In your Activity

publicfinalstaticStringMODE_DRIVING="driving";
publicfinalstaticStringMODE_TRANSIT="transit";
publicfinalstaticStringMODE_CYCLING="cycling";
publicfinalstaticStringMODE_WALKING="walking";

private ArrayList<SearchItem> directionSteps;
private ArrayList <LatLng> directionPoints;

...
            switch(checkedId) {
            case R.id.btnDriving:
                sMode = GMapV3Direction.MODE_DRIVING;
                 break;
            case R.id.btnTransit:
                sMode = GMapV3Direction.MODE_TRANSIT;
                break;
            case R.id.btnCycling:
                sMode = GMapV3Direction.MODE_CYCLING;
                 break;
            case R.id.btnWalking:
                sMode = GMapV3Direction.MODE_WALKING;
                break;
            }

            findDirectionsAddress(startAddress, destAddress, sMode );
...

@SuppressWarnings("unchecked")publicvoidfindDirectionsAddress(String fromPosition, String toPosition, String mode)
{
    Map<String, String> map = newHashMap<String, String>();
    map.put(GetDirectionsAsyncTask3.USER_CURRENT_ADDRESS, String.valueOf(fromPosition));
    map.put(GetDirectionsAsyncTask3.DESTINATION_ADDRESS, String.valueOf(toPosition));
    map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode);
    map.put(GetDirectionsAsyncTask.DIRECTIONS_LANGUAGE, (String) getResources().getText(R.string.language));

    GetDirectionsAsyncTask3asyncTask=newGetDirectionsAsyncTask3(this);
    asyncTask.execute(map);

    GetDirectionsAsyncTask4asyncTask2=newGetDirectionsAsyncTask4(this);
    asyncTask2.execute(map);

}

// Handle the turn by turn text directionspublicvoidhandleTurnByTurnResult(ArrayList<SearchItem> directionSteps)
{

    this.directionSteps = directionSteps;


    Log.d("Test", "Steps:" + directionSteps.size());
    adapter = newPickListAdapter(this, this.directionSteps);

    setListAdapter(adapter);

}

// Handle the lat/lons of each steppublicvoidhandleGetDirectionsResult(ArrayList<LatLng> directionPoints)
{
    this.directionPoints = directionPoints;

   Configurationconfig= getResources().getConfiguration();

    intwidth= config.screenWidthDp;
    intheight= config.screenHeightDp;

    if (calcPolyline != null) {
        calcPolyline.remove();
    }

    LatLngBounds.Builderbounds=null;
    bounds = newLatLngBounds.Builder(); 
    booleanfoundOne=false;

    bounds.include(currentLatLng);

    if ((theTrip.getStartAddress().getLatitude() != 0.0) && (theTrip.getStartAddress().getLongitude() !=0.0)) {

        bounds.include(newLatLng(theTrip.getStartAddress().getLatitude(), theTrip.getStartAddress().getLongitude()));

    }

    if ((theTrip.getDestinationAddress().getLatitude() != 0.0) && (theTrip.getDestinationAddress().getLongitude() !=0.0)) {

        bounds.include(newLatLng(theTrip.getDestinationAddress().getLatitude(), theTrip.getDestinationAddress().getLongitude()));

    }

    PolylineOptionsrectLine=newPolylineOptions().width(15).color(Color.BLUE);
    for(inti=0 ; i < directionPoints.size() ; i++)
    {
        rectLine.add((LatLng) directionPoints.get(i));
        bounds.include((LatLng) directionPoints.get(i));
        foundOne = true;
    }

    for (SegmentItem item : theTrip.getPathSegments()) {

        pathDynamic = newPolylineOptions().width(20).color(Color.RED);
        pathDynamic.addAll(decode(item.getEncodedPath()));

        for (inti=0; i < pathDynamic.getPoints().size(); i++) {
            LatLngpoint= pathDynamic.getPoints().get(i);
            bounds.include(point);
        }

    }

    if (mMap != null) {
        calcPolyline = mMap.addPolyline(rectLine);
        if (foundOne == true) {
            mMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds.build(), width, height, 40));
        }
    }
}

GMapV3Direction.java

package org.myapp;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.venturacounty.hsamileage.model.SearchItem;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.util.Log;

import com.google.android.gms.maps.model.LatLng;

publicclassGMapV3Direction {
publicfinalstaticStringMODE_DRIVING="driving";
publicfinalstaticStringMODE_TRANSIT="transit";
publicfinalstaticStringMODE_CYCLING="cycling";
publicfinalstaticStringMODE_WALKING="walking";

publicGMapV3Direction() { }

public Document getDocument(String start, String dest, String mode, String language) {

    try {
        start = URLEncoder.encode(start, "utf-8");
        dest = URLEncoder.encode(dest, "utf-8");
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    }

    longmilliseconds= System.currentTimeMillis();
    longseconds= milliseconds/1000;

    Stringurl="https://maps.googleapis.com/maps/api/directions/xml?departure_time="
            + seconds
            + "&origin=" + start
            + "&destination=" + dest
            + "&language=" + language
            + "&sensor=false&mode=" + mode;

    try {
        HttpClienthttpClient=newDefaultHttpClient();
        HttpContextlocalContext=newBasicHttpContext();
        HttpPosthttpPost=newHttpPost(url);
        HttpResponseresponse= httpClient.execute(httpPost, localContext);
        InputStreamin= response.getEntity().getContent();
        DocumentBuilderbuilder= DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Documentdoc= builder.parse(in);
        return doc;
    } catch (Exception e) {
        e.printStackTrace();
    }
    returnnull;
}

public String getDurationText(Document doc) {
    NodeListnl1= doc.getElementsByTagName("duration");
    Nodenode1= nl1.item(0);
    NodeListnl2= node1.getChildNodes();
    Nodenode2= nl2.item(getNodeIndex(nl2, "text"));
    Log.i("DurationText", node2.getTextContent());
    return node2.getTextContent();
}

publicintgetDurationValue(Document doc) {
    NodeListnl1= doc.getElementsByTagName("duration");
    Nodenode1= nl1.item(0);
    NodeListnl2= node1.getChildNodes();
    Nodenode2= nl2.item(getNodeIndex(nl2, "value"));
    Log.i("DurationValue", node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
}

public String getDistanceText(Document doc) {
    NodeListnl1= doc.getElementsByTagName("distance");
    Nodenode1= nl1.item(0);
    NodeListnl2= node1.getChildNodes();
    Nodenode2= nl2.item(getNodeIndex(nl2, "text"));
    Log.i("DistanceText", node2.getTextContent());
    return node2.getTextContent();
}

publicintgetDistanceValue(Document doc) {
    NodeListnl1= doc.getElementsByTagName("distance");
    Nodenode1= nl1.item(0);
    NodeListnl2= node1.getChildNodes();
    Nodenode2= nl2.item(getNodeIndex(nl2, "value"));
    Log.i("DistanceValue", node2.getTextContent());
    return Integer.parseInt(node2.getTextContent());
}

public String getStartAddress(Document doc) {
    NodeListnl1= doc.getElementsByTagName("start_address");
    Nodenode1= nl1.item(0);
    Log.i("StartAddress", node1.getTextContent());
    return node1.getTextContent();
}

public String getEndAddress(Document doc) {
    NodeListnl1= doc.getElementsByTagName("end_address");
    Nodenode1= nl1.item(0);
    Log.i("StartAddress", node1.getTextContent());
    return node1.getTextContent();
}

public String getCopyRights(Document doc) {
    NodeListnl1= doc.getElementsByTagName("copyrights");
    Nodenode1= nl1.item(0);
    Log.i("CopyRights", node1.getTextContent());
    return node1.getTextContent();
}

public ArrayList<SearchItem> getTurnByTurn(Document doc) {
    NodeList nl1, nl2, nl3;
    ArrayList<SearchItem> listDirections = newArrayList<SearchItem>();
    nl1 = doc.getElementsByTagName("step");
    if (nl1.getLength() > 0) {
        for (inti=0; i < nl1.getLength(); i++) {
            Nodenode1= nl1.item(i);
            nl2 = node1.getChildNodes();

            NodedistanceNode= nl2.item(getNodeIndex(nl2, "distance"));
            nl3 = distanceNode.getChildNodes();
            NodetextNode= nl3.item(getNodeIndex(nl3, "text"));
            Stringdistance= textNode.getTextContent();

            NodedurationNode= nl2.item(getNodeIndex(nl2, "duration"));
            nl3 = durationNode.getChildNodes();
            textNode = nl3.item(getNodeIndex(nl3, "text"));
            Stringduration= textNode.getTextContent();

            NodeinstructionsNode= nl2.item(getNodeIndex(nl2, "html_instructions"));
            Stringinstructions= instructionsNode.getTextContent();
            Stringdetails= distance + " -- " + duration;


            listDirections.add(newSearchItem(instructions, details, "", false));
        }
    }

    return listDirections;
}


public ArrayList<LatLng> getDirection(Document doc) {
    NodeList nl1, nl2, nl3;
    ArrayList<LatLng> listGeopoints = newArrayList<LatLng>();
    nl1 = doc.getElementsByTagName("step");
    if (nl1.getLength() > 0) {
        for (inti=0; i < nl1.getLength(); i++) {
            Nodenode1= nl1.item(i);
            nl2 = node1.getChildNodes();

            NodelocationNode= nl2.item(getNodeIndex(nl2, "start_location"));
            nl3 = locationNode.getChildNodes();
            NodelatNode= nl3.item(getNodeIndex(nl3, "lat"));
            doublelat= Double.parseDouble(latNode.getTextContent());
            NodelngNode= nl3.item(getNodeIndex(nl3, "lng"));
            doublelng= Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(newLatLng(lat, lng));

            locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "points"));
            ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
            for(intj=0 ; j < arr.size() ; j++) {
                LatLngitem= (LatLng) arr.get(j);
                listGeopoints.add(newLatLng(item.latitude, item.longitude));
            }

            locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
            nl3 = locationNode.getChildNodes();
            latNode = nl3.item(getNodeIndex(nl3, "lat"));
            lat = Double.parseDouble(latNode.getTextContent());
            lngNode = nl3.item(getNodeIndex(nl3, "lng"));
            lng = Double.parseDouble(lngNode.getTextContent());
            listGeopoints.add(newLatLng(lat, lng));
        }
    }

    return listGeopoints;
}

privateintgetNodeIndex(NodeList nl, String nodename) {
    for(inti=0 ; i < nl.getLength() ; i++) {
        if(nl.item(i).getNodeName().equals(nodename))
            return i;
    }
    return -1;
}

private ArrayList<LatLng> decodePoly(String encoded) {
    ArrayList<LatLng> poly = newArrayList<LatLng>();
    intindex=0, len = encoded.length();
    intlat=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);
        intdlat= ((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);
        intdlng= ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
        lng += dlng;

        LatLngposition=newLatLng((double) lat / 1E5, (double) lng / 1E5);
        poly.add(position);
    }
    return poly;
}
}

GetDirectionAsyncTask.java

package org.myapp;

import java.util.ArrayList;
import java.util.Map;

import org.myapp.model.SearchItem;
import org.w3c.dom.Document;

import com.google.android.gms.maps.model.LatLng;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.Toast;

publicclassGetDirectionsAsyncTaskextendsAsyncTask<Map<String, String>, Object, ArrayList<SearchItem>>
{
publicstaticfinalStringUSER_CURRENT_LAT="user_current_lat";
publicstaticfinalStringUSER_CURRENT_LONG="user_current_long";
publicstaticfinalStringDESTINATION_LAT="destination_lat";
publicstaticfinalStringDESTINATION_LONG="destination_long";
publicstaticfinalStringDIRECTIONS_MODE="directions_mode";
publicstaticfinalStringDIRECTIONS_LANGUAGE="directions_language";
private PickerActivity activity;
private Exception exception;
private ProgressDialog progressDialog;

publicGetDirectionsAsyncTask(PickerActivity pickerActivity)
{
    super();
    this.activity = pickerActivity;
}

publicvoidonPreExecute()
{
    progressDialog = newProgressDialog(activity);
    progressDialog.setTitle((String) this.activity.getResources().getText(R.string.directions));
    progressDialog.setMessage((String) this.activity.getResources().getText(R.string.calculating_directions));
    progressDialog.show();
}

publicvoidonPostExecute(ArrayList<SearchItem> result)
{
    progressDialog.dismiss();
    if (exception == null)
    {
     // activity.handleGetDirectionsResult(result);
        activity.handleTurnByTurnResult(result);
    }
    else
    {
        processException();
    }
}

@Overrideprotected ArrayList<SearchItem> doInBackground(Map<String, String>... params)
{
    Map<String, String> paramMap = params[0];
    try
    {
        LatLngfromPosition=newLatLng(Double.valueOf(paramMap.get(USER_CURRENT_LAT)) , Double.valueOf(paramMap.get(USER_CURRENT_LONG)));
        LatLngtoPosition=newLatLng(Double.valueOf(paramMap.get(DESTINATION_LAT)) , Double.valueOf(paramMap.get(DESTINATION_LONG)));
        StringsMode= paramMap.get(DIRECTIONS_MODE);
        StringsLanguage= paramMap.get(DIRECTIONS_LANGUAGE);
        GMapV2Directionmd=newGMapV2Direction();
        Documentdoc= md.getDocument(fromPosition, toPosition, sMode, sLanguage);
        // ArrayList directionPoints = md.getDirection(doc);
        ArrayList<SearchItem> directionSteps = md.getTurnByTurn(doc);
        return directionSteps;
    }
    catch (Exception e)
    {
        exception = e;
        returnnull;
    }
}

privatevoidprocessException()
{
    Toast.makeText(activity, activity.getString(R.string.error_when_retrieving_data), Toast.LENGTH_SHORT).show();
}
}

GetDirectionsAsyncTask3.java

package org.myapp;

import java.util.ArrayList;
import java.util.Map;

import org.myapp.model.SearchItem;
import org.w3c.dom.Document;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

publicclassGetDirectionsAsyncTask3extendsAsyncTask<Map<String, String>, Object, ArrayList<SearchItem>>
{
publicstaticfinalStringUSER_CURRENT_ADDRESS="user_current_address";
publicstaticfinalStringDESTINATION_ADDRESS="destination_address";
publicstaticfinalStringDIRECTIONS_MODE="directions_mode";
publicstaticfinalStringDIRECTIONS_LANGUAGE="directions_language";
private PickerActivity activity;
private Exception exception;

publicGetDirectionsAsyncTask3(PickerActivity pickerActivity)
{
    super();
    this.activity = pickerActivity;
}

publicvoidonPreExecute()
{
 }

publicvoidonPostExecute(ArrayList<SearchItem> result)
{
    if (exception == null)
    {
        // Task4 handles direction points// activity.handleGetDirectionsResult(result);// Task3 handles direction text steps
        activity.handleTurnByTurnResult(result);
    }
    else
    {
        processException();
    }
}

@Overrideprotected ArrayList<SearchItem> doInBackground(Map<String, String>... params)
{
    Map<String, String> paramMap = params[0];
    try
    {
        StringfromPosition= paramMap.get(USER_CURRENT_ADDRESS);
        StringtoPosition= paramMap.get(DESTINATION_ADDRESS);
        Stringmode= paramMap.get(DIRECTIONS_MODE);
        StringsLanguage= paramMap.get(DIRECTIONS_LANGUAGE);
        GMapV3Directionmd=newGMapV3Direction();

        Documentdoc= md.getDocument(fromPosition, toPosition, mode, sLanguage);
        // Task4 handles direction points// ArrayList directionPoints = md.getDirection(doc);// Task3 handles direction steps
        ArrayList<SearchItem> directionSteps = md.getTurnByTurn(doc);
        return directionSteps;
    }
    catch (Exception e)
    {
        exception = e;
        returnnull;
    }
}

privatevoidprocessException()
{
    Toast.makeText(activity, activity.getString(R.string.error_when_retrieving_data), Toast.LENGTH_SHORT).show();
}
}

GetDirectionsAsyncTask4.java

package org.myapp;

import java.util.ArrayList;
import java.util.Map;

import org.w3c.dom.Document;

import com.google.android.gms.maps.model.LatLng;

import android.os.AsyncTask;
import android.widget.Toast;

publicclassGetDirectionsAsyncTask4extendsAsyncTask<Map<String, String>, Object, ArrayList<LatLng>>
{
publicstaticfinalStringUSER_CURRENT_ADDRESS="user_current_address";
publicstaticfinalStringDESTINATION_ADDRESS="destination_address";
publicstaticfinalStringDIRECTIONS_MODE="directions_mode";
publicstaticfinalStringDIRECTIONS_LANGUAGE="directions_language";
private PickerActivity activity;
private Exception exception;

publicGetDirectionsAsyncTask4(PickerActivity pickerActivity)
{
    super();
    this.activity = pickerActivity;
}

publicvoidonPreExecute()
{
}

publicvoidonPostExecute(ArrayList<LatLng> result)
{
    if (exception == null)
    {
    // Task4 handles the directions points
        activity.handleGetDirectionsResult(result);

    // Task3 handles the directions text results// activity.handleTurnByTurnResult(result);
    }
    else
    {
        processException();
    }
}

@Overrideprotected ArrayList<LatLng> doInBackground(Map<String, String>... params)
{
    Map<String, String> paramMap = params[0];
    try
    {
        StringfromPosition= paramMap.get(USER_CURRENT_ADDRESS);
        StringtoPosition= paramMap.get(DESTINATION_ADDRESS);
        Stringmode= paramMap.get(DIRECTIONS_MODE);
        StringsLanguage= paramMap.get(DIRECTIONS_LANGUAGE);
        GMapV3Directionmd=newGMapV3Direction();
        Documentdoc= md.getDocument(fromPosition, toPosition, mode, sLanguage);

        // Task4 handles the directions points
        ArrayList<LatLng> directionPoints = md.getDirection(doc);

        // Task3 handles the directions text results// ArrayList directionSteps = md.getTurnByTurn(doc);return directionPoints;
    }
    catch (Exception e)
    {
        exception = e;
        returnnull;
    }
}

privatevoidprocessException()
{
    Toast.makeText(activity, activity.getString(R.string.error_when_retrieving_data), Toast.LENGTH_SHORT).show();
}
}

Solution 3:

Its pretty simple.

When you select the destination and the path is generated, there are 3 basic icons that appears on the right hand side: The Compass, The Search and The Speaker icon.

You have to make sure you set the speakers to Unmuted once you do that you will get the all notification about the journey, Like which route to stay on, left/Right Directions and the distance for the next action.

image 1

If you keep it mute you will not receive any audio notification

image 2

and if you select alert only then it will only alert you about important notifications, Like Left, right , U-Turn , Taking Service Roads Etc.

image 3

And Above all this you have to make sure your is active for Notification under sound settings. (differs from device to device)

Hope this details help you.

Solution 4:

First of all you should be aware that Google Maps Platform Terms of Service have certain restrictions regarding creation of real-time or turn-by-turn navigation. Basically, you are not allowed to create such functionality in you app.

Have a look at section 3.2.4 'Restrictions Against Misusing the Services' of ToS. In paragraph (c) you will find the following

No Re-Creating Google Products or Features. Customer will not use the Services to create a product or service with features that are substantially similar to or that re-create the features of another Google product or service...

For example, Customer will not: ...

(iv) combine data from the Directions API, Geolocation API, and Maps SDK for Android to create real-time navigation functionality substantially similar to the functionality provided by the Google Maps for Android mobile app.

source: https://cloud.google.com/maps-platform/terms/#3-license

That means that the only allowed option according to the ToS is redirect your users to Google Maps app where they can use navigation mode.

You should create an intent that opens the Google Maps native app in navigation mode. There is a Google Maps URLs that allows to construct a universal, cross-platform URL to launch Google Maps intents from your application. You can open navigation mode of native app following this documentation:

https://developers.google.com/maps/documentation/urls/guide#directions-action

Code snapshot might be

Stringurl="https://www.google.com/maps/dir/?api=1&destination=Madrid,Spain&origin=Barcelona,Spain&waypoints=Zaragoza|Huesca&travelmode=driving&dir_action=navigate";           
Intentintent=newIntent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent); 

Hope this helps!

Post a Comment for "How To Get Notified When To Turn Using Google Maps?"