java - 我无法在片段中显示地图
问题描述
我想在我的地图中显示带有标记的地图,MainActivity
但它没有显示任何地图,似乎在我运行应用程序时它不存在。
Fragment
我有一个activity_main
这样的:
<com.google.android.gms.maps.MapView
android:id="@+id/mapVieww"
android:layout_width="match_parent"
android:layout_height="400dp" />
和这样的 ia.java
文件:
public class MapViewFragment extends Fragment{
MapView mMapView;
private GoogleMap googleMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container, false);
mMapView = rootView.findViewById(R.id.mapVieww);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For showing a move to my location button
//googleMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}}
我在互联网上找到了信息。有谁知道错在哪里?
解决方案
首先删除你的try-catch,MapsInitializer.initialize(getActivity().getApplicationContext());
因为:
如果您正在使用 MapFragment 或 MapView 并且已经通过在这些类中调用 getMapAsync() 并等待 onMapReady(GoogleMap map) 回调获得(非空)GoogleMap,那么您无需担心此类。有关一些示例,请参阅示例应用程序。来自文档 - https://developers.google.com/android/reference/com/google/android/gms/maps/MapsInitializer
其次,mMapView.getMapAsync(this);
使用地图制作和移动您的工作以实施OnMapReadyCallback
第三:你是什么意思 -mMapView.onResume(); // needed to get the map to display immediately
为什么需要?
您在哪个设备上尝试?虚拟的还是真实的?
推荐阅读
- javascript - 如何在 Javascript 中将 Switch() 与 IF 语句一起使用?
- c++ - 递归尾部消除,影响时间?
- pandas - 仅针对组中选定成员的回填值 - pandas
- ansible - 如何从 terraform 模块调用 ansible 角色
- c++ - GetPixel 函数在句柄中获取值时返回不正确的值
- ruby-on-rails - Rails 协会问题
- tsql - 如果表为空且具有前 1000 个结果,则进行内部联接
- python - 加载模型 Allennlp
- angular - 如何使用 ngx-extended-pdf-viewer 显示本地 pdf?
- python - Discord.py 意外缩进