Google地图的坑SupportMapFragment.getmap() returns null

在项目中用到了google地图,要定位到相应的地址,添加一个marker图片在上面:
1.先去google地图获取秘钥。

2.在AndroidManifest上面添加申请到的key和添加权限:

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="@string/map_signing_key"/>

权限:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

先说说在FragmentActivity上使用吧,
xml:

<fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

代码:

public class TestMapDemo extends FragmentActivity {

private GoogleMap googleMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testmap);

MapsInitializer.initialize(this);
initilizeMap();
}

private void initilizeMap() {
try {
if (googleMap == null) {

googleMap = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
if (googleMap == null) {
Toast.makeText(this,
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
// marker(lat, lng);
marker(-27.47093, 153.0235);

}
} catch (Exception e) {
e.printStackTrace();
}
}

public void marker(double Lat, double Long) {
LatLng curLocation = new LatLng(Lat, Long);
googleMap.addMarker(new MarkerOptions()
.position(curLocation)
.title("GoogleMap")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.icon_location)));
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(
curLocation, 13);
googleMap.animateCamera(cameraUpdate);
}

}


这样是根据经纬度直接定位到那个位子然后显示一个marker图在上面,这是是没问题的。
然后在项目中是要在fragment上面用google地图的,结果发现
报错SupportMapFragment.getmap() returns null

得到地图fragment的实例,原来的使用是这样的:
getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

在fragment里面使用就会出现上面的那个return null了

找了很久的问题,原来是要改成这样才显示成功:
getChildFragmentManager().findFragmentById(R.id.map)).getMap();

这也是遇到的坑,记录一下


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值