How to get Google Maps object inside a Fragment

前端 未结 7 1909
走了就别回头了
走了就别回头了 2021-02-19 01:26

I am using fragments in my application and I am new for this. There is a fragment in which I want to display Google Map and want to get its object, for this I have a fragment in

相关标签:
7条回答
  • 2021-02-19 01:53
    <fragment
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:id="@+id/location_map"
        android:layout_above="@id/atmLocation_recyclerView"
        />
    
    View root= inflater.inflate(R.layout.fragment_a_t_m_locations, container, false);
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.location_map);
        mapFragment.getMapAsync(googleMap -> {
            mMap=googleMap;
            if(mMap!=null){
                mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            }
        });
    
    0 讨论(0)
  • 2021-02-19 01:53

    getMap() method is deprecated

    getMap() method is deprecated but after the play-services 9.2it is removed, so better use getMapAsync(). You can still use getMap() only if you are not willing to update the play-services 9.2 for your app.

    To use getMapAsync(), implement the OnMapReadyCallback interface on your activity or fragment:

    For fragment:

    public class MapFragment extends android.support.v4.app.Fragment
          implements OnMapReadyCallback { /* ... */ }
    

    Then, while initializing the map, use getMapAsync() instead of getMap():

    //call this method in your onCreateMethod
     private void initializeMap() {
      if (mMap == null) {
        SupportMapFragment mapFrag = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.fragment_map);
        mapFrag.getMapAsync(this);
      }
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        setUpMap();// do your map stuff here
    }
    

    For Activity:

    public class MapActivity extends FragmentActivity
          implements OnMapReadyCallback { }
    Then, while initializing the map, use getMapAsync() instead of getMap():
    
    
    //call this method in your onCreateMethod
     private void initializeMap() {
      if (mMap == null) {
        SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_map);
        mapFrag.getMapAsync(this);
      }
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        setUpMap();// do your map stuff here
    }
    

    Fragment in XML:

       <fragment  xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/map"
            android:name="com.google.android.gms.maps.SupportMapFragment"
            android:layout_width="match_parent"
            android:layout_height="match_parent"/>
    
    0 讨论(0)
  • 2021-02-19 02:02
    public class MapActivity extends FragmentActivity
          implements OnMapReadyCallback { }
    Then, while initializing the map, use getMapAsync() instead of getMap():
    
    
    //call this method in your onCreateMethod
     private void initializeMap() {
      if (mMap == null) {
        SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment_map);
        mapFrag.getMapAsync(this);
      }
    }
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    
    }
    

    You can use this to making map but it will return map object is null because you don't find solution with getMapAsync to create a new object mMap. It only background task with return null

    0 讨论(0)
  • 2021-02-19 02:07

    Revised code:

    Your xml file-

     <fragment 
          android:name="com.google.android.gms.maps.SupportMapFragment"
          android:id="@+id/map"
          android:layout_width="match_parent"
          android:layout_height="match_parent"/>
    

    Your java file (only relevant code)-

    View  view = null, mapView = null;
    private GoogleMap mMap;
    
    view = inflater.inflate(R.layout.findmycar, container,false);
    FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
                    .findFragmentById(R.id.map);
    
    mMap = supportMapFragment.getMap();
    mapView = (View) view.findViewById(R.id.map);
    
    0 讨论(0)
  • 2021-02-19 02:08

    Try this

     GoogleMap map = ((SupportMapFragment) getFragmentManager()
                    .findFragmentById(R.id.map)).getMap();
    

    and in your xml

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.gms.maps.SupportMapFragment" />
    
    0 讨论(0)
  • 2021-02-19 02:10

    Try this i have made this as a sample according to your need

    public class LocationMapActivity extends FragmentActivity {
        private GoogleMap mMap;
        static boolean Iscamera = false;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            setContentView(R.layout.locatio_map);
    
            setUpMapIfNeeded();
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            setUpMapIfNeeded();
    
        }
    
        private void setUpMapIfNeeded() {
    
            if (mMap == null) {
    
                // Try to obtain the map from the SupportMapFragment.
                mMap = ((SupportMapFragment) getSupportFragmentManager()
                        .findFragmentById(R.id.map)).getMap();
                mMap.setMyLocationEnabled(true);
    
                if (mMap != null) {
    
                    mMap.setMyLocationEnabled(true);
                    mMap.getUiSettings().setCompassEnabled(true);
                    mMap.getUiSettings().setZoomControlsEnabled(true);
                    mMap.getMaxZoomLevel();
                    mMap.getMinZoomLevel();
                    mMap.getUiSettings();
                    mMap.animateCamera(CameraUpdateFactory.zoomIn());
                    mMap.animateCamera(CameraUpdateFactory.zoomOut());
                    mMap.animateCamera(CameraUpdateFactory.zoomTo(20));
    
                    mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
                        @Override
                        public void onMyLocationChange(Location arg0) {
                            // TODO Auto-generated method stub
    
                            mMap.clear();
                            mMap.addMarker(new MarkerOptions()
                            .position(
                                    new LatLng(arg0.getLatitude(), arg0
                                            .getLongitude()))
                            .title("I am Here!!")
                            .icon(BitmapDescriptorFactory
                                    .fromResource(R.drawable.map_icon)));
                            if (!Iscamera) {
                                mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                        new LatLng(arg0.getLatitude(), arg0
                                                .getLongitude()), 14));
    
    
                                Iscamera = true;
                            }
                            try {
    
                                if (Constant.FORTNAME.equals("Arad Fort")) {
                                    mMap.addMarker(new MarkerOptions()
                                            .position(new LatLng(26.2525, 50.6269))
                                            .title(Constant.FORTNAME)
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.greenicon)));
    
                                } else if (Constant.FORTNAME.equals("Bahrain Fort")) {
                                    mMap.addMarker(new MarkerOptions()
                                            .position(
                                                    new LatLng(26.2333598,
                                                            50.52035139))
                                            .title(Constant.FORTNAME)
    
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.greenicon)));
                                } else if (Constant.FORTNAME
                                        .equals("International Circuit")) {
                                    mMap.addMarker(new MarkerOptions()
                                            .position(
                                                    new LatLng(26.0303251,
                                                            50.51121409))
                                            .title(Constant.FORTNAME)
    
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.greenicon)));
    
                                } else if (Constant.FORTNAME
                                        .equals("Khamis Mousque")) {
                                    mMap.addMarker(new MarkerOptions()
                                            .position(
                                                    new LatLng(26.158719, 50.516426))
                                            .title(Constant.FORTNAME)
    
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.greenicon)));
    
                                } else if (Constant.FORTNAME
                                        .equals("king fahad causeway")) {
                                    mMap.addMarker(new MarkerOptions()
                                            .position(
                                                    new LatLng(26.1723987,
                                                            50.4579942))
                                            .title(Constant.FORTNAME)
    
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.greenicon)));
    
                                } else if (Constant.FORTNAME.equals("Riffa Fort")) {
                                    mMap.addMarker(new MarkerOptions()
                                            .position(
                                                    new LatLng(26.11771965026855,
                                                            50.56298065185547))
                                            .title(Constant.FORTNAME)
    
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.greenicon)));
    
                                } else if (Constant.FORTNAME
                                        .equals("Royal Golf Club")) {
                                    mMap.addMarker(new MarkerOptions()
                                            .position(
                                                    new LatLng(26.13000, 50.55500))
                                            .title(Constant.FORTNAME)
    
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.greenicon)));
    
                                } else if (Constant.FORTNAME.equals("Tree of life")) {
                                    mMap.addMarker(new MarkerOptions()
                                            .position(
                                                    new LatLng(25.9940396,
                                                            50.583135500000026))
                                            .title(Constant.FORTNAME)
    
                                            .icon(BitmapDescriptorFactory
                                                    .fromResource(R.drawable.greenicon)));
    
                                }
    
                            } catch (Exception e) {
                                Toast.makeText(getApplicationContext(),
                                        e.getMessage(), Toast.LENGTH_LONG).show();
                                Log.e(e.getClass().getName(), e.getMessage(), e);
                            }
    
                        }
                    });
    
                }
            }
    
        }
    
        // ********************************************************************************************
        @SuppressWarnings("unused")
        private void setUpMap() {
    
            mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title(
                    "Marker"));
        }
    }
    
    0 讨论(0)
提交回复
热议问题