Java Android Program to Draw Driving Route on Google Maps in Android

«
»
Here is source code of the Program to Draw Driving Route on Google Maps in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

Here i start a service in my tracker activity which updates my current location constantly and sends my current location yo my tracker activity which then draws a line between my previous known location and my current updated location by using map.addPolyline() method.

Tracker Activity

advertisement
package com.example.travelplanner;
 
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
 
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
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;
 
public class Tracker extends Activity {
 
    double latitude;
    double longi;
    private static final LatLng JLNStadium = new LatLng(28.590401000000000000,
            77.233255999999980000);
    LatLng JLNS = new LatLng(28.55, 77.54);
    private double pLati, plongi, dLati, dlongi;// previous latitude and
                                                // longitude
 
    private GoogleMap map;
 
    private BroadcastReceiver receiver = new BroadcastReceiver() {
 
        @Override
        public void onReceive(Context context, Intent intent) {
            Bundle bundle = intent.getExtras();
            Log.i("Here", "onreceived");
            if (bundle != null) {
 
                latitude = bundle.getDouble("lati");
                Log.i("Tag", latitude + "");
 
                longi = bundle.getDouble("longi");
                Log.i("tag", longi + "");
                drawmap(latitude, longi);
            }
        }
    };
 
    public void drawmap(double latid, double longid) {
        // draw on map here
        // draw line from intial to final location and draw tracker location map
 
        Log.i("Tag", "map");
 
        // add line b/w current and prev location.
 
        LatLng prev = new LatLng(pLati, plongi);
        LatLng my = new LatLng(latid, longid);
        //map.moveCamera(CameraUpdateFactory.newLatLngZoom(my, 15));
        // map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
 
        Polyline line = map.addPolyline(new PolylineOptions().add(prev, my)
                .width(5).color(Color.BLUE));
        pLati = latid;
        plongi = longid;
 
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, new IntentFilter("com.example.mc_project"));
    }
 
    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(receiver);
        this.onStop();
    }
 
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tracker);
        final double src_lati = getIntent().getDoubleExtra("src_lati", 0.0);
        Log.i("Tracker_Src_lati", src_lati + "");
        final double src_longi = getIntent().getDoubleExtra("src_longi", 0.0);
        final double dest_lati = getIntent().getDoubleExtra("dest_lati", 0.0);
        final double dest_longi = getIntent().getDoubleExtra("dest_longi", 0.0);
 
        pLati = src_lati;// intialize latitude and longitude here from intent data.
        plongi = src_longi;
 
        // & get destination lai and longi. from intent data
        dLati = dest_lati;
        dlongi = dest_longi;
 
        try {
            // Loading map
            initilizeMap();
 
        } catch (Exception e) {
            e.printStackTrace();
        }
        Intent loc_intent;
        loc_intent = new Intent(getBaseContext(), Getlocation.class);
        loc_intent.putExtra("lat", dLati);
        loc_intent.putExtra("lon", dlongi);
        startService(loc_intent);
 
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.tracker, menu);
        return true;
    }
 
    @SuppressLint("NewApi")
    private void initilizeMap() {
        if (map == null) {
            map = ((MapFragment) getFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
            Log.i("Tag", "map");
            // draw line b/w intial and final location.
 
            LatLng strt = new LatLng(pLati, plongi);
            LatLng end = new LatLng(dLati, dlongi);
            Marker start_m = map.addMarker(new MarkerOptions().position(strt)
                    .title("START"));
            Marker end_m = map.addMarker(new MarkerOptions().position(end)
                    .title("JLN"));
 
            //map.moveCamera(CameraUpdateFactory.newLatLngZoom(strt, 15));
            map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
 
            Polyline line = map.addPolyline(new PolylineOptions()
                    .add(strt, end).width(5).color(Color.RED));
 
            // check if map is created successfully or not
            if (map == null) {
                Toast.makeText(getApplicationContext(),
                        "Sorry! unable to create maps", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    }
 
}

Service

package com.example.travelplanner;
 
 
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
 
public class Getlocation extends AbstractService implements LocationListener {
 
    private Context Context;
    boolean isGPSEnabled = false;
    boolean isNetworkEnabled = false;
    boolean canGetLocation = false;
    int flag = 0;
    Location location;
    Notification notification;
    Location mylocation = new Location("");
    Location dest_location = new Location("");
    float distance;
    NotificationManager notifier;
    public double latitude;
    double longitude;
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 40;// 40 meters
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 2;
 
    // update location within a time period of 2 minutes
 
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Log.i("Tag", "on create");
 
    }
 
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        Log.i("Indestroy", "destroyed");
        flag = 0;
        stopSelf();
        stopUsingGPS();
        super.onDestroy();
    }
 
    @Override
    public int onStartCommand(Intent intent, int flags, int startid) {
        // TODO Auto-generated method stub
        Context = this;
        Log.i("tag", "on start");
        mylocation = getLocation(Context);
 
        Double msg = mylocation.getLatitude();
        Log.i("my long", msg.toString());
 
        Double dest_lat = intent.getDoubleExtra("lat", 0.0);
        Double dest_lon = intent.getDoubleExtra("lon", 0.0);
        Log.i("get lat", dest_lat.toString());
        Log.i("get lon", dest_lon.toString());
 
        this.dest_location.setLatitude(dest_lat);
        this.dest_location.setLongitude(dest_lon);
        Log.i("get lon", dest_lon.toString());
 
        return START_NOT_STICKY;
    }
 
    protected LocationManager locationManager;
 
    public Location getLocation(Context Context) {
 
        try {
            locationManager = (LocationManager) Context
                    .getSystemService(LOCATION_SERVICE);
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
 
            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
                Log.i("No gps and No Network ",
                        "No gps and No Network is enabled enable either one of them");
                Toast.makeText(this, "Enable either Network or GPS",
                        Toast.LENGTH_LONG).show();
            } else {
                this.canGetLocation = true;
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }
 
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return location;
    }
 
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(Getlocation.this);
        }
    }
 
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }
        return latitude;
    }
 
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }
        return longitude;
    }
 
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
 
    @Override
    public void onLocationChanged(Location location) {
 
        mylocation = getLocation(Context);
        Log.i("Tag", "location changed");
        distance = mylocation.distanceTo(dest_location);
        Log.i("Tag", "" + distance);
        if (flag == 0) {
            Intent intent1 = new Intent("com.example.mc_project");
            intent1.putExtra("lati", mylocation.getLatitude());
            intent1.putExtra("longi", mylocation.getLongitude());
            sendBroadcast(intent1);
 
            //Toast.makeText(this, "broadcasted", Toast.LENGTH_LONG).show();
            if ((distance) < 600) {
                Log.i("Distance", "dist. b/w < 1km");
                Log.d("location", "" + distance);
                NotificationManager notificationManager = (NotificationManager) Context
                        .getSystemService(Context.NOTIFICATION_SERVICE);
                PendingIntent pendingIntent = PendingIntent.getActivity(
                        Context, 1, new Intent(Context, MainActivity.class), 0);
                Notification notification = new Notification(
                        R.drawable.ic_launcher,
                        "You areached ur destination!!",
                        System.currentTimeMillis());
                notification.defaults |= Notification.DEFAULT_SOUND;
                notification.setLatestEventInfo(Context,
                        "You areached ur destination!!", "You areached ur destination!!",
                        pendingIntent);
 
                notificationManager.notify(11, notification);
                Vibrator vi = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
 
                vi.vibrate(1000);
                flag = 1;
                onDestroy();
            }
        }
    }
 
    @Override
    public void onProviderDisabled(String provider) {
    }
 
    @Override
    public void onProviderEnabled(String provider) {
    }
 
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
 
    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
 
    @Override
    public void onStartService() {
        // TODO Auto-generated method stub
 
    }
 
    @Override
    public void onStopService() {
        // TODO Auto-generated method stub
 
    }
 
    @Override
    public void onReceiveMessage(Message msg) {
        // TODO Auto-generated method stub
 
    }
 
}

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement
If you wish to look at all Tutorials, go to Java Android Tutorials.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.