Android tutorial

Android how to used Google map and Show root and Calculate distance.

Android and Google Maps. This tutorial describes the usage of Google Maps in your Android application. In this article, I am sharing how to used a google map in android and how to show a marker on current location and source

And in these article, I am sharing how to show root in google map and show these root alternate root and  calculate the distance start to end point

Used a start trip run on google map

Step 1: First one to  Start Android Studio

Step 2 :  Seconds step to Create a New Project Project ClickOn  ==> File  ==> NEW ==> New Project

And select the google map activity in the android studio.

Step 3: Gradle Scripts Open Project base and add these

uildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.3'
       classpath 'com.google.gms:google-services:3.1.0'
   }
}
allprojects {
    repositories {
        mavenLocal()
        mavenCentral()
        maven {                                  // <-- Add this
           url 'https://maven.google.com/'
           name 'Google'
       }
        jcenter()
        maven {
            url "https://jitpack.io"
       }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And App Base  build.gradle and add these

First, one to add google service in your gradle.

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:27.0.2'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:design:27.0.2'
    compile 'com.android.support:support-v4:27.0.2'
    compile 'com.android.volley:volley:1.0.0'
    compile 'com.google.firebase:firebase-messaging:11.0.4'
    compile 'com.google.android.gms:play-services-base:11.0.4’
    compile 'com.google.android.gms:play-services-maps:11.0.4'
    compile 'com.google.maps.android:android-maps-utils:0.4.3'
    compile 'com.google.android.gms:play-services-location:11.0.4'
    compile 'org.jsoup:jsoup:1.11.2'
    testCompile 'junit:junit:4.12'
}
apply plugin: 'com.google.gms.google-services'

Step 4:  Open your XML file add these

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.codeplayon.StartTrip">

    <TextView
        android:id="@+id/RootText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:background="@color/colorPrimary"
        android:textColor="@color/text"/>
    <TextView
        android:id="@+id/RootText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:background="@color/colorPrimary"
        android:textColor="@color/text"/>

    <TextView
        android:id="@+id/RootText2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="2dp"
        android:background="@color/colorPrimary"
        android:textColor="@color/text"/>
    <fragment
        android:id="@+id/map"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

 

Step 5: Open your java file and add these code

public class StartTrip extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, RoutingListener {
    private GoogleMap mMap;
    double Latitude;
    double Longitude;
    protected LatLng start;
    protected LatLng end;
    TextView RouteText,RouteText1,RouteText2;
    //    double Latitude1;
//    double Longitude1;
   Location mCurrentLocation;
    String mLastUpdateTime;
    private static final String LOG_TAG = "MyActivity";

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;
    String Name, Address;
    AutoCompleteTextView destination;
    AutoCompleteTextView starting;
    private List<Polyline> polylines;
    private static final int[] COLORS = new int[]{R.color.driving,R.color.colorPrimary,R.color.colorAccent,R.color.secondryText,R.color.primary_dark_material_light};

    private static final long INTERVAL = 1000 * 60 * 1; //1 minute
   private static final long FASTEST_INTERVAL = 1000 * 60 * 1; // 1 minute
   private static final String TAG = "LocationTracker";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        logEvent("onCreate");
        //show error dialog if GoolglePlayServices not available
       if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        // Create Location Request
       createLocationRequest();
        polylines = new ArrayList<>();
        // Initialize GoogleApiClient
       mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
        setContentView(R.layout.activity_start_trip);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        Latitude = getIntent().getDoubleExtra("lat", Latitude);
        Longitude = getIntent().getDoubleExtra("log", Longitude);
        Address = getIntent().getStringExtra("address");
        end=new LatLng(Latitude,Longitude);

        Name = getIntent().getStringExtra("name");
        RouteText=(TextView)findViewById(R.id.RootText);
        RouteText1=(TextView)findViewById(R.id.RootText1);
        RouteText2=(TextView)findViewById(R.id.RootText2);


//        String lat=bundle.getString("lat");
//        String longs=bundle.getString("long");
//        Latitude1= Double.parseDouble(lat);
//        Longitude1=Double.parseDouble(longs);
   }

    private boolean isGooglePlayServicesAvailable() {
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (ConnectionResult.SUCCESS == status) {
            return true;
        } else {
            GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
            return false;
        }
    }

    /**
     * LocationRequest objects are used to request of service parameters
     * for request to the FusedLocationProviderApi.
     */
   private void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    protected void onStart() {
        super.onStart();
        logEvent("onStart");
        mGoogleApiClient.connect();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mGoogleApiClient.isConnected()) {
            startLocationUpdates();
            logEvent("Location update resumed");
        }
    }

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

    @Override
    protected void onStop() {
        super.onStop();
        logEvent("onStop");
        mGoogleApiClient.disconnect();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
       LatLng sydney = new LatLng(Latitude, Longitude);
        mMap.addMarker(new MarkerOptions().position(sydney).title(Name).snippet(Address));


    }

    /**
     * Before any operation is executed, the GoogleApiClient must be connected using the connect() method.
     * The client is not considered connected until the onConnected(Bundle) callback has been called.
     * @param bundle
    */
   @Override
    public void onConnected(@Nullable Bundle bundle) {
        logEvent("onConnected");
        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        logEvent("Connection failed: " + connectionResult.toString());

    }

    @Override
    public void onLocationChanged(Location location) {
        logEvent("onLocationChanged");
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        addMarker();

    }

    private void addMarker() {
        logEvent("addMarker");
        MarkerOptions options = new MarkerOptions();
        // To display the time as title for location markers
       IconGenerator iconFactory = new IconGenerator(this);
        iconFactory.setStyle(IconGenerator.STYLE_BLUE);
        options.icon(BitmapDescriptorFactory.
                fromBitmap(iconFactory.makeIcon(mLastUpdateTime)));
        options.anchor(iconFactory.getAnchorU(), iconFactory.getAnchorV());

        // Set marker
        start = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
        options.position(start);
        Marker marker = mMap.addMarker(options);
        long atTime = mCurrentLocation.getTime();
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date(atTime));
        marker.setTitle(mLastUpdateTime);
        logEvent("Marker added");
        LatLng origin = new LatLng(mCurrentLocation.getLatitude(),mCurrentLocation.getLongitude());
        LatLng destination = new LatLng(Latitude, Longitude);
//        start = new LatLng(18.015365, -77.499382);
//        waypoint= new LatLng(18.01455, -77.499333);
//        end = new LatLng(18.012590, -77.500659);
       sendRequest();

//
//        mMap.addPolyline((new PolylineOptions())
//                .add(origin,destination).width(5).color(Color.BLUE)
//                .geodesic(true));
//        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15));
        // move camera to zoom on map

   }


    /**
     * Request location updates with GoogleApiClient object, LocationRequest and
     * listener to pass result.
     */
   private void startLocationUpdates() {
        logEvent("startLocationUpdates");
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
           //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
           return;
        }
        PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);

    }

    /**
     * User is leaving screen, so stop location updates
     */
   protected void stopLocationUpdates() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        logEvent("Location update stopped.");
    }


    /**
     * Logs event
     * @param event
    */
   private void logEvent(String event) {
        Log.d(TAG, event);
    }

    public void sendRequest()
    {
        if (AppStatus.getInstance(this).isOnline()) {
//            Toast.makeText(this,"You are online!!!!",Toast.LENGTH_LONG).show();
           route();
        } else {
            ContextThemeWrapper ctw = new ContextThemeWrapper( StartTrip.this, R.style.Theme_AlertDialog);
            final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(ctw);
            alertDialogBuilder.setTitle("No internet connection");
            alertDialogBuilder.setMessage("Check your  internet connection or try again");
            alertDialogBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                }
            });
            alertDialogBuilder.show();
//            Toast.makeText(this,"You are not online!!!!",Toast.LENGTH_LONG).show();
//            Log.v("Home", "############################You are not online!!!!");
       }
    }


    public void route()
    {
        if(start==null || end==null)
        {
            if(start==null)
            {
                if(starting.getText().length()>0)
                {
                    starting.setError("Choose location from dropdown.");
                }
                else
               {
                    Toast.makeText(this,"Please choose a starting point.",Toast.LENGTH_SHORT).show();
                }
            }
            if(end==null)
            {
                if(destination.getText().length()>0)
                {
                    destination.setError("Choose location from dropdown.");
                }
                else
               {
                    Toast.makeText(this,"Please choose a destination.",Toast.LENGTH_SHORT).show();
                }
            }
        }
        else
       {

            Routing routing = new Routing.Builder()
                    .travelMode(AbstractRouting.TravelMode.DRIVING)
                    .withListener(this)
                    .alternativeRoutes(true)
                    .waypoints(start, end)
                    .build();
            routing.execute();

        }
    }


    @Override
    public void onRoutingFailure(RouteException e) {
        if(e != null) {
            Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }else {
            Toast.makeText(this, "Something went wrong, Try again", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onRoutingStart() {

    }

    @Override
    public void onRoutingSuccess(ArrayList<Route> route, int shortestRouteIndex) {
        CameraUpdate center = CameraUpdateFactory.newLatLng(start);
        CameraUpdate zoom = CameraUpdateFactory.zoomTo(12);
        mMap.moveCamera(center);
        mMap.moveCamera(zoom);
        mMap.getUiSettings().setZoomControlsEnabled(true);

        if(polylines.size()>0) {
            for (Polyline poly : polylines) {
                poly.remove();
            }
        }

        polylines = new ArrayList<>();
        //add route(s) to the map.
       for (int i = 0; i <route.size(); i++) {

            //In case of more than 5 alternative routes
           int colorIndex = i % COLORS.length;
            PolylineOptions polyOptions = new PolylineOptions();
            polyOptions.color(getResources().getColor(COLORS[colorIndex]));
            polyOptions.width(10 + i * 3);
            polyOptions.addAll(route.get(i).getPoints());
            polyOptions.toString();
            Polyline polyline = mMap.addPolyline(polyOptions);
            polylines.add(polyline);
            if(i==0){
//                Toast.makeText(getApplicationContext(),"Route "+ (i+1) +": distance- "+ route.get(i).getDistanceValue()/1000+": Time - "+ route.get(i).getDurationValue()/60,Toast.LENGTH_LONG).show();
           RouteText.setText("Route "+ (i+1) +":    KM- "+ route.get(i).getDistanceValue()/1000+":    Time- "+ route.get(i).getDurationValue()/60+"Mints");
            }else if(i==1){
//                Toast.makeText(getApplicationContext(),"Route "+ (i+1) +": distance- "+ route.get(i).getDistanceValue()+": Time - "+ route.get(i).getDurationValue()/60,Toast.LENGTH_LONG).show();
               RouteText1.setText("Route "+ (i+1) +":    KM- "+ route.get(i).getDistanceValue()/1000+":    Time- "+ route.get(i).getDurationValue()/60+"Mints");
            }else if(i==2){
//                Toast.makeText(getApplicationContext(),"Route "+ (i+1) +": distance- "+ route.get(i).getDistanceValue()+": Time - "+ route.get(i).getDurationValue()/60,Toast.LENGTH_LONG).show();
               RouteText2.setText("Route "+ (i+1) +":    KM- "+ route.get(i).getDistanceValue()/1000+":    Time - "+ route.get(i).getDurationValue()/60+"Mints");
            }



        }

        // Start marker
       MarkerOptions options = new MarkerOptions();
        options.position(start);
        options.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_directions_bike_black_48dp));
        mMap.addMarker(options);
        mMap.moveCamera(zoom);

        // End marker
//        options = new MarkerOptions();
//        options.position(end);
//        options.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_home_black_48dp));
//        mMap.addMarker(options);

   }



    @Override
    public void onRoutingCancelled() {
        Log.i(LOG_TAG, "Routing was cancelled.");

    }


}

 

Step 6: Manifest file add permission

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="in.rocareindia.com.rocareindiaems">

    <permission
        android:name="rutul.locationtracker.androidlocationmaps.permission.MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="com.javapapers.android.androidlocationmaps.permission.MAPS_RECEIVE" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:largeHeap="true"
        android:roundIcon="@mipmap/ic_launcher"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <activity
    android:name=".StartTrip"
    android:screenOrientation="portrait" />


        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_api_key" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        
    </application>

</manifest>

 

Step 7: Create  GPSTracker Class

public class GPSTracker1 extends Service implements LocationListener {

    private final
    CompleteCondition mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude
    long time;
    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker1(CompleteCondition context) {
        this.mContext = context;
        getLocation();
    }




    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                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 GPS Enabled get lat/long using GPS Services
                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;
    }

    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     */
    public void stopUsingGPS() {
        if (locationManager != null) {
            locationManager.removeUpdates(GPSTracker1.this);
        }
    }

    /**
     * Function to get latitude
     */
    public double getLatitude() {
        if (location != null) {
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     */
    public double getLongitude() {
        if (location != null) {
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     *
     * @return boolean
     */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     */
    public void showSettingsAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                mContext.startActivity(intent);
            }
        });

        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {


    }


    @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;
    }

}

 

 

 

 

 

 

 

1 Comment

  1. For most up-to-date news you have to pay a visit world wide web and on web I found this web site as a finest website for latest updates.|

Comments are closed.