How to find the way between two markers on Android?

1

I have two Markers placed on the map. I would like to insert a route between them. How can I do this?

//Nometodoondeimplementoosmarkerstenhoosegunintecodigo//TenhoabaixooprimeiroMakerimplementadoMarkerm_person=mMap.addMarker(newMarkerOptions().position(newLatLng(Float.parseFloat(cristao_latitude),Float.parseFloat(cristao_longitude))).title("Tua Ultima Localização\n"+gestao_datas.dia(time)+","+gestao_datas.mes_nome(time)).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)));
m_person.showInfoWindow();

//Agora tenho o segundo matker implementado       
Marker marker= mMap.addMarker(new MarkerOptions().position(new LatLng(Float.parseFloat(latitude), Float.parseFloat(longitude))).title(nome));

marker.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Float.parseFloat(latitude), Float.parseFloat(longitude)), 10));
    
asked by anonymous 31.07.2015 / 08:54

2 answers

1

If you want to draw a route between them use Polyline. Google has API for this, follow the links to studies:

link

link

    
31.07.2015 / 19:36
1

Thanks, I was able to implement the above links using Polyline and google api.

I had to create two classes the first one was to have the coordinates and through AsynkTask and the internet and get some coordinates to later mark using Polyline * GMapV2Direction (Configures the methods that will get the coordinates) * GetDirectionsAsyncTask (Class that uses ASynkTask, using methods of the previous class) * MapsActivity (Map Class) // Start of class GMapV2Direction

package gabrielfm.com.findyouchurch.Dados;
import java.io.InputStream;
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.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

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

import android.util.Log;

public class GMapV2Direction {
    public final static String MODE_DRIVING = "driving";
    public final static String MODE_WALKING = "walking";

    public GMapV2Direction() {
    }

    public Document getDocument(LatLng start, LatLng end, String mode) {
        String url = "http://maps.googleapis.com/maps/api/directions/xml?"
                + "origin=" + start.latitude + "," + start.longitude
                + "&destination=" + end.latitude + "," + end.longitude
                + "&sensor=false&units=metric&mode=driving";
        Log.d("url", url);
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse response = httpClient.execute(httpPost, localContext);
            InputStream in = response.getEntity().getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance()
                    .newDocumentBuilder();
            Document doc = builder.parse(in);
            return doc;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getDurationText(Document doc) {
        try {

            NodeList nl1 = doc.getElementsByTagName("duration");
            Node node1 = nl1.item(0);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "text"));
            Log.i("DurationText", node2.getTextContent());
            return node2.getTextContent();
        } catch (Exception e) {
            return "0";
        }
    }

    public int getDurationValue(Document doc) {
        try {
            NodeList nl1 = doc.getElementsByTagName("duration");
            Node node1 = nl1.item(0);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            Log.i("DurationValue", node2.getTextContent());
            return Integer.parseInt(node2.getTextContent());
        } catch (Exception e) {
            return -1;
        }
    }

    public String getDistanceText(Document doc) {
		/*
		 * while (en.hasMoreElements()) { type type = (type) en.nextElement();
		 *
		 * }
		 */

        try {
            NodeList nl1;
            nl1 = doc.getElementsByTagName("distance");

            Node node1 = nl1.item(nl1.getLength() - 1);
            NodeList nl2 = null;
            nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            Log.d("DistanceText", node2.getTextContent());
            return node2.getTextContent();
        } catch (Exception e) {
            return "-1";
        }

		/*
		 * NodeList nl1; if(doc.getElementsByTagName("distance")!=null){ nl1=
		 * doc.getElementsByTagName("distance");
		 *
		 * Node node1 = nl1.item(nl1.getLength() - 1); NodeList nl2 = null; if
		 * (node1.getChildNodes() != null) { nl2 = node1.getChildNodes(); Node
		 * node2 = nl2.item(getNodeIndex(nl2, "value")); Log.d("DistanceText",
		 * node2.getTextContent()); return node2.getTextContent(); } else return
		 * "-1";} else return "-1";
		 */
    }

    public int getDistanceValue(Document doc) {
        try {
            NodeList nl1 = doc.getElementsByTagName("distance");
            Node node1 = null;
            node1 = nl1.item(nl1.getLength() - 1);
            NodeList nl2 = node1.getChildNodes();
            Node node2 = nl2.item(getNodeIndex(nl2, "value"));
            Log.i("DistanceValue", node2.getTextContent());
            return Integer.parseInt(node2.getTextContent());
        } catch (Exception e) {
            return -1;
        }
		/*
		 * NodeList nl1 = doc.getElementsByTagName("distance"); Node node1 =
		 * null; if (nl1.getLength() > 0) node1 = nl1.item(nl1.getLength() - 1);
		 * if (node1 != null) { NodeList nl2 = node1.getChildNodes(); Node node2
		 * = nl2.item(getNodeIndex(nl2, "value")); Log.i("DistanceValue",
		 * node2.getTextContent()); return
		 * Integer.parseInt(node2.getTextContent()); } else return 0;
		 */
    }

    public String getStartAddress(Document doc) {
        try {
            NodeList nl1 = doc.getElementsByTagName("start_address");
            Node node1 = nl1.item(0);
            Log.i("StartAddress", node1.getTextContent());
            return node1.getTextContent();
        } catch (Exception e) {
            return "-1";
        }

    }

    public String getEndAddress(Document doc) {
        try {
            NodeList nl1 = doc.getElementsByTagName("end_address");
            Node node1 = nl1.item(0);
            Log.i("StartAddress", node1.getTextContent());
            return node1.getTextContent();
        } catch (Exception e) {
            return "-1";
        }
    }

    public String getCopyRights(Document doc) {
        try {
            NodeList nl1 = doc.getElementsByTagName("copyrights");
            Node node1 = nl1.item(0);
            Log.i("CopyRights", node1.getTextContent());
            return node1.getTextContent();
        } catch (Exception e) {
            return "-1";
        }

    }

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

                Node locationNode = nl2
                        .item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));

                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));
                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
                for (int j = 0; j < arr.size(); j++) {
                    listGeopoints.add(new LatLng(arr.get(j).latitude, arr
                            .get(j).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(new LatLng(lat, lng));
            }
        }

        return listGeopoints;
    }

    private int getNodeIndex(NodeList nl, String nodename) {
        for (int i = 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 = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 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);
            int dlat = ((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);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            LatLng position = new LatLng(lat / 1E5, lng / 1E5);
            poly.add(position);
        }
        return poly;
    }
}

// Start class GMapV2Direction

package gabrielfm.com.findyouchurch.Dados;

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

import org.w3c.dom.Document;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.widget.Toast;

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

import gabrielfm.com.findyouchurch.Activitys.MapsActivity;

public class GetDirectionsAsyncTask extends AsyncTask<Map<String, String>, Object, ArrayList>
{
    public static final String USER_CURRENT_LAT = "user_current_lat";
    public static final String USER_CURRENT_LONG = "user_current_long";
    public static final String DESTINATION_LAT = "destination_lat";
    public static final String DESTINATION_LONG = "destination_long";
    public static final String DIRECTIONS_MODE = "directions_mode";
    private ActionBarActivity activity;
    private Exception exception;
    private ProgressDialog progressDialog;

    public GetDirectionsAsyncTask(ActionBarActivity activity)
    {
        super();
        this.activity = activity;
    }

    public void onPreExecute()
    {
        progressDialog = new ProgressDialog(activity);
        progressDialog.setMessage("Calculating directions");
        progressDialog.show();
    }

    @Override
    public void onPostExecute(ArrayList result)
    {
        progressDialog.dismiss();
        if (exception == null)
        {

            MapsActivity m=(MapsActivity)activity;
           // map M = (map)activity;
            m.handleGetDirectionsResult(result);
        }
        else
        {
            processException();
        }
    }

    @Override
    protected ArrayList doInBackground(Map<String, String>... params)
    {
        Map<String, String> paramMap = params[0];
        try
        {
            LatLng fromPosition = new LatLng(Double.valueOf(paramMap.get(USER_CURRENT_LAT)) , Double.valueOf(paramMap.get(USER_CURRENT_LONG)));
            LatLng toPosition = new LatLng(Double.valueOf(paramMap.get(DESTINATION_LAT)) , Double.valueOf(paramMap.get(DESTINATION_LONG)));
            GMapV2Direction md = new GMapV2Direction();
            Document doc = md.getDocument(fromPosition, toPosition, paramMap.get(DIRECTIONS_MODE));
            ArrayList directionPoints = md.getDirection(doc);
            return directionPoints;
        }
        catch (Exception e)
        {
            exception = e;
            return null;
        }
    }

    private void processException()
    {
        // Toast.makeText(activity, activity.getString(R.string.error_when_retrieving_data), 3000).show();
    }
}

// Start the class that defines the map to use etc.

package gabrielfm.com.findyouchurch.Activitys;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Path;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.Circle;
import com.google.android.gms.maps.model.CircleOptions;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import org.w3c.dom.Document;

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

import gabrielfm.com.findyouchurch.BD.Database_Congregacao;
import gabrielfm.com.findyouchurch.Dados.GMapV2Direction;
import gabrielfm.com.findyouchurch.Dados.Gestao_Datas;
import gabrielfm.com.findyouchurch.Dados.GetDirectionsAsyncTask;
import gabrielfm.com.findyouchurch.R;

public class MapsActivity extends ActionBarActivity {



 LatLng start;
     LatLng and;
    private GoogleMap mMap;
    private Double latitude;
    GMapV2Direction md;
String titulo;
    private Double longitude;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);


    titulo=MapsActivity.this.getIntent().getStringExtra("titulo");

        getSupportActionBar().setTitle((Html.fromHtml("<small>" + (titulo) + "</small>")));

    //    setUpMapIfNeeded();

    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_todos_mapas, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

 private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {
        Gestao_Datas gestao_datas=new Gestao_Datas(getApplicationContext());

        String latitude=MapsActivity.this.getIntent().getStringExtra("latitude");
        String longitude=MapsActivity.this.getIntent().getStringExtra("longitude");
        String nome=MapsActivity.this.getIntent().getStringExtra("nome_congregacao");
        String cristao_latitude=MapsActivity.this.getIntent().getStringExtra("cristao");
        String cristao_longitude=MapsActivity.this.getIntent().getStringExtra("cristaoo");
        String time=MapsActivity.this.getIntent().getStringExtra("time");

//Cotido de circular
   //     CircleOptions circleOptions = new CircleOptions()
   //             .center(new LatLng(Float.parseFloat(cristao_latitude), Float.parseFloat(cristao_longitude)))
   //             .radius(1000); // In meters

// Get back the mutable Circle
//        Circle circle = mMap.addCircle(circleOptions);
//circle.setStrokeColor(Color.GREEN);
//        circle.setStrokeWidth(1);
start=new LatLng(Float.valueOf(cristao_latitude),Float.valueOf(cristao_longitude));
and=new LatLng(Float.valueOf(latitude),Float.valueOf(longitude));

        Marker m_person = mMap.addMarker(new MarkerOptions().position(new LatLng(Float.parseFloat(cristao_latitude), Float.parseFloat(cristao_longitude))).title("Tua Ultima Localização\n" + gestao_datas.dia(time) + "," + gestao_datas.mes_nome(time)).icon(BitmapDescriptorFactory.fromResource(R.drawable.walking_100)));
        // Marker marker=mMap.addMarker(new MarkerOptions().position(new LatLng(lt,lon)).title(nome_congregacao).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_place)));

        m_person.showInfoWindow();
        Marker marker= mMap.addMarker(new MarkerOptions().position(new LatLng(Float.parseFloat(latitude), Float.parseFloat(longitude))).title(nome));

        marker.showInfoWindow();
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(Float.parseFloat(latitude), Float.parseFloat(longitude)),14));


        /*
        Polyline line = mMap.addPolyline(new PolylineOptions()
                .add(new LatLng(Float.parseFloat(cristao_latitude), Float.parseFloat(cristao_longitude)), new LatLng(Float.parseFloat(latitude), Float.parseFloat(longitude)))
                .width(5)

                .color(Color.WHITE)
                .geodesic(true));

*/

       findDirections(start.latitude,
                start.longitude,
                and.latitude, and.longitude, GMapV2Direction.MODE_DRIVING);

        }


    private class showRoute extends AsyncTask<Void, Void, Document> {
        Document doc;
        public  Polyline linha; PolylineOptions rectLine;
        public showRoute() {
            // TODO Auto-generated constructor stub
        }
        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }
        @Override
        protected Document doInBackground(Void... params) {
            Log.d("mapa", "do in background direction");
            if(linha!=null){
                linha.remove();
                Log.d("mapa", "remove poliline");
            }
            doc = md.getDocument(start, and,GMapV2Direction.MODE_DRIVING);
            ArrayList<LatLng> directionPoint = md.getDirection(doc);
            rectLine = new PolylineOptions().width(3).color(Color.RED);
            for (int i = 0; i < directionPoint.size(); i++) {
                rectLine.add(directionPoint.get(i));
            }
            return null;
        }

        @Override
        protected void onPostExecute(Document result) {
            linha = mMap.addPolyline(rectLine);

        }

    }


    public void findDirections(double fromPositionDoubleLat, double fromPositionDoubleLong, double toPositionDoubleLat, double toPositionDoubleLong, String mode)
    {
        Map<String, String> map = new HashMap<String, String>();
        map.put(GetDirectionsAsyncTask.USER_CURRENT_LAT, String.valueOf(fromPositionDoubleLat));
        map.put(GetDirectionsAsyncTask.USER_CURRENT_LONG, String.valueOf(fromPositionDoubleLong));
        map.put(GetDirectionsAsyncTask.DESTINATION_LAT, String.valueOf(toPositionDoubleLat));
        map.put(GetDirectionsAsyncTask.DESTINATION_LONG, String.valueOf(toPositionDoubleLong));
        map.put(GetDirectionsAsyncTask.DIRECTIONS_MODE, mode);

        GetDirectionsAsyncTask asyncTask = new GetDirectionsAsyncTask(this);
        asyncTask.execute(map);
    }



    public void handleGetDirectionsResult(ArrayList directionPoints)
    {
        Polyline newPolyline;
        GoogleMap mMap = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

        PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.BLUE);
        for(int i = 0 ; i < directionPoints.size() ; i++)
        {
            rectLine.add((LatLng)directionPoints.get(i));
        }
        newPolyline = mMap.addPolyline(rectLine);
    }

}

// srenn

    
04.08.2015 / 13:49