我一直在研究谷歌地图,下面是我用来初始化地图的方法。令人惊讶的是,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");
}
请注意,getMapAsync中的Log语句永远不会执行。任何人都可以帮我这个吗?
修改
有人将此问题标记为What is a NullPointerException, and how do I fix it?的副本请注意这个问题是关于getMapAync()如何以及何时调用onMapReady()方法(它与空指针异常无关)
答案 0 :(得分:2)
您应该在googleMap
方法中移动使用变量onMapReady(...) { ... }
的代码,因为getMapAsync(...)
是异步的,onMapReady(...)
稍后会在地图响应后在另一个线程中调用。< / p>