public class OutdoorFragment extends Fragment {
private GoogleMap googleMap;
double latitude = 1.31039;
double longitude = 103.7784;
public OutdoorFragment() {
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_outdoor, container,
false);
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
googleMap.getUiSettings().setZoomGesturesEnabled(true);
googleMap.getUiSettings().setRotateGesturesEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
googleMap.setMyLocationEnabled(true);
// create marker
MarkerOptions marker = new MarkerOptions().position(
new LatLng(latitude, longitude)).title("Koh Chi Hao ");
// adding marker
marker.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET));
googleMap.addMarker(marker);
return rootView;
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getActivity().getApplicationContext(),
"Sorry! unable to create maps", Toast.LENGTH_SHORT)
.show();
}
}
}
@Override
public void onResume() {
super.onResume();
initilizeMap();
}
}
您好,在initializeMap()
内,googleMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
继续说Cannot cast from Fragment to SupportMapFragment
。我不确定发生了什么。
提前致谢
答案 0 :(得分:1)
您需要使用android.support.v7.app.Fragment;
需要使用getSupportFragmentManager
基本上你需要v7库
答案 1 :(得分:1)
更改;
googleMap = ((SupportMapFragment) getFragmentManager().
findFragmentById(R.id.map)).getMap();
有了这个;
googleMap = ((SupportMapFragment) getSupportFragmentManager().
findFragmentById(R.id.map)).getMap();
请注意,getSupportFragmentManager
来自 android.support.v4.app.FragmentActivity 。
答案 2 :(得分:1)
检查您的活动布局。带有map的片段必须具有以下属性name="com.google.android.gms.maps.SupportMapFragment"
,以指示您使用的片段类。