How to draw a path between two locations in google maps

时间:2015-11-12 11:57:10

标签: android google-maps

I'm developing an android app in which I need to show the Google Map with the path drawn from source to destination.For Example I need to go from A to B there might be different routes but I need to draw only on a particular route.

This is what tried but it was not taking on any road it directly displaying a line from source to destination.

public class MapsActivity extends Activity {
private GoogleMap googleMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);

    try {
        if (googleMap == null) {
            googleMap = ((MapFragment) getFragmentManager().
                    findFragmentById(R.id.map)).getMap();
        }
       /* googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        Marker TP = googleMap.addMarker(new MarkerOptions().
                position(TutorialsPoint).title("My Location"));*/

        Polyline line = googleMap.addPolyline(new PolylineOptions()
                .add(new LatLng(17.4489224, 78.3483612), new LatLng(17.4831854, 77.9736794))
                .width(5)
                .color(Color.RED));
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:3)

首先,您必须创建一个Polyline对象来指定点,然后您可以设置Polyline对象添加Polyline选项:

PolylineOptions polylineOptions = new PolylineOptions()
    .add(new LatLng(37.35, -122.0)); // Point A.
    .add(new LatLng(38.35, -123.0)); // Point B.

Polyline polyline = mMap.addPolyline(polylineOptions);

要在添加折线后更改折线的形状,可以调用Polyline.setPoints()并为折线提供新的点列表。