Reputation: 81
I'm confused about how to get my location when clicking a button.
I was trying with my code below:
private void showMyLocation() {
FusedLocationProviderApi fusedLocationApi = LocationServices.FusedLocationApi;
Location location = fusedLocationApi.getLastLocation(googleApiClient);
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLng(latLng);
map.animateCamera(cameraUpdate);
}
and the result is a force close app. I can't read logcat , because logcat is gone when the app crashes.
Are there any suggestions?
Upvotes: 0
Views: 111
Reputation: 143
Firstly create Location mLocation
as globally then inside onLocationChanged
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;}
then
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
btn = findViewById(R.id.btn);
// add code
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mLastLocation != null) {
LatLng latLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
lat = mLastLocation.getLatitude();
Log.d("MapActivity", "lat of current" + lat);
lng = mLastLocation.getLongitude();
Log.d("MapActivity", "lng of current" + lng);
if (marker != null) {
marker.remove();
}
marker = mMap.addMarker(new MarkerOptions()
.position(latLng)
.title("You are here!!!")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.a1)));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
}
}
}
});
Upvotes: 1