Advertisement
Kirizhik

Untitled

Jun 30th, 2018
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 16.46 KB | None | 0 0
  1. package com.clBrain.mmmmapio;
  2.  
  3. import android.content.DialogInterface;
  4. import android.content.pm.PackageManager;
  5. import android.location.Location;
  6. import android.os.Bundle;
  7. import android.support.annotation.NonNull;
  8. import android.support.v4.app.ActivityCompat;
  9. import android.support.v4.content.ContextCompat;
  10. import android.support.v7.app.AlertDialog;
  11. import android.support.v7.app.AppCompatActivity;
  12. import android.util.Log;
  13. import android.view.Menu;
  14. import android.view.MenuItem;
  15. import android.view.View;
  16. import android.widget.FrameLayout;
  17. import android.widget.TextView;
  18.  
  19. import com.google.android.gms.location.FusedLocationProviderClient;
  20. import com.google.android.gms.location.LocationServices;
  21. import com.google.android.gms.location.places.GeoDataClient;
  22. import com.google.android.gms.location.places.PlaceDetectionClient;
  23. import com.google.android.gms.location.places.PlaceLikelihood;
  24. import com.google.android.gms.location.places.PlaceLikelihoodBufferResponse;
  25. import com.google.android.gms.location.places.Places;
  26. import com.google.android.gms.maps.CameraUpdateFactory;
  27. import com.google.android.gms.maps.GoogleMap;
  28. import com.google.android.gms.maps.OnMapReadyCallback;
  29. import com.google.android.gms.maps.SupportMapFragment;
  30. import com.google.android.gms.maps.model.CameraPosition;
  31. import com.google.android.gms.maps.model.LatLng;
  32. import com.google.android.gms.maps.model.Marker;
  33. import com.google.android.gms.maps.model.MarkerOptions;
  34. import com.google.android.gms.tasks.OnCompleteListener;
  35. import com.google.android.gms.tasks.Task;
  36.  
  37. /**
  38.  * An activity that displays a map showing the place at the device's current location.
  39.  */
  40. public class MapsCurrentPlaceActivity extends AppCompatActivity
  41.         implements OnMapReadyCallback {
  42.  
  43.     private static final String TAG = MapsCurrentPlaceActivity.class.getSimpleName();
  44.     private GoogleMap mMap;
  45.     private CameraPosition mCameraPosition;
  46.  
  47.     // The entry points to the Places API.
  48.     private GeoDataClient mGeoDataClient;
  49.     private PlaceDetectionClient mPlaceDetectionClient;
  50.  
  51.     // The entry point to the Fused Location Provider.
  52.     private FusedLocationProviderClient mFusedLocationProviderClient;
  53.  
  54.     // A default location (Sydney, Australia) and default zoom to use when location permission is
  55.     // not granted.
  56.     private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
  57.     private static final int DEFAULT_ZOOM = 15;
  58.     private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1;
  59.     private boolean mLocationPermissionGranted;
  60.  
  61.     // The geographical location where the device is currently located. That is, the last-known
  62.     // location retrieved by the Fused Location Provider.
  63.     private Location mLastKnownLocation;
  64.  
  65.     // Keys for storing activity state.
  66.     private static final String KEY_CAMERA_POSITION = "camera_position";
  67.     private static final String KEY_LOCATION = "location";
  68.  
  69.     // Used for selecting the current place.
  70.     private static final int M_MAX_ENTRIES = 5;
  71.     private String[] mLikelyPlaceNames;
  72.     private String[] mLikelyPlaceAddresses;
  73.     private String[] mLikelyPlaceAttributions;
  74.     private LatLng[] mLikelyPlaceLatLngs;
  75.  
  76.     @Override
  77.     protected void onCreate(Bundle savedInstanceState) {
  78.         super.onCreate(savedInstanceState);
  79.  
  80.         // Retrieve location and camera position from saved instance state.
  81.         if (savedInstanceState != null) {
  82.             mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
  83.             mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
  84.         }
  85.  
  86.         // Retrieve the content view that renders the map.
  87.         setContentView(R.layout.activity_maps);
  88.  
  89.         // Construct a GeoDataClient.
  90.         mGeoDataClient = Places.getGeoDataClient(this, null);
  91.  
  92.         // Construct a PlaceDetectionClient.
  93.         mPlaceDetectionClient = Places.getPlaceDetectionClient(this, null);
  94.  
  95.         // Construct a FusedLocationProviderClient.
  96.         mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
  97.  
  98.         // Build the map.
  99.         SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
  100.                 .findFragmentById(R.id.map);
  101.         mapFragment.getMapAsync(this);
  102.  
  103.     }
  104.  
  105.     /**
  106.      * Saves the state of the map when the activity is paused.
  107.      */
  108.     @Override
  109.     protected void onSaveInstanceState(Bundle outState) {
  110.         if (mMap != null) {
  111.             outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
  112.             outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
  113.             super.onSaveInstanceState(outState);
  114.         }
  115.     }
  116.  
  117.     /**
  118.      * Sets up the options menu.
  119.      * @param menu The options menu.
  120.      * @return Boolean.
  121.      */
  122.     @Override
  123.     public boolean onCreateOptionsMenu(Menu menu) {
  124.         getMenuInflater().inflate(R.menu.current_place_menu, menu);
  125.         return true;
  126.     }
  127.  
  128.     /**
  129.      * Handles a click on the menu option to get a place.
  130.      * @param item The menu item to handle.
  131.      * @return Boolean.
  132.      */
  133.     @Override
  134.     public boolean onOptionsItemSelected(MenuItem item) {
  135.         if (item.getItemId() == R.id.option_get_place) {
  136.             showCurrentPlace();
  137.         }
  138.         return true;
  139.     }
  140.  
  141.     /**
  142.      * Manipulates the map when it's available.
  143.      * This callback is triggered when the map is ready to be used.
  144.      */
  145.     @Override
  146.     public void onMapReady(GoogleMap map) {
  147.         mMap = map;
  148.  
  149.         // Use a custom info window adapter to handle multiple lines of text in the
  150.         // info window contents.
  151.         mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
  152.  
  153.             @Override
  154.             // Return null here, so that getInfoContents() is called next.
  155.             public View getInfoWindow(Marker arg0) {
  156.                 return null;
  157.             }
  158.  
  159.             @Override
  160.             public View getInfoContents(Marker marker) {
  161.                 // Inflate the layouts for the info window, title and snippet.
  162.                 View infoWindow = getLayoutInflater().inflate(R.layout.custom_info_contents,
  163.                         (FrameLayout) findViewById(R.id.map), false);
  164.  
  165.                 TextView title = ((TextView) infoWindow.findViewById(R.id.title));
  166.                 title.setText(marker.getTitle());
  167.  
  168.                 TextView snippet = ((TextView) infoWindow.findViewById(R.id.snippet));
  169.                 snippet.setText(marker.getSnippet());
  170.  
  171.                 return infoWindow;
  172.             }
  173.         });
  174.  
  175.         // Prompt the user for permission.
  176.         getLocationPermission();
  177.  
  178.         // Turn on the My Location layer and the related control on the map.
  179.         updateLocationUI();
  180.  
  181.         // Get the current location of the device and set the position of the map.
  182.         getDeviceLocation();
  183.     }
  184.  
  185.     /**
  186.      * Gets the current location of the device, and positions the map's camera.
  187.      */
  188.     private void getDeviceLocation() {
  189.         /*
  190.          * Get the best and most recent location of the device, which may be null in rare
  191.          * cases when a location is not available.
  192.          */
  193.         try {
  194.             if (mLocationPermissionGranted) {
  195.                 Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
  196.                 locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {
  197.                     @Override
  198.                     public void onComplete(@NonNull Task<Location> task) {
  199.                         if (task.isSuccessful()) {
  200.                             // Set the map's camera position to the current location of the device.
  201.                             mLastKnownLocation = task.getResult();
  202.                             mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
  203.                                     new LatLng(mLastKnownLocation.getLatitude(),
  204.                                             mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));
  205.                         } else {
  206.                             Log.d(TAG, "Current location is null. Using defaults.");
  207.                             Log.e(TAG, "Exception: %s", task.getException());
  208.                             mMap.moveCamera(CameraUpdateFactory
  209.                                     .newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
  210.                             mMap.getUiSettings().setMyLocationButtonEnabled(false);
  211.                         }
  212.                     }
  213.                 });
  214.             }
  215.         } catch (SecurityException e)  {
  216.             Log.e("Exception: %s", e.getMessage());
  217.         }
  218.     }
  219.  
  220.  
  221.     /**
  222.      * Prompts the user for permission to use the device location.
  223.      */
  224.     private void getLocationPermission() {
  225.         /*
  226.          * Request location permission, so that we can get the location of the
  227.          * device. The result of the permission request is handled by a callback,
  228.          * onRequestPermissionsResult.
  229.          */
  230.         if (ContextCompat.checkSelfPermission(this.getApplicationContext(),
  231.                 android.Manifest.permission.ACCESS_FINE_LOCATION)
  232.                 == PackageManager.PERMISSION_GRANTED) {
  233.             mLocationPermissionGranted = true;
  234.         } else {
  235.             ActivityCompat.requestPermissions(this,
  236.                     new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
  237.                     PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
  238.         }
  239.     }
  240.  
  241.     /**
  242.      * Handles the result of the request for location permissions.
  243.      */
  244.     @Override
  245.     public void onRequestPermissionsResult(int requestCode,
  246.                                            @NonNull String permissions[],
  247.                                            @NonNull int[] grantResults) {
  248.         mLocationPermissionGranted = false;
  249.         switch (requestCode) {
  250.             case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: {
  251.                 // If request is cancelled, the result arrays are empty.
  252.                 if (grantResults.length > 0
  253.                         && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
  254.                     mLocationPermissionGranted = true;
  255.                 }
  256.             }
  257.         }
  258.         updateLocationUI();
  259.     }
  260.  
  261.     /**
  262.      * Prompts the user to select the current place from a list of likely places, and shows the
  263.      * current place on the map - provided the user has granted location permission.
  264.      */
  265.     private void showCurrentPlace() {
  266.         if (mMap == null) {
  267.             return;
  268.         }
  269.  
  270.         if (mLocationPermissionGranted) {
  271.             // Get the likely places - that is, the businesses and other points of interest that
  272.             // are the best match for the device's current location.
  273.             @SuppressWarnings("MissingPermission") final
  274.             Task<PlaceLikelihoodBufferResponse> placeResult =
  275.                     mPlaceDetectionClient.getCurrentPlace(null);
  276.             placeResult.addOnCompleteListener
  277.                     (new OnCompleteListener<PlaceLikelihoodBufferResponse>() {
  278.                         @Override
  279.                         public void onComplete(@NonNull Task<PlaceLikelihoodBufferResponse> task) {
  280.                             if (task.isSuccessful() && task.getResult() != null) {
  281.                                 PlaceLikelihoodBufferResponse likelyPlaces = task.getResult();
  282.  
  283.                                 // Set the count, handling cases where less than 5 entries are returned.
  284.                                 int count;
  285.                                 if (likelyPlaces.getCount() < M_MAX_ENTRIES) {
  286.                                     count = likelyPlaces.getCount();
  287.                                 } else {
  288.                                     count = M_MAX_ENTRIES;
  289.                                 }
  290.  
  291.                                 int i = 0;
  292.                                 mLikelyPlaceNames = new String[count];
  293.                                 mLikelyPlaceAddresses = new String[count];
  294.                                 mLikelyPlaceAttributions = new String[count];
  295.                                 mLikelyPlaceLatLngs = new LatLng[count];
  296.  
  297.                                 for (PlaceLikelihood placeLikelihood : likelyPlaces) {
  298.                                     // Build a list of likely places to show the user.
  299.                                     mLikelyPlaceNames[i] = (String) placeLikelihood.getPlace().getName();
  300.                                     mLikelyPlaceAddresses[i] = (String) placeLikelihood.getPlace()
  301.                                             .getAddress();
  302.                                     mLikelyPlaceAttributions[i] = (String) placeLikelihood.getPlace()
  303.                                             .getAttributions();
  304.                                     mLikelyPlaceLatLngs[i] = placeLikelihood.getPlace().getLatLng();
  305.  
  306.                                     i++;
  307.                                     if (i > (count - 1)) {
  308.                                         break;
  309.                                     }
  310.                                 }
  311.  
  312.                                 // Release the place likelihood buffer, to avoid memory leaks.
  313.                                 likelyPlaces.release();
  314.  
  315.                                 // Show a dialog offering the user the list of likely places, and add a
  316.                                 // marker at the selected place.
  317.                                 openPlacesDialog();
  318.  
  319.                             } else {
  320.                                 Log.e(TAG, "Exception: %s", task.getException());
  321.                             }
  322.                         }
  323.                     });
  324.         } else {
  325.             // The user has not granted permission.
  326.             Log.i(TAG, "The user did not grant location permission.");
  327.  
  328.             // Add a default marker, because the user hasn't selected a place.
  329.             mMap.addMarker(new MarkerOptions()
  330.                     .title(getString(R.string.default_info_title))
  331.                     .position(mDefaultLocation)
  332.                     .snippet(getString(R.string.default_info_snippet)));
  333.  
  334.             // Prompt the user for permission.
  335.             getLocationPermission();
  336.         }
  337.     }
  338.  
  339.     /**
  340.      * Displays a form allowing the user to select a place from a list of likely places.
  341.      */
  342.     private void openPlacesDialog() {
  343.         // Ask the user to choose the place where they are now.
  344.         DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
  345.             @Override
  346.             public void onClick(DialogInterface dialog, int which) {
  347.                 // The "which" argument contains the position of the selected item.
  348.                 LatLng markerLatLng = mLikelyPlaceLatLngs[which];
  349.                 String markerSnippet = mLikelyPlaceAddresses[which];
  350.                 if (mLikelyPlaceAttributions[which] != null) {
  351.                     markerSnippet = markerSnippet + "\n" + mLikelyPlaceAttributions[which];
  352.                 }
  353.  
  354.                 // Add a marker for the selected place, with an info window
  355.                 // showing information about that place.
  356.                 mMap.addMarker(new MarkerOptions()
  357.                         .title(mLikelyPlaceNames[which])
  358.                         .position(markerLatLng)
  359.                         .snippet(markerSnippet));
  360.  
  361.                 // Position the map's camera at the location of the marker.
  362.                 mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(markerLatLng,
  363.                         DEFAULT_ZOOM));
  364.             }
  365.         };
  366.  
  367.         // Display the dialog.
  368.         AlertDialog dialog = new AlertDialog.Builder(this)
  369.                 .setTitle(R.string.pick_place)
  370.                 .setItems(mLikelyPlaceNames, listener)
  371.                 .show();
  372.     }
  373.  
  374.     /**
  375.      * Updates the map's UI settings based on whether the user has granted location permission.
  376.      */
  377.     private void updateLocationUI() {
  378.         if (mMap == null) {
  379.             return;
  380.         }
  381.         try {
  382.             if (mLocationPermissionGranted) {
  383.                 mMap.setMyLocationEnabled(true);
  384.                 mMap.getUiSettings().setMyLocationButtonEnabled(true);
  385.             } else {
  386.                 mMap.setMyLocationEnabled(false);
  387.                 mMap.getUiSettings().setMyLocationButtonEnabled(false);
  388.                 mLastKnownLocation = null;
  389.                 getLocationPermission();
  390.             }
  391.         } catch (SecurityException e)  {
  392.             Log.e("Exception: %s", e.getMessage());
  393.         }
  394.     }
  395. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement