0

I know this question is similar to other question but i am unable to understand the procedure of getting my location in google map. I have tried lots of tutorials but i think i am missing something.

I am using the following code in my main class :

 LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    //I am getting bestProvider = gps here 
    String bestProvider = locationManager.getBestProvider(criteria, true);
    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) {
       //getting location null here 
        Location location = locationManager.getLastKnownLocation(bestProvider);

        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
    }else 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)){
  //getting location null here 
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(bestProvider, 20000, 0, this);
    }
}

@Override
public void onLocationChanged(Location location) {
    TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    LatLng latLng = new LatLng(latitude, longitude);
    googleMap.addMarker(new MarkerOptions().position(latLng));
    googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
    locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
Preet Jay
  • 309
  • 4
  • 8

2 Answers2

2

Here you go.You can use this below code sample in your application:

public class CurrentLocation {
Timer timer;
LocationManager locationManager;
LocationResult locationResult;
boolean gpsEnabled=false;
boolean networkEnabled=false;

public boolean getLocation(Context context, LocationResult result)
{
    //I use LocationResult callback class to pass location value from MyLocation to user code.
    locationResult=result;
    if(locationManager ==null)
        locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    //exceptions will be thrown if provider is not permitted.
    try{
        gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
    try{
        networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}

    //don't start listeners if no provider is enabled
    if(!gpsEnabled && !networkEnabled)
        return false;

    if(gpsEnabled)
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
    if(networkEnabled)
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
    timer =new Timer();
    timer.schedule(new GetLastLocation(), 20000);
    return true;
}

LocationListener locationListenerGps = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer.cancel();
        locationResult.gotLocation(location);
        locationManager.removeUpdates(this);
        locationManager.removeUpdates(locationListenerNetwork);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

LocationListener locationListenerNetwork = new LocationListener() {
    public void onLocationChanged(Location location) {
        timer.cancel();
        locationResult.gotLocation(location);
        locationManager.removeUpdates(this);
        locationManager.removeUpdates(locationListenerGps);
    }
    public void onProviderDisabled(String provider) {}
    public void onProviderEnabled(String provider) {}
    public void onStatusChanged(String provider, int status, Bundle extras) {}
};

class GetLastLocation extends TimerTask {
    @Override
    public void run() {
        locationManager.removeUpdates(locationListenerGps);
        locationManager.removeUpdates(locationListenerNetwork);

        Location net_loc=null, gps_loc=null;
        if(gpsEnabled)
            gps_loc= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(networkEnabled)
            net_loc= locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

        //if there are both values use the latest one
        if(gps_loc!=null && net_loc!=null){
            if(gps_loc.getTime()>net_loc.getTime())
                locationResult.gotLocation(gps_loc);
            else
                locationResult.gotLocation(net_loc);
            return;
        }

        if(gps_loc!=null){
            locationResult.gotLocation(gps_loc);
            return;
        }
        if(net_loc!=null){
            locationResult.gotLocation(net_loc);
            return;
        }
        locationResult.gotLocation(null);
    }
}

}

Riten
  • 2,879
  • 3
  • 24
  • 28
0

Use this code for get current location by GPS provider or network provider

if (locationManager == null) {
                locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            }
            if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)) {
                isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                isNetworkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                if (isGPSEnabled) {
                    location = getLastLocationByProvider(locationManager, LocationManager.GPS_PROVIDER, getApplicationContext());
                } else if (isNetworkProviderEnabled) {
                    location = getLastLocationByProvider(locationManager, LocationManager.NETWORK_PROVIDER, getApplicationContext());
                }
                if (location != null) {
                    latitude = location.getLatitude();
                    longitude = location.getLongitude();
                } else {
                    if (isNetworkProviderEnabled) {
                        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100000, 1, this);
                        provider_info = LocationManager.NETWORK_PROVIDER;
                    } else if (isGPSEnabled) {
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100000, 1, this);
                        provider_info = LocationManager.GPS_PROVIDER;
                    } else {

                        alertDialog = Util.showOkDialog(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                if (Env.currentActivity != null) {
                                    if (Env.currentActivity instanceof LocationActivity) {
                                        try {
                                            gotoSettings();
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                    }

                                }
                                if (alertDialog != null) {
                                    alertDialog.dismiss();
                                    alertDialog = null;
                                }

                            }
                        }, this.getResources().getString(R.string.location_service_validation));

                    }

                    location = locationManager.getLastKnownLocation(provider_info);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
Nitesh Pareek
  • 362
  • 2
  • 10