BatCave1997
7/23/2018 - 5:13 AM

Maps api and GPS

Using maps api to track down current user location. Geocoder to configure gps Access Fine Locatio permission required Api key is needed to use google maps service

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    LocationListener locationListener;
    LocationManager locationManager;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(grantResults.length>1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }


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

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                LatLng  loc = new LatLng(location.getLatitude(),location.getLongitude());
                mMap.addMarker(new MarkerOptions().position(loc).title("You are here"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));

                Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
                try {
                    List<Address> list = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

                    if(list != null){
                        String address = "";

                        if(list.get(0).getThoroughfare() != null){
                            address += list.get(0).getThoroughfare()+" ";
                        }

                        if(list.get(0).getSubLocality() != null){
                            address += list.get(0).getSubLocality()+" ";
                        }

                        if(list.get(0).getLocality() != null){
                            address += list.get(0).getLocality()+" ";
                        }

                        if(list.get(0).getAdminArea() != null){
                            address += list.get(0).getAdminArea()+" ";
                        }

                        Log.i("Place info", address);
                        Toast.makeText(MapsActivity.this, "You are at : "+address, Toast.LENGTH_SHORT).show();

                    }
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }


            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
        }
        else{
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
            Location lastLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

            LatLng  loc = new LatLng(lastLoc.getLatitude(),lastLoc.getLongitude());
            mMap.addMarker(new MarkerOptions().position(loc).title("You are here"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(loc));
        }
    }
}
public class MainActivity extends AppCompatActivity {

    LocationManager locationManager;
    LocationListener listener;

    TextView la, lo, ac, ad;

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if(grantResults.length>1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
            }
        }
    }

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

        la = findViewById(R.id.lat);
        lo = findViewById(R.id.lon);
        ac = findViewById(R.id.acc);
        ad = findViewById(R.id.add);

        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                String lat = String.valueOf(location.getLatitude());
                String lon = String.valueOf(location.getLongitude());
                String acc = String.valueOf(location.getAccuracy());

                Log.i("Latitude", lat);
                Log.i("Longitude", lon);
                Log.i("Accuracy", acc);

                Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
                try {
                    List<Address> list = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(),1);
                    if(list != null){
                        String address = "";
                        if(list.get(0).getThoroughfare() != null){
                            address += list.get(0).getThoroughfare()+" ";
                        }
                        if(list.get(0).getLocality() != null){
                            address += list.get(0).getLocality()+ " ";
                        }
                        if(list.get(0).getAdminArea() != null){
                            address += list.get(0).getAdminArea()+" ";
                        }

                        Log.i("Address", address);

                        la.setText("Latitude : "+lat);
                        lo.setText("Longitude : "+lon);
                        ac.setText("Accuracy : "+acc);
                        ad.setText("Address : "+address);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        if(ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
        }else{
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
        }
    }
}