有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在片段中使用谷歌地图视图?

期望的行为

如果它影响到任何答案或建议,我希望最终在这个应用程序中看到的是一个导航UI,其中一个Fragment是一个地图。我使用一个模板以一个导航UI开始,它给了我几个Fragment,每个选项卡一个。目前,我正在尝试使用Google API在其中一个Fragment中放置一个MapView

当前行为

一般来说,这是行不通的(显然)。我已经启动并运行了一切,但当我打开带有地图的选项卡时,地图是空白的。没有崩溃,也没有输出错误:

I/Google Maps Android API: Google Play services client version: 12451000
I/Google Maps Android API: Google Play services package version: 201516040
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/DynamiteModule: Considering local module com.google.安卓.gms.googlecertificates:0 and remote module com.google.安卓.gms.googlecertificates:4
    Selected remote version of com.google.安卓.gms.googlecertificates, version >= 4

其他详细信息/故障排除

我知道我的API密钥可以工作,因为我有另一个应用程序,其中的地图可以按预期工作。我怀疑我是否需要第二个API密钥,但我还是看了看,因为如何创建第二个API密钥并不太明显,我认为直觉是正确的。我使用的大部分代码都是从那个工作示例中复制的;主要区别在于,其他示例使用了SupportMapFragment,并且它有一个class MapsActivity extends FragmentActivity。在这里,因为我不想处理嵌套片段,所以我尝试在片段内部使用MapView

我的代码中没有被复制的部分主要来自在线资源。我所做的一切都没有产生更好的效果

MapView inside fragment回答了一个不同的问题

Creating google maps v2 in a fragment using Navigation Drawer只包含我已经拥有的东西

安卓 MapView in Fragment给了我使用MapsInitializer.initialize(this.getActivity());的想法,但那没有帮助

Mapview in separate fragment 安卓没有什么新鲜事

how do i solve integrating google map in fragment in 安卓使用Fragment而不是MapView

我还知道onMapReady正在被调用。在这里面,我移动相机,然后调用^{。但是,它不输入onCameraMoveonCameraIdle

密码

这就是代码,它使用了上面链接中的一些想法。我试图删掉任何不相关的东西(其他碎片等)

AndroidManifest。xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    package="com.example.retailtherapy">

    <uses-permission 安卓:name="安卓.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission 安卓:name="安卓.permission.ACCESS_FINE_LOCATION" />
    <uses-permission 安卓:name="安卓.permission.INTERNET" />

    <application
        安卓:allowBackup="true"
        安卓:icon="@mipmap/ic_launcher"
        安卓:label="@string/app_name"
        安卓:roundIcon="@mipmap/ic_launcher_round"
        安卓:supportsRtl="true"
        安卓:theme="@style/AppTheme">

        <meta-data
            安卓:name="com.google.安卓.geo.API_KEY"
            安卓:value="@string/google_maps_key" />

        <activity
            安卓:name=".MainActivity"
            安卓:label="@string/app_name"
            安卓:windowSoftInputMode="stateVisible|adjustResize" >
            <intent-filter>
                <action 安卓:name="安卓.intent.action.MAIN" />

                <category 安卓:name="安卓.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

    <uses-feature
        安卓:glEsVersion="0x00020000"
        安卓:required="true"/>

</manifest>

主要活动。xml

<安卓x.constraintlayout.widget.ConstraintLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:id="@+id/container"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent">

    <com.google.安卓.material.bottomnavigation.BottomNavigationView
        安卓:id="@+id/nav_view"
        app:menu="@menu/bottom_nav_menu" />

    <fragment
        安卓:id="@+id/nav_host_fragment"
        安卓:name="安卓x.navigation.fragment.NavHostFragment"
        app:defaultNavHost="true"
        app:navGraph="@navigation/mobile_navigation"
        tools:context=".MainActivity" />

</安卓x.constraintlayout.widget.ConstraintLayout>

移动导航。xml

<navigation xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:id="@+id/mobile_navigation"
    app:startDestination="@+id/navigation_map">

    <fragment
        安卓:id="@+id/navigation_map"
        安卓:name="com.example.retailtherapy.ui.map.MapFragment"
        安卓:label="Map"
        tools:layout="@layout/fragment_map" />

</navigation>

碎片与地图。xml


<RelativeLayout
    xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
    xmlns:app="http://schemas.安卓.com/apk/res-auto"
    xmlns:tools="http://schemas.安卓.com/tools"
    安卓:layout_width="match_parent"
    安卓:layout_height="match_parent"
    tools:context=".ui.map.MapFragment" >

    <com.google.安卓.gms.maps.MapView
        安卓:id="@+id/googleMap"
        安卓:layout_width="match_parent"
        安卓:layout_height="match_parent" />

</RelativeLayout>

地图碎片。java

public class MapFragment extends Fragment implements OnMapReadyCallback, LocationListener {

    /*************************************************************************
     *
     * M E M B E R S
     *
     */

    // Location manager for getting current location
    private LocationManager mLocationManager = null;

    // The map object for reference for ease of adding points and such
    private GoogleMap mGoogleMap = null;
    private MapView mMapView = null;

    // The camera position tells us where the view is on the map
    private CameraPosition mCameraPosition = Constants.GetDefaultCameraPosition();

    // Current latitude and longitude of user
    private LatLng mCurrentLatLong = new LatLng(0.0, 0.0);

    // These are flags that allow us to selectively not move the camera and
    // instead wait for idle so the movement isn't jerky
    private boolean mCameraMoving = false;
    private boolean mPendingUpdate = false;

    /*************************************************************************
     *
     * F R A G M E N T
     *
     */

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

        super.onCreateView(inflater, container, savedInstanceState);
        View root = inflater.inflate(R.layout.fragment_map, container, false);

        // The google map...
        MapsInitializer.initialize(getActivity());
        mMapView = (MapView) root.findViewById(R.id.googleMap);
        mMapView.onCreate(savedInstanceState);
        mMapView.getMapAsync(this);

        // The required permissions...
        final String[] REQUIRED_PERMISSIONS = {
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.INTERNET,
        };
        requestPermissions(REQUIRED_PERMISSIONS, 0);

        return root;
    }

    @Override
    public void onStart() throws SecurityException {
        super.onStart();

        // Location manager for getting info current location
        mLocationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mMapView.onDestroy();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mMapView.onSaveInstanceState(outState);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mMapView.onLowMemory();
    }

    /*************************************************************************
     *
     * G O O G L E   M A P S
     *
     */

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

        // Assuming if here that we have permissions okay.  Dangerous sure
        // but I'm lazy...
        mGoogleMap.setMyLocationEnabled(true);

        // Store the location of the camera for UI purposes so we can go
        // back to where we were
        mGoogleMap.setOnCameraMoveListener(new GoogleMap.OnCameraMoveListener() {
            @Override
            public void onCameraMove() {
                mCameraPosition = mGoogleMap.getCameraPosition();
            }
        });
        mGoogleMap.setOnCameraMoveStartedListener(new GoogleMap.OnCameraMoveStartedListener() {
            @Override
            public void onCameraMoveStarted(int i) {
                mCameraMoving = true;
            }
        });
        mGoogleMap.setOnCameraIdleListener(new GoogleMap.OnCameraIdleListener() {
            @Override
            public void onCameraIdle() {
                mCameraMoving = false;
                if (mPendingUpdate) {
                    centerCameraOnLocation(false);
                }
            }
        });

        // Start with user centered in view
        centerCameraOnLocation(true);
    }

    /*************************************************************************
     *
     * L O C A T I O N
     *
     */

    @Override
    public void onLocationChanged(Location location) {
        // Store the current location so if we start auto-center but aren't
        // already, we know where to pan to
        LatLng newLatLng = new LatLng(location.getLatitude(), location.getLongitude());
        if (!newLatLng.equals(mCurrentLatLong)) {
            mCurrentLatLong = new LatLng(location.getLatitude(), location.getLongitude());
            centerCameraOnLocation(false);
        }
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}

    @Override
    public void onProviderDisabled(String provider) {}

    @Override
    public void onProviderEnabled(String provider) {}

    /*************************************************************************
     *
     * M A P   C A M E R A
     *
     */

    /*
     * Updates the camera position based on current state.  If the camera is
     * already moving, then wait.
     */
    private void centerCameraOnLocation(boolean animate) {
        if (mGoogleMap == null) {
            return;
        }

        if (mCameraMoving) {
            mPendingUpdate = true;
            return;
        }

        // Get the CameraPosition to update to based on whether we are auto
        // centering or not.
        if (mCameraPosition == null) {
            mCameraPosition = Constants.GetDefaultCameraPosition();
        }

        // If this is the same as it was before, then don't reset it
        if (mCameraPosition.equals(mGoogleMap.getCameraPosition())) {
            return;
        }

        // Make the update so we can move the camera
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(mCameraPosition);

        // Move the camera with or without animation.  The time we don't want
        // animation is when we're setting the position initially
        if (animate) {
            mGoogleMap.animateCamera(cameraUpdate);
        }
        else {
            mGoogleMap.moveCamera(cameraUpdate);
        }
        mPendingUpdate = false;
    }
}

共 (0) 个答案