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
。我不確定發生了什麼事。 在此先感謝
它可能與您在佈局上定義的片段類有關。你能不能顯示你的R.layout.fragment_outdoor文件? – joao2fast4u 2014-10-01 09:10:47
您是否使用'support library'中的'Fragments'而不是'android.app.'?活動是「FragmentActivity」還是「ActionBarActivity」? – EpicPandaForce 2014-10-01 09:11:50
嘗試使用'googleMap =((SupportMapFragment)getSupportFragmentManager()。findFragmentById(R.id.map))。getMap(); '而不是 – joao2fast4u 2014-10-01 09:13:40