0
votes

I've got a activity that onCreate, it calculates the distance between your location and a event that is nearby, I've used lastKnownLocation to get the current device location and put a marker of it on a google map, but I need it to write the longitude and latitude outside of it's method to be used to calculate distances.

I've used LocationManager to get the rough coordinates but these aren't accurate enough and has a distance of 50 miles for something that's not even half a mile away. I currently have it so will overwrite longitude and latitude got from LocationManager but it does not.

I've attempted to use LocationRequest too and that hasn't helped.

                    LocationRequest locationRequest = LocationRequest.create();
                    locationRequest.setInterval(60000);
                    locationRequest.setFastestInterval(5000);
                    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                    LocationCallback locationCallback = new LocationCallback() {
                        @Override
                        public void onLocationResult(LocationResult locationResult){
                            if(locationRequest==null){
                                return;
                            }
                            for(Location location : locationResult.getLocations()) {
                                if (location != null){
                                    userLat=location.getLatitude();
                                    userLng=location.getLongitude();
                                }
                            }
                        }
                    };

                    LocationServices.getFusedLocationProviderClient(EventLocator.this).requestLocationUpdates(locationRequest,locationCallback, null);

                    LocationServices.getFusedLocationProviderClient(EventLocator.this).getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {

                        @Override
                        public void onSuccess(Location location) {
                            if(location!=null){
                                double longitude=location.getLongitude();
                                double latitude=location.getLatitude();
                                userLng=longitude;
                                userLat=latitude;
                            }
                        }
                    });

All the permissions are correct, as I said I've used getLastLocation() to place a marker.

5
Some time location you get is not correct. You can check accuracy before you calculate the distance. Location.getaccuracy()Harry Mad

5 Answers

1
votes
  1. Make sure you added location permission in manifest file

  2. If you are using android os 6 above make sure you have location permission

  3. Make sure you GPS service is enabled in you mobile

    public Location getLocation() { LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    if (locationManager != null) {
    Location lastKnownLocationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (lastKnownLocationGPS != null) {
    return lastKnownLocationGPS; } else {
    Location loc = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); System.out.println("1::"+loc);----getting null over here System.out.println("2::"+loc.getLatitude()); return loc; } } else {
    return null; } }

If still not working try to restart your phone and then try again.

0
votes

You can create interface and implement it in the class where you need to calculate the distance

0
votes

Usually GPS takes time to warm up. Your initial location reading could be from a cold GPS. In order to get a more accurate reading keep reading results until you get an accuracy reading that works for you.

Keep in mind GPS on a phone is not very accurate and would not be able to get accurate readings inside buildings or if not enough coverage is in your area at the time.

Last know position does not give you your current position, like it says it is the last know position which could have been more than a few minutes ago. Also it could've come from a cell tower reading instead of a GPS reading.

0
votes

I'm using this code

lateinit var fusedLocationProviderClient: FusedLocationProviderClient
lateinit var latitude : Double
lateinit var longitude : Double

    override fun onCreate() {
        super.onCreate()
        fusedLocationProviderClient = FusedLocationProviderClient(this)
        updateLocationTracking()
    }

    @SuppressLint("MissingPermission")
    private fun updateLocationTracking() {
            if(PermissionUtility.isPermissionsGranted(this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                val request = LocationRequest().apply {
                    interval = LOCATION_UPDATE_INTERVAL
                    fastestInterval = FASTEST_LOCATION_INTERVAL
                    priority = PRIORITY_HIGH_ACCURACY
                }
                fusedLocationProviderClient.requestLocationUpdates(
                    request,
                    locationCallback,
                    Looper.getMainLooper()
                )
            } 
    }

    private val locationCallback = object : LocationCallback() {
        override fun onLocationResult(result: LocationResult?) {
            super.onLocationResult(result)
                result?.locations?.let { locations ->
                    for(location in locations) {
                        setLocationData(location)
                    }
                }
        }
   }

    private fun setLocationData(location : Location){
        latitude = location.latitude
longitude = location.longitude

    }

 
}
0
votes

So I figured it out when I couldn't use my phone I use for debugging and used my personal phone for testing, went on the activity and the distances were correct.

Messed around with both debug phone settings and using GPS_PROVIDER and NETWORK_PROVIDER and when my phone used just GPS to get location, it got nothing. Other phone can, so think it's safe to say my debug phone's GPS is borked. It's a old phone that, when I got a new one, I factory reset to use for debugging, as it helped with the backwards compatibility for older phones and smaller screens. I never thought if the actual hardware was faulty too after the reset.

So error was with the phone itself not the app. Guess it goes to show have two devices to test on.