java - GOOGLE MAPS API - 如何在没有 map.setMyLocationEnabled(boolean) 的情况下获取我的位置?

标签 java android google-maps

我对如何在单击按钮时获取我的位置感到困惑。

我正在尝试使用下面的代码:

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/

相关文章:

java - 油漆组件是如何工作的?

java - 相对布局以编程方式添加一个 View ,另一个 View 未正确对齐

android - 在折叠工具栏布局中添加 FloatingActionButton

android - 如何在两个进程之间共享数据

android - Google Play 服务和 Google Maps Android API 版本 2,授权失败

java - 贾斯珀报告 : wrong positioning of text fields in Internet Explorer

java - Future中的get方法在java中是如何工作的?

android - Zygote The String#value field is not present on Android versions >= 6.0 Android 错误

java - CF 中的十六进制对象

Android 不同的屏幕尺寸