getMapAsync()没有给onMapReady()回调以初始化googleMap对象

时间:2018-01-12 20:34:18

标签: java android google-maps

我一直在研究谷歌地图,下面是我用来初始化地图的方法。令人惊讶的是,mapFragment.getMapAsync()方法没有被执行,因此在调用getMapAsync()之后googleMaps对象仍为null。

// Initialize the google map

void initMap() {
    Log.d(MAPSACTIVITY_TAG, "Initializing google map");
    mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.maps_fragment);
    mapFragment.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap gMap) {
            Log.d(MAPSACTIVITY_TAG,"Maps is ready");
            googleMap=gMap;
        }
    });

    Log.d(MAPSACTIVITY_TAG,"Value of google maps is "+googleMap);

    //This will get device location, set GoogleAPIClient and set mundu marker
    if (isLocationPermissionGranted) {
        getDeviceLocation();
        buildGoogleApiClient();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(context, "Sorry! App requires location permission", Toast.LENGTH_SHORT).show();
            return;
        }
        googleMap.setMyLocationEnabled(true);
        //this will get client's location and set client's marker
        geoLocateClient();
    } else
        Log.d(MAPSACTIVITY_TAG, "Location permission is not given");
}

以下是Logcat快照:enter image description here

请注意,getMapAsync中的Log语句永远不会执行。任何人都可以帮我这个吗?

修改

有人将此问题标记为What is a NullPointerException, and how do I fix it?的副本请注意这个问题是关于getMapAync()如何以及何时调用onMapReady()方法(它与空指针异常无关

1 个答案:

答案 0 :(得分:2)

您应该在googleMap方法中移动使用变量onMapReady(...) { ... }的代码,因为getMapAsync(...)是异步的,onMapReady(...)稍后会在地图响应后在另一个线程中调用。< / p>