Am I configuring something wrong? - Locationlistener generates erroneous locations

1

Good morning, I am developing an application where I get the user's location through the LocationListener class of Android Java, the problem is that sometimes it locates me correctly, sometimes it locates me to more or less 10 or 20 meters of error (I think that this is normal), but the real problem is that sometimes places me more than 2 or 3 kilometers away from my real position, I'm thinking that maybe I have something wrong configured this is my code:

   /*Metodo de ubicacion de usuarios, listener de cambio de posicion*/
    public void LocListener()
    {
 buscando=true;
        /*Se ejecuta cada vez que hay un cambio en la posicion del usuario*/
        final LocationListener milListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                location.getLatitude();
                location.getLongitude();
                rotacion=location.getBearing();
                posicionUsuario = new LatLng(location.getLatitude(),location.getLongitude());
                    hayUbicacion++;//incrementa en 1 cada vez que se llama a el cambio de posicion
            }

            /*Se ejecuta cada vez que hay un cambio en la configuracion del gps*/
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {
                switch (status) {
                    case LocationProvider.AVAILABLE:
                        Log.d("debug", "LocationProvider.AVAILABLE");
                        break;
                    case LocationProvider.OUT_OF_SERVICE:
                        Log.d("debug", "LocationProvider.OUT_OF_SERVICE");
                        break;
                    case LocationProvider.TEMPORARILY_UNAVAILABLE:
                        Log.d("debug", "LocationProvider.TEMPORARILY_UNAVAILABLE");
                        break;
                }
            }

            @Override
            public void onProviderEnabled(String provider) {
                // Este metodo se ejecuta cuando el GPS es activado
               // mensaje1.setText("GPS Activado");
            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        };

        /*Verificamos que se tengan los permisos antes de comenzar la busqueda de la ubicacion OBLIGATORIO*/
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION,}, 1000);
        }
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, (LocationListener) milListener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, (LocationListener) milListener);
        /*En 5 segundos se verifica si ya se a leido la posicion del usuario 2 veces
        * esto puede ser opcional segun se vea la necesidad de acelerar el proceso
        * de busqueda*/
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                /*Si hay coordenadas entonces apagamos el buscador para evitar bug por tareas largas*/
                if(hayUbicacion>=1) {
                    segundaUbicacion=0;//reiniciamos el contador de busquedas para volver a buscar desde el boton de gps
                    locationManager.removeUpdates(milListener);
                    locationManager = null;
                    //Toast.makeText(MainUsuarios.this, "detiene busqueda", Toast.LENGTH_SHORT).show();
                    buscando=false;
                    progressUbicacion.setVisibility(View.GONE);
                    btnPedirTaxi.setVisibility(View.VISIBLE);
                    animacionCamara();
                    mtdRastreadorConductoresCercanos();
                }
                /*Si no han leido las coordenadas las dos veces entonces reiniciamos la busqueda*/
                else
                {
                    LocListener();
                   // Toast.makeText(MainUsuarios.this, "reinicia"+segundaUbicacion, Toast.LENGTH_SHORT).show();
                }

            }
        },3000);//Valor en milisegundos para el reinicio de la busqueda

    }

If you know any solution or know of some code that works correctly I would appreciate it if you shared it

    
asked by Alvaro Fabian M 24.01.2018 в 20:21
source

1 answer

1

I understand the problem you describe, first you must know the operation of the providers:

  

GPS_PROVIDER: GPS location provider. This provider determines the   location using satellites. Depending on the conditions, this   provider may take a time to return a correction of   location.

     

NETWORK_PROVIDER: network location provider. This provider   determines the location based on the availability of tower   mobile telephony and WiFi hotspots.

If you want an exact position both have an error range , it is regularly asked which one is available, but the most accurate is the GPS.

To make your measurements more accurate, check the method: requestLocationUpdates ()

In your code you are defining:

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, (LocationListener) milListener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, (LocationListener) milListener);
  • The second parameter is the minimum time for updates in Milliseconds.
  • The third parameter is the minimum time for updates in meters.

These are the values that you can modify to obtain a lower error range, for example in the case of NETWORK_PROVIDER ,

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 10, (LocationListener) milListener);

You have defined that every 5 seconds (5000 ms) or every 10 meters get the geolocation update, in the case of only having WiFi on your device you will only use this provider, the option is to update in less time and in a shorter distance.

As everything has a pro and con, you should take into account that if you make more requests in a shorter range of time the battery may run out faster.

    
answered by 24.01.2018 / 21:02
source