在片段中使用Google地图

时间:2016-12-16 20:01:29

标签: java android google-maps android-fragments

我正在尝试在我正在处理的项目中使用Google地图,但我无法将地图作为片段使用。我想将地图用作片段并将片段添加到我的主要活动中(假设我可以在其他地方重用此片段,如果我需要的话)但应用程序崩溃或者除了加载地图之外没有做任何其他事情,具体取决于关于我尝试和改变的事情。

这是我用作MapsFragment.java文件中代码基础的教程。 https://developers.google.com/maps/documentation/android-api/current-places-tutorial

这是我尝试在activity_main.xml

中显示地图的基本标记
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:id="@+id/fragment_container"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent">

<Button
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:text="text"/>

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:tools="http://schemas.android.com/tools"
          android:id="@+id/map_fragment"
          android:name="com.google.android.gms.maps.SupportMapFragment"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          tools:context="[path info].MapsFragment"/>
</LinearLayout>

    @Override
    public void onConnected(Bundle connectionHint) {
        getDeviceLocation();
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_fragment);
        mapFragment.getMapAsync(this);
    }

使用此XML将加载地图,但它似乎不会调用我的Fragment类中的任何方法。它肯定不会调用onCreate,onCreateView或onConnected。

这里是我的片段类MapsFragment.java

的代码
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.location.LocationListener;

import java.util.Date;

public class MapsFragment extends Fragment implements
        OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    private static final String TAG = MapsActivity.class.getSimpleName();
    private GoogleMap mMap;

    // A default location (Sydney, Australia) and default zoom to use when location permission is
    // not granted.
    private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
    private static final int DEFAULT_ZOOM = 15;
    private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
    private boolean mLocationPermissionGranted;


    private Location mCurrentLocation;
    private Marker mCurrentLocationMarker;

    private CameraPosition mCameraPosition;

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
            UPDATE_INTERVAL_IN_MILLISECONDS / 2;

    // Keys for storing activity state.
    private static final String KEY_CAMERA_POSITION = "camera_position";
    private static final String KEY_LOCATION = "location";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // initialize GoogleAPIClient
        Activity parentActivity = this.getActivity();
        if (parentActivity != null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this.getActivity())
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this)
                    .addApi(LocationServices.API)
                    .build();
            createLocationRequest();

        }
    }

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

    @Override
    public void onResume() {
        super.onResume();
        //setUpMapIfNeeded();
        if (mGoogleApiClient.isConnected()) {
            getDeviceLocation();
        } else {
            mGoogleApiClient.connect();
        }
    }

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

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

        if (mCurrentLocation != null) {
            LatLng latLng = new LatLng(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());    // maybe add default zoom?
            mMap.addMarker(new MarkerOptions().position(latLng).title("You"));  //(latLng).title("Marker"));
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, DEFAULT_ZOOM));
        } else {
            Log.d(TAG, "Current location is null.  Using defaults.");
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mDefaultLocation, 10));     //zoom to Sydney, Australia
        }
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        getDeviceLocation();
        SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_fragment);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult result) {
        // Refer to the reference doc for ConnectionResult to see what error codes might
        // be returned in onConnectionFailed.
        Log.d(TAG, "Play services connection failed: ConnectionResult.getErrorCode() = "
        + result.getErrorCode());
    }

    @Override
    public void onConnectionSuspended(int cause) {
        Log.d(TAG, "Play services connection suspended");
    }

    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;
        //updateMarkers();
        if (mCurrentLocationMarker != null) {
            mCurrentLocationMarker.remove();
        }
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        // DEBUG
        Date date = new Date();
        int hour = date.getHours();
        int minutes = date.getMinutes();
        String time = String.valueOf(hour) + ":" + String.valueOf(minutes);
        //
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, DEFAULT_ZOOM));
        // might need mMap.animateCamera(CameraUpdateFactory.zoomTo(11)) to animate transition. Not sure.
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        markerOptions.title(time);
        mCurrentLocationMarker = mMap.addMarker(markerOptions);

        Log.d(TAG, latLng.toString() + ", Time: " + time);
    }

    private void getDeviceLocation() {
        if (ContextCompat.checkSelfPermission(this.getContext(),
            Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
        {
            mLocationPermissionGranted = true;
        } else {
            ActivityCompat.requestPermissions(this.getActivity(),
                new String[] {Manifest.permission.ACCESS_FINE_LOCATION},
                PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
        }

        if (mLocationPermissionGranted) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
            mLocationRequest, this);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
    @NonNull String permissions[],
    @NonNull int[] grantResults) {
        mLocationPermissionGranted = false;
        switch (requestCode) {
            case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    mLocationPermissionGranted = true;
                }
            }
        }
        updateLocationUI();
    }

    @SuppressWarnings("MissingPermission")
    private void updateLocationUI() {
        if (mMap == null) {
            return;
        }

        if (mLocationPermissionGranted) {
            mMap.setMyLocationEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(true);
        } else {
            mMap.setMyLocationEnabled(false);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);
            mCurrentLocation = null;
        }
    }

    private void createLocationRequest() {
        mLocationRequest = new LocationRequest();

        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }
}

我已经尝试摆脱android:name name-value对,并添加class =&#34; [完全限定路径名称]&#34;因为我认为我需要一种方法将类和片段绑定在一起,以便在片段膨胀时执行代码。如果我这样做,我的类代码实际上被调用,但是当在onConnected中调用getMapAsync时我得到以下错误

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.SupportMapFragment.getMapAsync(com.google.android.gms.maps.OnMapReadyCallback)' on a null object reference
                                                                         at [the path info].MapsFragment.onConnected(MapsFragment.java:163)
                                                                         at com.google.android.gms.common.internal.zzm.zzq(Unknown Source)
                                                                         at com.google.android.gms.internal.zzaal.zzo(Unknown Source)
                                                                         at com.google.android.gms.internal.zzaaj.zzvE(Unknown Source)
                                                                         at com.google.android.gms.internal.zzaaj.onConnected(Unknown Source)
                                                                         at com.google.android.gms.internal.zzaan.onConnected(Unknown Source)
                                                                         at com.google.android.gms.internal.zzzy.onConnected(Unknown Source)
                                                                         at com.google.android.gms.common.internal.zzl$1.onConnected(Unknown Source)
                                                                         at com.google.android.gms.common.internal.zzf$zzj.zzwZ(Unknown Source)
                                                                         at com.google.android.gms.common.internal.zzf$zza.zzc(Unknown Source)
                                                                         at com.google.android.gms.common.internal.zzf$zza.zzu(Unknown Source)
                                                                         at com.google.android.gms.common.internal.zzf$zze.zzxa(Unknown Source)
                                                                         at com.google.android.gms.common.internal.zzf$zzd.handleMessage(Unknown Source)
                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                         at android.os.Looper.loop(Looper.java:148)
                                                                         at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

我一直在尝试不同的事情,并试图了解究竟是什么导致了我的问题,以及如何使其工作,但无济于事。如果这不是我正在尝试做的正确方法,我应该做些什么呢?

我试着在这个网站上查找类似问题的问题,但他们似乎都找不到答案。

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

我所做的是创建另一个xml,仅用于加载地图布局xml

<fragment 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:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.user.myApp.Fragment.MapFragment" />

之后,我的片段中的地图膨胀

SupportMapFragment mapFragment;

if (mapFragment == null) {
        mapFragment = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map));


        // Check if we were successful in obtaining the map.
        if (mapFragment != null) {
            mapFragment.getMapAsync(this);

            if (mapFragment == null) {

                Toast.makeText(getContext(),"Sorry! unable to create maps", Toast.LENGTH_SHORT).show();
            }
        }
    }

开始时连接你的api

@Override
public void onStart() {
    super.onStart();
    googleApiClient.connect();
}
在初始化onCreateView

之后,{p>以及mapFragment中的以下几行
googleApiClient = new GoogleApiClient.Builder(getActivity())
            .addApi(LocationServices.API)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .build();

如果您发现任何问题,请告诉我

答案 1 :(得分:0)

在活动的onCreate中添加这段代码

    FragmentManager myFragmentManager = getSupportFragmentManager();
    SupportMapFragment mapFragment = (SupportMapFragment) myFragmentManager
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);