片段内的地图视图

时间:2018-10-31 14:10:21

标签: android android-permissions android-mapview android-location android-maps-v2

我一直在寻找Fragment中Map(MapView)的正确代码。我有以下代码:

 public class Clock extends Fragment implements OnMapReadyCallback,
            GoogleApiClient.ConnectionCallbacks,
            GoogleApiClient.OnConnectionFailedListener,
            com.google.android.gms.location.LocationListener
    {
      public static final String ACCESS_FINE_LOCATION = "android.permission.ACCESS_FINE_LOCATION";
      MapView mMapView;
      private GoogleMap googleMap;

  private static final int MY_PERMISSION_REQUEST_CODE = 0;
  private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 1;

  private GoogleApiClient mgoogleApiClient;
  private LocationRequest mlocationRequest;
  private Location mlastlocation;
  double longitude,latitude;

  Marker myCurrentMarker;

  private static int UPDATE_INTERVAL = 1000;
  private static int FASTEST_INTERVAL = 3000;
  private static int DISPLACEMENT = 10;

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.tab_clock, container, false);

    setUpLocation();


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

    mMapView.onResume(); // needed to get the map to display immediately

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

    mMapView.getMapAsync(new OnMapReadyCallback() {
      @Override
      public void onMapReady(GoogleMap mMap) {
        googleMap = mMap;

        displayLocation();

        // For showing a move to my location button
        if (ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getActivity().getApplicationContext(), permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
          // TODO: Consider calling
          //    ActivityCompat#requestPermissions
          // here to request the missing permissions, and then overriding
          //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
          //                                          int[] grantResults)
          // to handle the case where the user grants the permission. See the documentation
          // for ActivityCompat#requestPermissions for more details.
        }

        try {
          googleMap.setMyLocationEnabled(true);
        } catch (Exception e) {
          e.printStackTrace();
        }
        // For dropping a marker at a point on the Map
//        LatLng sydney = new LatLng(-34, 151);
//        googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
//
//        // For zooming automatically to the location of the marker
//        CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
//        googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

        mlastlocation = LocationServices.FusedLocationApi.getLastLocation(mgoogleApiClient);
        if (mlastlocation != null) {
          final double latitude = mlastlocation.getLatitude();
          final double longitute = mlastlocation.getLongitude();

          final LatLng latLng = new LatLng(latitude, longitute);

          if (myCurrentMarker != null) {
            myCurrentMarker.remove();
          }

          MarkerOptions markerOptions = new MarkerOptions();
          markerOptions.position(latLng);
          markerOptions.title("Current Location");
          markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));

          myCurrentMarker = googleMap.addMarker(markerOptions);


          googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
          googleMap.animateCamera(CameraUpdateFactory.zoomBy(10));
        }
      }
    });

    return rootView;
  }

  private void displayLocation() {
    if (ActivityCompat.checkSelfPermission(getActivity(),
            android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getActivity(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED) {
      return;
    }
    mlastlocation = LocationServices.FusedLocationApi.getLastLocation(mgoogleApiClient);
    if (mlastlocation != null) {
      final double latitude = mlastlocation.getLatitude();
      final double longitute = mlastlocation.getLongitude();

      final LatLng latLng = new LatLng(latitude, longitute);

      if (myCurrentMarker != null)
      {
        myCurrentMarker.remove();
      }

      MarkerOptions markerOptions = new MarkerOptions();
      markerOptions.position(latLng);
      markerOptions.title("Current Location");
      markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));

      myCurrentMarker = googleMap.addMarker(markerOptions);


      googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
      googleMap.animateCamera(CameraUpdateFactory.zoomBy(10));


    }

  }



  public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

  private void setUpLocation() {
    if (ActivityCompat.checkSelfPermission(getActivity(),
            android.Manifest.permission.ACCESS_COARSE_LOCATION) !=
            PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(getActivity(),
                    android.Manifest.permission.ACCESS_FINE_LOCATION) !=
                    PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(getActivity(), new String[]{
              android.Manifest.permission.ACCESS_COARSE_LOCATION,
              android.Manifest.permission.ACCESS_FINE_LOCATION
      }, MY_PERMISSION_REQUEST_CODE);
    } else {
      if (checkPlaySercives()) {
        buildGoogleApiClient();
        creatLocationRequest();
//        displayLocation();
      }
    }
  }

  @Override
  public void onRequestPermissionsResult(int requestCode, @NonNull String[]
          permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
      case MY_PERMISSIONS_REQUEST_LOCATION:
        if (grantResults.length > 0 && grantResults[0] ==
                PackageManager.PERMISSION_GRANTED) {
          if (checkPlaySercives()) {
            buildGoogleApiClient();
            creatLocationRequest();
//            displayLocation();
          }
        }
        break;
    }
  }

  private boolean checkPlaySercives() {
    int resultCode =
            GooglePlayServicesUtil.isGooglePlayServicesAvailable(getActivity());
    if (resultCode != ConnectionResult.SUCCESS) {
      if (GooglePlayServicesUtil.isUserRecoverableError(resultCode))
        GooglePlayServicesUtil.getErrorDialog(resultCode, getActivity(),PLAY_SERVICES_RESOLUTION_REQUEST).show();
      else {
        Toast.makeText(getActivity(), "This device is not supported",
                Toast.LENGTH_LONG).show();
      }
      return false;
    }
    return true;
  }

  private void buildGoogleApiClient() {
    mgoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mgoogleApiClient.connect();
  }

  private void creatLocationRequest() {
    mlocationRequest = new LocationRequest();
    mlocationRequest.setInterval(UPDATE_INTERVAL);
    mlocationRequest.setFastestInterval(FASTEST_INTERVAL);
    mlocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mlocationRequest.setSmallestDisplacement(DISPLACEMENT);
  }



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

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

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

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

  @Override
  public void onConnected(@Nullable Bundle bundle) {

  }

  @Override
  public void onConnectionSuspended(int i) {

  }

  @Override
  public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

  }

  @Override
  public void onLocationChanged(Location location) {

  }

  @Override
  public void onMapReady(GoogleMap googleMap) {

  }
}

如果该应用程序已经安装在模拟器中,则可以正常工作。我有地图和位置。但是...

当我从模拟器卸载应用程序并再次运行时。它不起作用。我的意思是位置请求代码无法那样工作。

在我的logcat中,我具有: java.lang.IllegalArgumentException:GoogleApiClient 参数是必需的。 (但仅当我第一次在模拟器上安装应用程序时)

有解决方案吗?

0 个答案:

没有答案