【问题标题】:Display google maps inside a fragment在片段内显示谷歌地图
【发布时间】:2020-01-13 07:10:19
【问题描述】:

我正在使用 kotlin,我想在片段内的 androidx 应用程序中实现谷歌地图。

我尝试了 mapView,但在我运行该应用程序时它不显示任何地图。

【问题讨论】:

    标签: google-maps kotlin fragment androidx


    【解决方案1】:

    您可以在活动中使用 mapView 并将片段实现为

        public class SomeFragment extends Fragment {
    
    MapView mapView;
    GoogleMap map;
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)          {
        View v = inflater.inflate(R.layout.some_layout, container, false);
    
        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
    
        // Gets to GoogleMap from the MapView and does initialization stuff
        map = mapView.getMap();
        map.getUiSettings().setMyLocationButtonEnabled(false);
        map.setMyLocationEnabled(true);
    
        // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
        try {
            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        }
    
        // Updates the location and zoom of the MapView
        CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
        map.animateCamera(cameraUpdate);
    
        return v;
    }
    
    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }
    
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
     }
    
     @Override
     public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
      }
    
    }
    

    【讨论】:

    • 上面的答案应该可以代替 map = mapView.getMap();使用 mapView.getAsyncMap(this) 并实现 OnMapReadyCallback 和覆盖方法 @Override public void onMapReady(GoogleMap googleMap) { map = googleMap; map.setMapType(GoogleMap.MAP_TYPE_HYBRID); map.getUiSettings().setAllGesturesEnabled(true); }
    • 这对我不起作用。我实际上只使用片段。当我添加 mapView.onCreate(savedInstanceState) 时,它给了我一个错误“Smartcast 到 mapView 是不可能的,因为它是一个可变属性”
    猜你喜欢
    • 2020-11-15
    • 2018-05-16
    • 2020-02-14
    • 2020-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-09
    • 1970-01-01
    相关资源
    最近更新 更多