Вид карты внутри фрагмента - PullRequest
0 голосов
/ 31 октября 2018

Я так долго искал правильный код для Map (MapView) во Fragment. И у меня есть этот код:

 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 параметр обязателен. (НО ТОЛЬКО КОГДА Я УСТАНАВЛИВАЮ ПРИЛОЖЕНИЕ ВПЕРВЫЕ НА ЭМУЛЯТОР)

Есть решение?

...