我对如何在单击按钮时获取我的位置感到困惑。
我正在尝试使用下面的代码:
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);
}
结果是强制关闭应用程序。我无法读取 logcat ,因为当应用程序崩溃时 logcat 就消失了。
有什么建议吗?
最佳答案
首先全局创建Location mLocation
,然后在onLocationChanged内创建
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;}
然后
@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));
}
}
}
});
关于java - GOOGLE MAPS API - 如何在没有 map.setMyLocationEnabled(boolean) 的情况下获取我的位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60222911/