【问题标题】:How to use google map in fragment in android?如何在android的片段中使用谷歌地图?
【发布时间】:2016-07-11 11:35:34
【问题描述】:

我正在尝试在片段中使用 google map api,但它总是返回 null。我无法处理它,任何帮助都会得到帮助。有代码;

public class Map extends android.app.Fragment implements OnMapReadyCallback {
    private MapView mMapView;
    private GoogleMap mGoogleMap;
    String response_vehicles;
    Location location;
    float map_zoom=14;
    public Map() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View mapView = inflater.inflate(R.layout.fragment_map, null, false);

        MapFragment mapFragment = (MapFragment) getFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        return mapView;
    }

    @Override
    public void onMapReady(GoogleMap map) {
        map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LatLng sydney = new LatLng(-33.867, 151.206);

        map.setMyLocationEnabled(true);
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 13));

        map.addMarker(new MarkerOptions()
                .title("Sydney")
                .snippet("The most populous city in Australia.")
                .position(sydney));
    }
}

还有xml文件;

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/map"
    tools:context=".Fragments.Map"
    android:name="com.google.android.gms.maps.SupportMapFragment" />

我在 mapFragment.getMapAsync(this) 处给出错误; NullPointerException 我该如何解决这个问题?我认为清单文件和权限是完全正确的。

【问题讨论】:

  • 用 FragmentActivity 扩展类,你应该使用 supportMapFragment
  • 查看本教程 - androidhive.info/2013/08/android-working-with-google-maps-v2 希望对您有所帮助
  • 使用getChilFragmentManager()
  • 但我必须使用片段,因为我使用浮动操作菜单在片段之间传递。
  • Raghunandan 我将其更改为 getChildFragmentManager() 但它仍然给出 null。

标签: java android google-maps android-fragments


【解决方案1】:

这是在片段类中使用地图的解决方案

片段类

public class DemoMapFragment extends Fragment implements OnMapReadyCallback {
    private GoogleMap googleMap;
    private View rootView;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.activity_demo, container, false);
        // Try to obtain the map from the SupportMapFragment.
        SupportMapFragment mapFragment = SupportMapFragment.newInstance();
        getChildFragmentManager().beginTransaction().replace(R.id.map, mapFragment).commit();
        mapFragment.getMapAsync(this);

        return rootView;
    }


    @Override
    public void onMapReady(final GoogleMap googleMap) {
        this.googleMap = googleMap;

    }

}

还有你的 xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_demo"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

【讨论】:

  • 它需要 supportMapFragment 但我使用 android.app.Fragment 我该如何解决这个问题?
  • 片段片段 = null;片段 = 新地图(); FragmentManager fragmentManager = getFragmentManager(); fragmentManager.beginTransaction() .replace(R.id.frame_container, fragment).commit();我正在以这种方式进行片段交易,现在它给出了错误
  • 将其更改为 v4 支持
【解决方案2】:

我使用的是 Android 最新版本。

Android Studio 北极狐 | 2020.3.1

Gradle 版本:7.0.3

这是片段中的地图解决方案。

@Override
public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    binding = FragmentMapBinding.inflate(inflater, container, false);
    View root = binding.getRoot();

    mMapView = binding.mapView;
    mMapView.onCreate(savedInstanceState);
    mMapView.onResume();


    try {
        MapsInitializer.initialize(requireActivity().getApplicationContext());
    } catch (Exception e) {
        e.printStackTrace();
    }

    mMapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap mMap) {
            googleMap = mMap;


            if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                requestPermissions(new String[]{
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                }, 0);
            } else {
                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(15).build();
            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        }
    });

    return root;
}

XML 文件如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.map.MapFragment">

    <com.google.android.gms.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

结果和这张图一样。

enter image description here

【讨论】:

  • 在android最新版本中,使用了View Binding。
猜你喜欢
  • 1970-01-01
  • 2020-12-21
  • 2017-08-16
  • 1970-01-01
  • 2013-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多