androidgoogle-mapssupportmapfragment

Show a google map inside a dialogfragment in a fragment


I want to load a map inside a dialog fragment that is loaded from a fragment.

When I do this using an activity, it is working fine, the map is displayed and it is fully functioning. However, when I do this inside a fragment, the map only shows a grey fragment with a google logo on the bottom left.

I have browsed everywhere and almost got a similar answer for checking my google API key. However, the API key is just working fine with the other project. I also tried changing it, but of no help.

Here is my code: map_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="@color/colorPrimary">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Choose your location"
            android:textAlignment="center"
            android:padding="10dp"
            android:textAppearance="@style/TextAppearance.AppCompat.Headline" />
    </RelativeLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="10dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_marginRight="20dp"
            android:text="Long click the marker pin or click anywhere on map"
            android:textAlignment="center"
            android:textSize="18dp" />

        <ScrollView android:id="@+id/ScrollView01"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:orientation="vertical"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <fragment xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="match_parent"
                    android:layout_height="250dp"
                    android:id="@+id/map"
                    tools:context=".ngo.NgoHomeActivity"
                    android:name="com.google.android.gms.maps.SupportMapFragment"
                    android:layout_marginTop="15dp"/>

                <customfonts.MyEditText
                    android:layout_marginTop="10dp"
                    android:padding="20dp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:textColorHint="#000"
                    android:textColor="#000"
                    android:inputType="textMultiLine"
                    android:textSize="16dp"
                    android:hint="Address"
                    android:id="@+id/etAddress"/>
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:textSize="16dp"
                    android:id="@+id/btnSaveAddress"
                    android:text="SAVE ADDRESS"
                    android:background="@drawable/angle"
                    android:textColor="#fff"
                    android:gravity="center"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:padding="5dp"
                    android:layout_alignParentBottom="true"
                    android:layout_marginBottom="20dp"
                    android:layout_marginTop="10dp"/>
            </LinearLayout>

        </ScrollView>

    </LinearLayout>
</LinearLayout>

MapDialogFragment.java


public class MapDialogFragment extends DialogFragment implements OnMapReadyCallback{
    Address address;
    StringBuffer addressDetails;
    List<Address> addresses;
    GoogleMap mMap;
    Marker marker;

    Location currentLocation;
    LatLng latLng;
    FusedLocationProviderClient fusedLocationProviderClient;
    private static final int REQUEST_CODE = 101;
    double latitude, longitude;
    String nAddLine2;
    View rootView;
    EditText edAddress;
    Button btnSaveAdd;
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_map_dialog,container,false);
        edAddress = rootView.findViewById(R.id.etAddress);
        btnSaveAdd = rootView.findViewById(R.id.btnSaveAddress);
        btnSaveAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getDialog().dismiss();
            }
        });
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
        fetchLastLocation();
        return rootView;
    }
    @Override
    public void onMapReady(GoogleMap googleMap) {
        latLng = new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude());
        mMap = googleMap;
        CameraPosition newCamPos = new CameraPosition(latLng,
                15.5f,
                mMap.getCameraPosition().tilt, //use old tilt
                mMap.getCameraPosition().bearing); //use old bearing
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(newCamPos), 4000, null);
//        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,10));
        Toast.makeText(getContext(), latLng.toString(),Toast.LENGTH_LONG).show();

        mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {

            }

            @Override
            public void onMarkerDrag(Marker marker) {

            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                Geocoder geocoder = new Geocoder(getContext(), Locale.getDefault());
                try{
                    latitude = marker.getPosition().latitude;
                    longitude = marker.getPosition().longitude;
                    addresses = geocoder.getFromLocation(latitude, longitude, 1);
                }catch (Exception IOException) {
                    IOException.printStackTrace();
                    Log.d("Error Message:", IOException.getMessage());
                    Log.e("", "Error in getting address for the location");
                    Toast.makeText(getContext(), "Couldn't get address",Toast.LENGTH_SHORT).show();
                }

                if(addresses == null || addresses.size() == 0){
                    Log.e("","Error in getting address for the location");

                }else{
                    String receivedAddress = getAddress();
                    showResults(receivedAddress);
                    mMap.animateCamera(CameraUpdateFactory.newLatLng(marker.getPosition()));
                }
            }
        });
        marker = mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(true));
    }

    private void fetchLastLocation() {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE);
            return;
        }
        Task<Location> task = fusedLocationProviderClient.getLastLocation();
        task.addOnSuccessListener(new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                if (location != null) {

                    currentLocation = location;
//                    Toast.makeText(getContext(), location.toString(),Toast.LENGTH_LONG).show();
                    SupportMapFragment supportMapFragment = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
                    supportMapFragment.getMapAsync(MapDialogFragment.this);
                }
            }
        });
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case REQUEST_CODE:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    fetchLastLocation();
                }
        }
    }

    public String getAddress(){

    }

    private void showResults(String currentAdd) {


    }
}

and the button clcik event from fragment that launched the dialog fragment:

edNAddLine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new MapDialogFragment().show(getFragmentManager(),null);
            }
        });

Can anyone help?


Solution

  • Finally resolved the problem on my own. The problem was with the fragment only. Because I tried launching the map inside an activity and it was working just fine.

    For anyone who encounters the problem, I changed the following statement:

    dialogFragment.show(Objects.requireNonNull(getFragmentManager()),null);
    

    Where the key was: Objects.requireNonNull(getFragmentManager).

    I don't know however, what does that do. Answers appreciated.