Why is the marker placed at the wrong coordinates?

Asked

Viewed 46 times

1

I want to do a program that puts a marker where the phone is. In the case, I put the latitude and longitude of a city in Greenland, but the value of the final location is (37.42342342342342, -122.08395287867832), the coordinates of Google’s Headquarters. What I need to put on my show?

@Override
public void onMapReady(GoogleMap googleMap) {

    mMap = googleMap;
    manager = (LocationManager) getSystemService(Service.LOCATION_SERVICE);
   String teste =  manager.getBestProvider(criteria, false);
   Log.i("testando", ""+teste);
    provedor = LocationServices.getFusedLocationProviderClient(this); // Necessário para iniciar o provedor

    @SuppressLint("MissingPermission") Task task =  provedor.getLastLocation();
    task.addOnSuccessListener(this, new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            if (location != null) {

                longitude = location.getLongitude();
                latitude = location.getLatitude();
                Log.i("teste", "pos "+ latitude + "  " + longitude);
                LatLng sydney = new LatLng(latitude, longitude);
                mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
            } else { // Ao que tudo indica, a localização não é nula
                Toast.makeText(getApplicationContext(), "ERRO!", Toast.LENGTH_LONG).show();
            }
        }
    });

1 answer

1

The reason is that the method is being used getLastLocation().
The method returns the last location known(by the previous). It may not match the current location.

To ensure you get an up-to-date location you should use a Locationrequest in conjunction with Fusedlocationclient, using the method mFusedLocationClient.requestLocationUpdates().
Look at this reply an example of how to do.

To verify that this is the reason run any application, existing on the device, that uses your location, such as Google Maps.
This application will ask the provider for the current location, which will be the last known.

Re-run your application which, since the provider will now have the updated location, will place the marker in the expected location.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.