我知道这个问题已经被问过几次了,但是通过查看它们我找不到解决方案。我已经创建了一个导航抽屉。导航抽屉自然有助于切换片段。在一个这样的片段中,我想显示一个谷歌地图。
map_fragment.xml:
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
MapFragment:
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
public class MapFragment extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.map_fragment, container, false);
GoogleMap map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
return view;
}
}
该行:
GoogleMap map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
始终显示:
无法从Fragment投射到SupportMapFragment
我不确定为什么会出现这种情况?我要去哪里错了?我已经在清单中提供了所有必需的权限,因为我能够在其他活动中看到google map。
最佳答案
这是使用google map的最佳实践,请尝试一下。
public class MapFragment extends Fragment implements OnMapReadyCallback{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.map_fragment, container, false);
// GoogleMap map = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
MapFragment map = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
map.getMapAsync(this);
return view;
}
@Override
public void onMapReady(GoogleMap googleMap) {
//googleMap is your map
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
gm = googleMap;
googleMap.setOnMarkerClickListener(this);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(Ancona, 5));
}
}
关于java - 无法在 fragment 内使用Google Map V2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29006458/