我想在MainActivity
中显示一个带有标记的地图,但它没有显示任何地图,当我运行应用程序时,它似乎不存在。
我的activity_main
中有一个Fragment
,如下所示:
<com.google.android.gms.maps.MapView
android:id="@+id/mapVieww"
android:layout_width="match_parent"
android:layout_height="400dp" />
我有一个像这样的.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;
}}
我在网上找到了这些信息。谁知道哪里出了错?
首先用MapsInitializer.initialize(getActivity().getApplicationContext());
删除您的try-catch,因为:
如果您正在使用MapFragment或MapView,并且已经通过对这两个类中的任何一个调用getMapAsync((并等待onMapReady(GoogleMap map(回调获得了一个(非null(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
?
你在哪台设备上试用?虚拟的还是真实的?