首页 > 解决方案 > 我无法在片段中显示地图

问题描述

我想在我的地图中显示带有标记的地图,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;
}}

我在互联网上找到了信息。有谁知道错在哪里?

标签: javaandroidandroid-studiomaps

解决方案


首先删除你的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为什么需要?

您在哪个设备上尝试?虚拟的还是真实的?


推荐阅读