I trying to get the devices location, but the TomtomMap.getUsersLocation() is always returning null.
The wired thing is that since i set TomtomMap.setMyLocationEnabled(true) the map marks the user location correctly, but when i try to get it for my self it returns null.
I followed the documentation on how to do it, it was very simple to follow, it just does not work. I also checked the answer below, but it is just a copy of the docs.
It's hard to guess without looking at the code, but most probably you are trying to get user location too early when GPS position is not yet available (perhaps inside onMapReady
callback).
To make sure that you are getting the user location as quick as possible you can override the onLocationChanged
callback.
Please find an example activity code below:
public class MainActivity extends AppCompatActivity implements LocationUpdateListener, OnMapReadyCallback {
private TomtomMap map;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Register onMapReady callback
MapFragment mapFragment = (MapFragment) getSupportFragmentManager().findFragmentById(R.id.map_fragment);
mapFragment.getAsyncMap(this);
}
@Override
public void onMapReady(@NonNull TomtomMap tomtomMap) {
this.map = tomtomMap;
// Enable location and register location listener callback
this.map.setMyLocationEnabled(true);
this.map.addLocationUpdateListener(this);
}
// Forward permissions callbacks
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
this.map.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
@Override
public void onLocationChanged(Location location) {
// Use map.getUserLocation() without getting NULL
Toast.makeText(this, this.map.getUserLocation().toString(), Toast.LENGTH_SHORT).show();
// Remove location listener if needed
this.map.removeLocationUpdateListener(this);
}
}