2

I started with this example, to draw a route between 2 address, type by the user. It is working. http://blog.rolandl.fr/1357-android-des-itineraires-dans-vos-applications-grace-a-lapi-google-direction

But now I would like to draw a route from my current position to an other destination, type by the user. My problem is that I don't know how to retrieve the current position, in this case. I've tried to do :

LocationManager locationmanager=(LocationManager)this.getSystemService(LOCATION_SERVICE);
final double longitude=locationmanager.getLongitude();
final double latitude=locationmanager.getLatitude();

But it will not work... I think I am mixing every example I've found, and it is not good at all.

Can you please help me ?

Here is my MapActivity : Receiving 2 address typed by the user in my MainActivity public class MapActivity extends Activity implements LocationListener { private GoogleMap googlemap;

    protected void onCreate(final Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);

        // Recuperation des composants graphiques
        googlemap = ((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();

        //Recuperations des adresses depart-arrivee
        // RETRIEVE DEPARTURE AND DESTINATION ADDRESS
        /*
         * For editDepart, I would like to replace it by my Current location
         */
        final String editDepart = getIntent().getStringExtra("DEPART");
        final String editArrivee = getIntent().getStringExtra("ARRIVEE");       

        /* Appel de la méthode asynchrone // ASYNCHRONOUS METHOD
         * ATTENTION : Il faut que ItineraireTask soit extends AsyncTask<Void, Integer, Boolean>
         * Sinon, on ne pourra pas utilise la methode execute() */
        new ItineraireTask(this, googlemap, editDepart, editArrivee).execute();

    }
}

Here is my ItineraireTask :

    public class ItineraireTask extends AsyncTask<Void, Integer, Boolean> 
{
    private static final String TOAST_MSG = "Calcul de l'itinéraire en cours";
    private static final String TOAST_ERR_MAJ = "Impossible de trouver un itinéraire";

    private Context context;
    private GoogleMap gMap;
    private String editDepart;
    private String editArrivee;
    private final ArrayList<LatLng> lstLatLng = new ArrayList<LatLng>();

    /** CONSTRUCTEUR **/
    public ItineraireTask(final Context context, final GoogleMap gMap, final String editDepart, final String editArrivee) 
    {
        this.context = context;
        this.gMap= gMap;
        this.editDepart = editDepart;
        this.editArrivee = editArrivee;
    }    

    protected void onPreExecute() 
    {
        Toast.makeText(context, TOAST_MSG, Toast.LENGTH_LONG).show();
    }

    protected Boolean doInBackground(Void... params) 
    {
        try 
        {
            //Construction de l'url à appeler          
            final StringBuilder url = new StringBuilder("http://maps.googleapis.com/maps/api/directions/xml?sensor=false&language=fr");
            url.append("&origin=");
            url.append(editDepart.replace(' ', '+'));
            url.append("&destination=");
            url.append(editArrivee.replace(' ', '+'));

            //Appel du web service
            final InputStream stream = new URL(url.toString()).openStream();

            //Traitement des données
            final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            documentBuilderFactory.setIgnoringComments(true);

            final DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

            final Document document = documentBuilder.parse(stream);
            document.getDocumentElement().normalize();

            //On récupère d'abord le status de la requête
            final String status = document.getElementsByTagName("status").item(0).getTextContent();
            if(!"OK".equals(status)) 
            {
                return false;
            }

            //On récupère les steps
            final Element elementLeg = (Element) document.getElementsByTagName("leg").item(0);
            final NodeList nodeListStep = elementLeg.getElementsByTagName("step");
            final int length = nodeListStep.getLength();

            for(int i=0; i<length; i++) 
            {       
            final Node nodeStep = nodeListStep.item(i); 
                if(nodeStep.getNodeType() == Node.ELEMENT_NODE) 
                {
                    final Element elementStep = (Element) nodeStep;

                    //On décode les points du XML
                    decodePolylines(elementStep.getElementsByTagName("points").item(0).getTextContent());
                }
            }
            return true;           
        }
        catch(final Exception e) 
        {
            return false;
        }
    }


    /** METHODE QUI DECODE LES POINTS EN LAT-LONG**/
    private void decodePolylines(final String encodedPoints) 
    {
        int index = 0;
        int lat = 0, lng = 0;

        while (index < encodedPoints.length()) 
        {
            int b, shift = 0, result = 0;

            do 
            {
                b = encodedPoints.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 = encodedPoints.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);

            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng; 
            lstLatLng.add(new LatLng((double)lat/1E5, (double)lng/1E5));
        }
    }


    protected void onPostExecute(final Boolean result) 
    {   
        if(!result) 
        {
            Toast.makeText(context, TOAST_ERR_MAJ, Toast.LENGTH_SHORT).show();
        }
        else 
        {
            //On déclare le polyline, c'est-à-dire le trait (ici bleu) que l'on ajoute sur la carte pour tracer l'itinéraire
            final PolylineOptions polylines = new PolylineOptions();
            polylines.color(Color.BLUE);

            //On construit le polyline
            for(final LatLng latLng : lstLatLng)
            {
                polylines.add(latLng);
            }        
            //On déclare un marker vert que l'on placera sur le départ
            final MarkerOptions markerA = new MarkerOptions();
            markerA.position(lstLatLng.get(0));
            markerA.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));

            //On déclare un marker rouge que l'on mettra sur l'arrivée
            final MarkerOptions markerB = new MarkerOptions();
            markerB.position(lstLatLng.get(lstLatLng.size()-1));
            markerB.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));

            //On met à jour la carte
            gMap.moveCamera(CameraUpdateFactory.newLatLngZoom(lstLatLng.get(0), 10));
            gMap.addMarker(markerA);
            gMap.addPolyline(polylines);
            gMap.addMarker(markerB);
        }
    }
}

Thanks to you in advance !

Best regards,

Tofuw

Tofuw
  • 908
  • 5
  • 16
  • 35
  • 1
    you should probably read about how to get your current location http://developer.android.com/training/location/index.html – tyczj Dec 02 '13 at 16:16

1 Answers1

5

Here is a blog post I wrote on this topic and that can help you with this one:

Google Maps API V2 Draw Directions

There is a sample project that you can download and use.

Emil Adz
  • 40,709
  • 36
  • 140
  • 187
  • or you can use my library I made based off @EminAdz blog post https://github.com/tyczj/MapNavigator this does not really answer his question though i guess since he does not know how to get his current location – tyczj Dec 02 '13 at 16:15
  • Hello @Emil Adz, I've just tried your application, and it works :) But I have to put `` in the Manifest, or it will crash. But it is not really what I am searching for. Thanks to you anyway ! – Tofuw Dec 04 '13 at 08:43
  • yes you should do that, and it's mentioned in one of my other posts. – Emil Adz Dec 04 '13 at 08:53
  • Hi @tyczj ! Thanks for your help. I was trying little by little different methods. Now, I'll try yours. So to use your library, I just have to implement my fragment with OnPathSetListner, and instanciate `GoogleMap map = getMap(); Navigator nav = new Navigator(map,start,end); nav.findDirections(true, false);` Like my english is not fluent, I'd like to be sure on asking you a confirmation. In advance, thank you ! – Tofuw Dec 05 '13 at 08:12
  • @Tofuw yes that will get you the directions from one point to another and plot them on the map but if you need tour current location it will not help you with that, you need to look at hot to implement a location manager correctly – tyczj Dec 05 '13 at 13:13