Android : How to draw driving path with location changing in new google map services

493 views Asked by At

I used google android map to mark current location and another location . Also I wanted to mark drive path between these directions. But I could draw just only a single line between theses two locations.

Here are my steps,

This is my layout file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/content_roster_clock_out_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="5dp"
    android:layout_marginTop="3dp"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".RosterClockOutActivity"
    tools:showIn="@layout/app_bar_roster_clock_out">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="5dp"
            android:layout_marginRight="5dp"
            android:orientation="vertical">

            <com.google.android.gms.maps.MapView
                android:id="@+id/roster_clock_out_map_view"
                android:layout_width="match_parent"
                android:layout_height="300dp"
                android:clickable="true"
                android:apiKey="my api key"
                android:layout_weight="1"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/roster_clock_out_map_view"
                android:layout_marginTop="4dp"
                android:layout_marginBottom="15dp"
                android:alpha="0.5"
                android:background="#765491"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/roster_clock_out_date_text"
                    android:layout_width="match_parent"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:paddingTop="7dp"
                    android:background="#563e6b"
                    android:paddingBottom="7dp"
                    android:text="5 th MAY 2017"
                    android:textAlignment="center"
                    android:textStyle="bold"
                    android:textColor="@android:color/white"
                    android:textSize="24sp" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="10dp"
                    android:orientation="horizontal">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="START TIME"
                        android:textStyle="bold"
                        android:textAlignment="center"
                        android:textColor="@android:color/white"
                        android:textSize="14sp" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="END TIME"
                        android:textStyle="bold"
                        android:textAlignment="center"
                        android:textColor="@android:color/white"
                        android:textSize="14sp" />

                </LinearLayout>


                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="horizontal">

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:id="@+id/roster_clock_out_st_time_text"
                        android:layout_weight="1"
                        android:text="08.30 AM"
                        android:textStyle="bold"
                        android:textAlignment="center"
                        android:textColor="@android:color/white"
                        android:textSize="20sp" />

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:id="@+id/roster_clock_out_ed_time_text"
                        android:layout_weight="1"
                        android:text="05.30 PM"
                        android:textStyle="bold"
                        android:textAlignment="center"
                        android:textColor="@android:color/white"
                        android:textSize="20sp" />

                </LinearLayout>

                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:id="@+id/roster_clock_out_location_text"
                    android:layout_marginRight="35dp"
                    android:layout_marginLeft="35dp"
                    android:layout_marginTop="8dp"
                    android:drawablePadding="5dp"
                    android:drawableLeft="@drawable/ic_place_small"
                    android:textAlignment="center"
                    android:maxLines="3"
                    android:lines="3"
                    android:clickable="true"
                    android:textSize="14sp"
                    android:text="Australian Strategic Partnership\n#9, School Lane, Kollpity, Colombo 3"
                    android:textColor="@android:color/white" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="18dp"
                    android:orientation="horizontal">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="10dp"
                        android:layout_weight="1"
                        android:orientation="vertical">

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"
                                android:textSize="14sp"
                                android:text="CLOCK IN"
                                android:textStyle="bold"
                                android:textAlignment="center"
                                android:textColor="#f7f316"/>

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:layout_weight="1"/>

                        </LinearLayout>

                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:orientation="horizontal">

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:id="@+id/roster_clock_in_sign_time_text"
                                android:layout_weight="1"
                                android:textSize="18sp"
                                android:textStyle="bold"
                                android:textColor="#f7f316"
                                android:text="08:43 PM"
                                android:textAlignment="center"/>

                            <TextView
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                android:id="@+id/roster_clock_in_delayed_time_text"
                                android:layout_weight="1"
                                android:textSize="18sp"
                                android:textColor="@android:color/white"
                                android:text="04:00"
                                android:textStyle="bold"
                                android:textAlignment="center"/>

                        </LinearLayout>

                    </LinearLayout>

                    <android.support.v7.widget.AppCompatButton
                        android:id="@+id/roster_clock_out_save_btn"
                        style="@style/ButtonStyle"
                        android:layout_height="32dp"
                        android:background="#800080"
                        android:alpha="5"
                        android:layout_marginBottom="10dp"
                        android:layout_marginRight="10dp"
                        android:textSize="16sp"
                        android:textStyle="bold"
                        android:clickable="true"
                        android:layout_weight="1.5"
                        android:text="CLOCK OUT" />

                </LinearLayout>

            </LinearLayout>

        </LinearLayout>

    </ScrollView>

</RelativeLayout>

And this step is for google map implement inside an activity,

public class RosterActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {

    private Context context;    
    MapView locationMap;
    View mainView;

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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_roster);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        mainView = this.getWindow().getDecorView().findViewById(R.id.content_roster_clock_in_layout);
        context = this;                    

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout_roster);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view_roster);
        Menu menu = navigationView.getMenu();
        if (menu != null) {
            for (int i = 0; i < menu.size(); i++) {
                MenuItem menuItem = menu.getItem(i);

            }
        }
        navigationView.setNavigationItemSelectedListener(this);

        locationMap = (MapView) findViewById(R.id.roster_map_view);
        locationMap.onCreate(savedInstanceState);        

        InternetConnectivity internetConnectivity = new InternetConnectivity();
        final boolean isConnectedToInternet = internetConnectivity.isConnectedToInternet(context);

        final LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        final Criteria criteria = new Criteria();

        final Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));

        if (isConnectedToInternet == true) {

            final LatLng assignedLocation = new LatLng(6.931253, 79.906292);

            locationMap.getMapAsync(new OnMapReadyCallback() {
                @Override
                public void onMapReady(final GoogleMap googleMap) {
                    if (ActivityCompat.checkSelfPermission(RosterActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(RosterActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        googleMap.setMyLocationEnabled(true);
                    }
                    googleMap.setMyLocationEnabled(true);
                    googleMap.getUiSettings().setAllGesturesEnabled(true);
                    googleMap.getUiSettings().setZoomControlsEnabled(true);
                    googleMap.getUiSettings().setScrollGesturesEnabled(true);
                    googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                    if (location != null)                    {
                        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 13));

                        CameraPosition cameraPosition = new CameraPosition.Builder()
                                .target(new LatLng(location.getLatitude(), location.getLongitude()))
                                .zoom(10)
                                .bearing(0)
                                .tilt(40)
                                .build();
                        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
                    }
                    googleMap.addMarker(new MarkerOptions().position(assignedLocation).title("Your Location").draggable(true));

                }
            });

            setData(responseBody);
        }else{
            Snackbar.make(mainView, "No Internet Connection", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }      
    }

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        return true;
    }



    @Override
    protected void onStart() {
        super.onStart();
        locationMap.onStart();
    }

    @Override
    protected void onResume() {
        super.onResume();
        locationMap.onResume();
    }

    @Override
    protected void onPause(){
        super.onPause();
        locationMap.onPause();
    }

    @Override
    protected void onStop(){
        super.onStop();
        locationMap.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationMap.onDestroy();
    }

    @Override
    public void onLowMemory(){
        super.onLowMemory();
        locationMap.onLowMemory();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        locationMap.onSaveInstanceState(outState);
    }

}

How can I do with my mapview and google map ?

Have any ideas ?

2

There are 2 answers

0
Nguyễn Gia Lễ On
  1. Please get data from this api, with these parameter: origin ( lat,long of source), destination(lat, long of destination), key( google api key) http://maps.googleapis.com/maps/api/directions/json
  2. Data which get from above api is a list of location from A to B. All you have to do is draw a list of dot from data. You will get a direction line from a to b

        final JSONObject json = new JSONObject(result);
        JSONArray routeArray = json.getJSONArray("routes");
        JSONObject routes = routeArray.getJSONObject(0);
        JSONObject overviewPolylines = routes
                .getJSONObject("overview_polyline");
        String encodedString = overviewPolylines.getString("points");
    
        JSONArray legArray =routes.getJSONArray("legs");
        JSONObject legs= legArray.getJSONObject(0);
        JSONObject distance =legs.getJSONObject("distance");
        String dis=distance.getString("text");
        RouteActivity.txtDistance.setText("("+dis+")");
    
        JSONObject duration =legs.getJSONObject("duration");
        String dur=duration.getString("text");
        RouteActivity.txtTime.setText(dur);
    
        List<LatLng> list = decodePoly(encodedString);
    
        PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
        for (int z = 0; z < list.size(); z++) {
            LatLng point = list.get(z);
            options.add(point);
        }
        mGoogleMap.addPolyline(options);
    
    private static List<LatLng> decodePoly(String encoded) {
    
    List<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 p = new LatLng((((double) lat / 1E5)),
                (((double) lng / 1E5)));
        poly.add(p);
    }
    
    return poly;
    }
    
0
parbir On

You can use google direvtions in google map android api v2.

This will return routes in JSONArray format.

Parse the array and store in List

Use polylines to display the routes stored in List.