1

I am working on google maps. I want to get the user location and show him on the map. I wrote a Locationlistener to get the user location.

 public Location getUserLocation(){

    try {
        // 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

            return null;
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,DISTANCE_CALC,TIME_UPDATE, this);
                Log.d("Network", "Network Enabled");
                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,DISTANCE_CALC,TIME_UPDATE, this);
                    Log.d("GPS", "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;
}

The getUserLocation() is one of the functions in the LocationListener that will return the user location with either the GPS or the network. I am calling this function from a fragment like this.

if (Build.VERSION.SDK_INT >= 23){
            if (checkPermission()) {
                location = locHandler.getUserLocation();
                if(location!=null)
                    showTheMaps(location);
                else
                    AlertBuilder(title,body);
            }else {
                requestPermission();
            }
        }else {
            //The build is less than marshmellow so no need for permission
            location = locHandler.getUserLocation();
            try {
//                double d = location.getLatitude();
                showTheMaps(location);
            }catch (NullPointerException e){
                AlertBuilder(title, body);
            }
       }


public void showTheMaps(Location location){

CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()), DataModel.zoomlevel);
googleMap.animateCamera(cameraUpdate);
}

The AlertBuilder function will show an alert box with a button which upon click closes the app.

As you can see from the screenshot the GPS is enabled yet the location returned to me is null and the app closes after showing the alert dialog. enter image description here What could be the problem? why is the location returning null even after turning on the GPS?

MrUpsidown
  • 21,592
  • 15
  • 77
  • 131
Tyson
  • 747
  • 2
  • 6
  • 18
  • Does the GPS have a fix by the time you ask for the location? – Carcigenicate Apr 25 '17 at 11:30
  • I don't know..There is a delay after which the icon appears..Is that what you mean @Carcigenicate..The dialog box appears before the icon appears on the top – Tyson Apr 25 '17 at 11:32
  • 1
    The `requestLocationUpdates()` only starts the (asynchronous) process of fetching the location. If you call `getLastKnownLocation()` right after it, the location isn't available yet. Your class should implement a location listener and receive the location in the `onLocationChanged()` callback. There are a lot of examples on Stack Overflow. – Markus Kauppinen Apr 25 '17 at 11:34
  • @Tyson Check the accuracy of the fix before trying to get the location. When I used the Python Android api to work with GPS like 3 years ago, I seem to recall needing to wait to allow it to find my location before asking. Check the API docs for what happens if you attempt to get the location before the GPS has a fix. – Carcigenicate Apr 25 '17 at 11:35
  • The location listener is implemented in the same class.. Are you suggesting that I call the `getUserLocation` function from `onLocationChanged()` before trying to call it from my fragment? @MarkusKauppinen – Tyson Apr 25 '17 at 11:36
  • 1
    [Only use `getLastKnownLocation()` as an optimization](https://stackoverflow.com/a/43082164/115145). Your code needs to be able to handle receiving a location via `onLocationChanged()` *in addition to* perhaps getting one from `getLastKnownLocation()`. – CommonsWare Apr 25 '17 at 11:42

1 Answers1

1

Use

Location currentLocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

Source: https://developer.android.com/training/location/retrieve-current.html

Another (deprecated) way is to set a OnMyLocationChangeListener to your map to get the location

mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
    @Override
    public void onMyLocationChange(Location location) {
        // do something with location
     }
});

More info: how to get current location in google map android

Community
  • 1
  • 1
Denny
  • 1,766
  • 3
  • 17
  • 37
  • There is no requirement fo `getLastLocation()` to return a non-`null` value. This is not much of an improvement over what the question has. – CommonsWare Apr 25 '17 at 11:40
  • It's just a suggestion for the OP to use other methods than used to get the location – Denny Apr 25 '17 at 11:47