how do i solve integrating google map in fragment in android

血红的双手。 提交于 2021-02-07 09:44:01

问题


I have a problem integrating google map in fragment in android. I know how to do it in activity but fragment reference on this site are very old and not working in 2018. I don't have any error.below is fragment file. Any help will be highly appreciated. I have added API key and proper manifest file.

package com.example.narmail.truck30mint.Api.Fragments;

        import android.Manifest;
        import android.content.Context;
        import android.content.DialogInterface;
        import android.content.pm.PackageManager;
        import android.net.Uri;
        import android.os.Bundle;
        import android.support.annotation.NonNull;
        import android.support.v4.app.ActivityCompat;
        import android.support.v4.app.Fragment;
        import android.support.v4.content.ContextCompat;
        import android.support.v7.app.AlertDialog;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.TextView;

        import com.example.narmail.truck30mint.R;
        import com.google.android.gms.maps.CameraUpdateFactory;
        import com.google.android.gms.maps.GoogleMap;
        import com.google.android.gms.maps.MapView;
        import com.google.android.gms.maps.MapsInitializer;
        import com.google.android.gms.maps.OnMapReadyCallback;
        import com.google.android.gms.maps.model.CameraPosition;
        import com.google.android.gms.maps.model.LatLng;
        import com.google.android.gms.maps.model.MarkerOptions;

        import java.util.ArrayList;

        public class ViewTrucksFragment extends Fragment {

            TextView pageTitle;
            MapView mMapView;
            private GoogleMap googleMap;

            public ViewTrucksFragment() {
                // Required empty public constructor
            }

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

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                     Bundle savedInstanceState) {
                // Inflate the layout for this fragment
                View rootView = inflater.inflate(R.layout.fragment_view_trucks, container, false);
                pageTitle = rootView.findViewById(R.id.view_trucks_title);
                String load_id =  getArguments().getString("load_id");
                String load_from = getArguments().getString("load_from");
                String load_to = getArguments().getString("load_to");
                if (load_id != null && load_from != null && load_to != null) {
                    pageTitle.setText("Matching Trucks for "+load_from+" to "+load_to);
                }

                mMapView= rootView.findViewById(R.id.view_trucks_map);
                mMapView.onCreate(savedInstanceState);

                mMapView.onResume();

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

                mMapView.getMapAsync(new OnMapReadyCallback() {
                    @Override
                    public void onMapReady(GoogleMap mMap) {
                        googleMap = mMap;
                        googleMap.getUiSettings().setCompassEnabled(true);
                        googleMap.getUiSettings().setMyLocationButtonEnabled(true);
                        googleMap.getUiSettings().setRotateGesturesEnabled(true);
                        // For dropping a marker at a point on the Map
                        LatLng sydney = new LatLng(30.374219,76.782055);
                        googleMap.addMarker(new MarkerOptions().position(sydney).
                                title("Title").snippet("TitleName"));

                        // 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;
            }
        }

and below is my layout file

<?xml version="1.0" encoding="utf-8"?>
        <FrameLayout 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:background="@color/colorWhite"
            tools:context=".Api.Fragments.ViewTrucksFragment">

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

            <TextView
                android:id="@+id/view_trucks_title"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:textAlignment="center"
                android:layout_marginRight="10dp"
                android:layout_marginLeft="10dp"
                android:padding="10dp"
                android:textColor="@color/colorPrimary"
                android:textSize="15sp"
                android:text="@string/hello_blank_fragment" />

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

           </LinearLayout>

        </FrameLayout>

回答1:


Please follow below step to finish your task. Just need to create 3 files

(1) Create XML layout for map inside your fragment layout fragment_map.xml

<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

(2) Create Fragment to load MAP MapFragment.Java

public class MapFragment extends Fragment implements OnMapReadyCallback {

    private GoogleMap mMap;

    public MapFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_map, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        if(getActivity()!=null) {
            SupportMapFragment mapFragment = (SupportMapFragment) getActivity().getSupportFragmentManager()
                    .findFragmentById(R.id.map);
            if (mapFragment != null) {
                mapFragment.getMapAsync(this);
            }
        }
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        //Do your stuff here
    }
}

(3) Create Activity to load MAP fragment MapsActivity.java

public class MapsActivity extends FragmentActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.content,new MapFragment());
        fragmentTransaction.commit();
    }

}

For MAP key you need to follow same step you have done in your project. Hope this step will help you.

Inside Gradle please use below gradle

implementation 'com.google.android.gms:play-services-maps:15.0.1'

AndroidManifest.xml define below things.

<uses-permission android:name="android.permission.INTERNET"/>

Inside Application Tag.

<meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="YOUR MAP KEY" />


来源:https://stackoverflow.com/questions/51442253/how-do-i-solve-integrating-google-map-in-fragment-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!