What Is the Place Called Where You Can Enter the Art Places

1. Before y'all begin

Learn how to utilize Google Maps Platform and the Places SDK for Android to present your users with a list of Places to identify their electric current locations.

bd07a9ad2cb27a06.png

Prerequisites

  • Basic Java skills

What you'll do

  • Add together a map to an Android app.
  • Use location permissions to geolocate the user.
  • Fetch Places virtually the user's current location.
  • Present likely Places to the user to place their current location.

What you'll build

You build your Android app from scratch, but you can download the sample code for comparing when debugging. Download the sample code from GitHub, or, if y'all have Git set upwardly for command-line use, enter the following:

git clone https://github.com/googlecodelabs/current-place-picker-android.git          

If yous run into whatsoever bug (lawmaking bugs, grammatical errors, unclear wording, or something else) every bit you work through this codelab, please report the issue via the Study a fault link in the lower left corner of the codelab.

2. Get Started

Before starting this codelab, you lot need to set up upward the following:

Android Studio

Download Android Studio from https://developer.android.com/studio.

If you already take Android Studio, brand sure you have the latest version by clicking Android Studio > Cheque for Updates....

1f36bae83b64e33.png

This lab was written using Android Studio 3.4.

Android SDK

In Android Studio, you can configure your desired SDKs using the SDK Managing director. This lab uses the Android Q SDK.

  1. From the Android Studio welcome screen, click Configure > SDK Manager.

d3fa03c269ec231c.png

  1. Select your desired SDK checkbox, so click Apply.

If you don't have the SDK yet, this will initiate downloading of the SDK to your auto.

884e0aa1314f70d.png

Google Play services

From the SDK manager, you also need to install Google Play services.

  1. Click SDK Tools tab and select the Google Play services checkbox.

Update if the condition reads Update bachelor.

ad6211fd78f3b629.png

3. Prepare the emulator

To run the app, you can connect your own device or use the Android Emulator.

If using your own device, skip to Real device instructions: Update Google Play Services at the end of this page.

Add an emulator

  1. From the Android Studio welcome screen, click Configure > AVD Manager.

5dd2d14c9c56d3f9.png

This opens the Android Virtual Device Managing director dialog.

  1. Click Create Virtual Device... to open a list of devices you tin can cull from.

2d44eada384f8b35.png

  1. Cull a device with the Play d5722488d80cd6be.png icon in the Play Store column and click Next.

e0248f1c6e85ab7c.png

You lot'll see a set of system images that you can install. If Q targeting Android 9.+ (Google Play) has the word Download next to it, click Download.

316d0d1efabd9f24.png

  1. Click Side by side to give your virtual device a proper name, then click Finish.

You render to the list of Your Virtual Devices.

  1. Click Start ba8adffe56d3b678.png side by side to your new device:

7605864ed27f77ea.png

After a few moments, the emulator opens.

Emulator instructions—update Google Play services

  1. In one case the emulator launches, click ... in the navigation bar that appears**.**

2e1156e02643d018.png

This opens the Extended controls dialog.

  1. Click Google Play in the menu.

If an update is available, click Update.

5afd2686c5cad0e5.png

  1. Sign in to the emulator with a Google Account.

You can use your own or create a new account for gratis to keep your testing split up from your personal information.

Google Play then opens to Google Play services.

  1. Click Update to get the latest version of Google Play services.

f4bc067e80630b9c.png

If asked to consummate your account setup and add a payment option, click Skip.

Set location in the emulator

  1. Once the emulator launches, blazon "maps" into the search bar on the domicile screen to pull up the Google Maps app icon.

2d996aadd53685a6.png

  1. Click the icon to launch.

Y'all see a default map.

  1. At the bottom-correct of the map, click Your Location c5b4e2fda57a7e71.png.

You're asked to requite the phone permissions to use location.

f2b68044eabca151.png

  1. Click ... to open the Extended Controls menu.
  2. Click the Location tab.
  3. Enter a latitude and longitude.

Enter annihilation you like here, but make certain information technology's in an surface area with plenty of places.

(Use Latitude xx.7818 and Longitude -156.4624 for the town of Kihei on Maui in Hawaii to replicate the results from this codelab.)

  1. Click Transport and the map updates with this location.

f9576b35218f4187.png

You're ready to run your app and test it with location.

Existent device instructions—update Google Play services

If you lot're using a real Android device, then do the following:

  1. Use the search bar on the domicile screen to search for, and open up, Google Play services.
  2. Click More than Details.

If available, click Update.

ad16cdb975b5c3f7.png baf0379ef8a9c88c.png

iv. Create the app trounce with a Google Maps action

  1. On the Android Studio welcome screen, select First a new Android Studio project.
  2. On the Telephone and Tablet tab, select Google Maps Activity.

c9c80aa8211a8761.png

The Configure your project dialog opens. Here is where you proper noun your app and create the package based on your domain.

Hither are the settings for an app called Electric current Place, which corresponds to the package com.google.codelab.currentplace.

37f5b93b94ee118c.png

  1. Cull Coffee as the linguistic communication and select Use androidx. artifacts*.

Keep the defaults for the residuum of the settings.

  1. Click Finish.

5. Add Google Services dependencies to the Gradle build file

To access location permissions in Android, you need Google Location and Activity Recognition API from Google Play services. For more information on adding this and other Google Play services APIs, see Set up Upwards Google Play Services.

Android Studio projects typically accept 2 build.gradle files. One is for the overall project and 1 is for the app. If you take the Android Studio Projection explorer in Android view, you see both of them in the Gradle Scripts folder. Y'all need to edit the build.gradle (Module: app) file to add Google services.

f3043429cf719c47.png

  1. Add two lines to the dependencies section to add Google services for location and the Places API ( sample code in context).

build.gradle (Module: app)

            plugins {   id 'com.android.application' }  android {     compileSdkVersion 28     defaultConfig {         applicationId "com.google.codelab.currentplace"         minSdkVersion nineteen         targetSdkVersion 28         versionCode 1         versionName "1.0"         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"     }     buildTypes {         release {             minifyEnabled simulated             proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'         }     } }  dependencies {     implementation fileTree(dir: 'libs', include: ['*.jar'])     implementation 'androidx.appcompat:appcompat:1.0.2'     implementation 'com.google.android.gms:play-services-maps:16.1.0'     testImplementation 'junit:junit:4.12'     androidTestImplementation 'androidx.exam:runner:1.1.1'     androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.i'      implementation 'com.google.android.gms:play-services-location:16.0.0'     implementation 'com.google.android.libraries.places:places:i.1.0' }                      

six. Enable Google Maps Platform APIs and get an API fundamental

For the post-obit enablement step , you demand to enable Maps SDK for Android and Places API.

Prepare up Google Maps Platform

If you do non already take a Google Cloud Platform account and a project with billing enabled, please see the Getting Started with Google Maps Platform guide to create a billing business relationship and a projection.

  1. In the Cloud Console, click the project drop-down menu and select the project that y'all want to use for this codelab.

  1. Enable the Google Maps Platform APIs and SDKs required for this codelab in the Google Cloud Marketplace. To do so, follow the steps in this video or this documentation.
  2. Generate an API key in the Credentials page of Cloud Console. You can follow the steps in this video or this documentation. All requests to Google Maps Platform require an API key.

Re-create the API key y'all just created. Switch dorsum to Android Studio, and find the file google_maps_api.xml under Android > app > res > values.

Supercede YOUR_KEY_HERE with the API key you copied.

aa576e551a7a1009.png

Your app is now configured.

seven. Edit the layout file

  1. In your project explorer, open up the activity_maps.xml file in the Android > app > res > layout.

4e0d986480c57efa.png

  1. You'll see the basic UI open up on the right of the screen, with tabs at the lesser allowing you to select the Pattern or Text editor for your layout. Select Text, and replace the entire contents of the layout file with this:

activity_maps.xml

            <?xml version="1.0" encoding="utf-8"?>  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:fitsSystemWindows="true"     android:orientation="vertical">      <androidx.appcompat.widget.Toolbar         android:id="@+id/toolbar"         android:minHeight="?attr/actionBarSize"         android:layout_width="match_parent"         android:layout_height="wrap_content"         app:titleTextColor="@android:color/white"         android:groundwork="@colour/colorPrimary" />      <LinearLayout         android:layout_width="match_parent"         android:layout_height="match_parent"         android:orientation="vertical">          <fragment             android:id="@+id/map"             android:name="com.google.android.gms.maps.SupportMapFragment"             android:layout_width="match_parent"             android:layout_height="349dp"             tools:context=".MapsActivity" />          <ListView             android:id="@+id/listPlaces"             android:layout_width="match_parent"             android:layout_height="wrap_content" />     </LinearLayout>  </LinearLayout>                      

This volition give you a user interface that looks similar this:

1bf786808a4697ce.png

8. Prepare the app bar

To give the user a push to click when they want to pick their current place, add an app bar with an icon that finds the user's electric current place and displays nearby likely places. It will look similar this:

3a17c92b613a26c5.png

On a phone, but the icon is shown. On a tablet with more infinite, the text is also included.

Create the icon

  1. In the project explorer, click Android > app, so right-click the res folder and select New > Image Asset.

The Asset Studio opens.

  1. In the Icon Type menu, click Action Bar and Tab Icons.
  2. Name your asset ic_geolocate.
  3. Select Clip Fine art as the nugget blazon**.**
  4. Click the graphic next to the Clip Art.

This opens the Select Icon window.

  1. Choose an icon.

Y'all tin can use the search bar to find icons related to your intent.

  1. Search for location and pick a location-related icon.

The my location icon is the same every bit the i used in the Google Maps app when a user wants to snap the camera to their current location.

  1. Click OK > Next > Finish, and ostend there is a new folder called drawable that contains your new icon files.

b9e0196137ed18ae.png

Add cord resources

  1. In the project explorer, click Android > app > res > values and open the strings.xml file.
  2. Add the following lines later on <string name="title_activity_maps">Map</cord>:

strings.xml

                          <string name="action_geolocate">Pick Place</string>     <string proper name="default_info_title">Default Location</cord>     <cord name="default_info_snippet">No places establish, because location permission is disabled.</string>                      

The first line is used in your app bar when at that place is infinite to include a text label adjacent to the icon. The others are used for markers that you add to the map.

Now the code in the file looks like this:

            <resources>     <string proper noun="app_name">Current Place</cord>     <string proper name="title_activity_maps">Map</string>     <cord proper name="action_geolocate">Pick Place</string>     <string name="default_info_title">Default Location</string>     <cord proper noun="default_info_snippet">No places establish, considering location permission is disabled.</string> </resource>                      

Add together the app bar

  1. In the project explorer, click Android > app, then right-click the res folder and select New > Directory to create a new subdirectory under app/src/main/res.
  2. Name the directory menu.
  3. Correct-click the menu folder and select New > File.
  4. Name the file carte.xml.
  5. Paste in this code:
            <?xml version="ane.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto">      <!-- "Locate me", should appear as action button if possible -->     <item         android:id="@+id/action_geolocate"         android:icon="@drawable/ic_geolocate"         android:championship="@string/action_geolocate"         app:showAsAction="ever|withText" />  </menu>                      

Update the app bar way

  1. In the project explorer, aggrandize the Android > app > res > values and open the file styles.xml inside.
  2. In the <style> tag, edit the parent property to exist "Theme.AppCompat.NoActionBar".
  3. Note the name property, which y'all employ in the side by side footstep.

styles.xml

            <way name="AppTheme" parent="Theme.AppCompat.NoActionBar">                      

Update the app theme in AndroidManifest.xml

  1. Click Android > app > manifests and open the AndroidManifest.xml file.
  2. Detect the android:theme line and edit or confirm the value to be @mode/AppTheme.

AndroidManifest.xml

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

You're now ready to brainstorm coding!

9. Initialize the app

  1. In your project explorer, discover the MapsActivity.java file.

It's in the folder corresponding to the parcel that you created for your app in step 1.

8b0fa27d417f5f55.png

  1. Open the file and yous're in the Coffee code editor.

Import the Places SDK and other dependencies

Add these lines at the elevation of MapsActivity.coffee, replacing the existing import statements.

They include the existing imports and add together many more used in the code in this codelab.

MapsActivity.java

            import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat;  import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView;  import com.google.android.gms.common.api.ApiException; import com.google.android.gms.location.FusedLocationProviderClient; 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.LatLng; import com.google.android.gms.maps.model.MarkerOptions;  import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.android.libraries.places.api.Places; import com.google.android.libraries.places.api.model.Place; import com.google.android.libraries.places.api.model.PlaceLikelihood; import com.google.android.libraries.places.api.net.FindCurrentPlaceRequest; import com.google.android.libraries.places.api.net.FindCurrentPlaceResponse; import com.google.android.libraries.places.api.net.PlacesClient;  import coffee.util.Arrays; import java.util.List;                      

Update the class signature

The Places API uses AndroidX components for astern-compatible back up, and so you need to define it to extend the AppCompatActivity. It replaces the FragmentActivity extension that is defined by default for a maps activity.

            public course MapsActivity extends AppCompatActivity implements OnMapReadyCallback {                      

Add class variables

Adjacent, declare the various class variables used in different class methods. These include the UI elements and condition codes. These should exist only below the variable proclamation for GoogleMap mMap.

                          // New variables for Current Place picker     private static final String TAG = "MapsActivity";     ListView lstPlaces;     private PlacesClient mPlacesClient;     private FusedLocationProviderClient mFusedLocationProviderClient;      // The geographical location where the device is currently located. That is, the last-known     // location retrieved past the Fused Location Provider.     private Location mLastKnownLocation;      // A default location (Sydney, Australia) and default zoom to utilise when location permission is     // not granted.     individual last LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);     private static final int DEFAULT_ZOOM = 15;     individual static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = i;     individual boolean mLocationPermissionGranted;      // Used for selecting the Current Place.     private static terminal int M_MAX_ENTRIES = 5;     private String[] mLikelyPlaceNames;     individual String[] mLikelyPlaceAddresses;     private String[] mLikelyPlaceAttributions;     private LatLng[] mLikelyPlaceLatLngs;                      

Update the onCreate method

You'll demand to update the onCreate method to handle runtime user permissions for location services, setting upwardly the UI elements and creating the Places API customer.

Add the following lines of lawmaking regarding the action toolbar, views setup, and Places client to the end of the existing onCreate() method.

MapsActivity.java onCreate()

                          @Override     protected void onCreate(Packet savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_maps);         // Obtain the SupportMapFragment and become notified when the map is fix to be used.         SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()                 .findFragmentById(R.id.map);         mapFragment.getMapAsync(this);          //         // PASTE THE LINES Below THIS Comment         //                  // Set upward the action toolbar         Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);         setSupportActionBar(toolbar);          // Set upwardly the views         lstPlaces = (ListView) findViewById(R.id.listPlaces);          // Initialize the Places customer         String apiKey = getString(R.cord.google_maps_key);         Places.initialize(getApplicationContext(), apiKey);         mPlacesClient = Places.createClient(this);         mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);     }                      

These ii methods add the app bar bill of fare (with a unmarried item, the Pick Place icon) and handle the user's click on the icon.

Re-create these two methods into your file afterward the onCreate method.

MapsActivity.coffee onCreateOptionsMenu() and onOptionsItemSelected()

                          @Override     public boolean onCreateOptionsMenu(Bill of fare carte) {         getMenuInflater().inflate(R.bill of fare.menu, carte);          render super.onCreateOptionsMenu(menu);     }      @Override     public boolean onOptionsItemSelected(MenuItem item) {         switch (item.getItemId()) {            case R.id.action_geolocate:                                  // COMMENTED OUT UNTIL WE DEFINE THE METHOD                 // Nowadays the current place picker                 // pickCurrentPlace();                 return true;              default:                 // If we got here, the user's activeness was not recognized.                 // Invoke the superclass to handle it.                 return super.onOptionsItemSelected(particular);          }     }                      

Exam it

  1. From Android Studio, click Run or Run menu > Run 'app'.

28bea91c68c36fb2.png

  1. You're asked to select your deployment target. The running emulator should announced on this list. Select it, and Android Studio deploys the app to the emulator for you lot.

f44658ca91f6f41a.png

Afterwards a few moments, the app launches. Yous see the map centered on Sydney, Australia, with the single button and unpopulated places list.

68eb8c70f4748350.png

The focus of the map doesn't move to the user's location unless yous request permission to access the device'south location.

10. Request and handle location permissions

Request location permissions after the map is prepare

  1. Ascertain a method called getLocationPermission that requests user permissions.

Paste this code below the onOptionsSelected method you just created.

MapsActivity.java getLocationPermission()

                          private void getLocationPermission() {         /*          * Request location permission, so that we tin can get the location of the          * device. The result of the permission request is handled by a callback,          * onRequestPermissionsResult.          */         mLocationPermissionGranted = false;         if (ContextCompat.checkSelfPermission(this.getApplicationContext(),                 android.Manifest.permission.ACCESS_FINE_LOCATION)                 == PackageManager.PERMISSION_GRANTED) {             mLocationPermissionGranted = true;         } else {             ActivityCompat.requestPermissions(this,                     new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},                     PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);         }     }                      
  1. Add together 2 lines to the stop of the existing onMapReady method to enable zoom controls and asking location permissions from the user.

MapsActivity.coffee onMapReady()

                          @Override     public void onMapReady(GoogleMap googleMap) {         mMap = googleMap;          // Add a marker in Sydney and motion the camera         LatLng sydney = new LatLng(-34, 151);         mMap.addMarker(new MarkerOptions().position(sydney).championship("Mark in Sydney"));         mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));          //         // PASTE THE LINES BELOW THIS COMMENT         //          // Enable the zoom controls for the map         mMap.getUiSettings().setZoomControlsEnabled(truthful);          // Prompt the user for permission.         getLocationPermission();      }                      

Handle the result from requested permissions

When the user responds to the request permission dialog, this callback is called by Android.

Paste this code after the getLocationPermission() method:

MapsActivity.java onRequestPermissionsResult()

                          /**      * Handles the result of the request for location permissions      */     @Override     public void onRequestPermissionsResult(int requestCode,                                            @NonNull String permissions[],                                            @NonNull int[] grantResults) {         mLocationPermissionGranted = false;         switch (requestCode) {             example 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;                 }             }         }     }                      

xi. Get the electric current location and fetch likely places

When the user clicks Pick Identify in the app bar, the app calls the method pickCurrentPlace(), which calls the getDeviceLocation() method you defined before. The getDeviceLocation method calls another method, getCurrentPlaceLikelihoods, after retrieving the latest device location.

Telephone call the findCurrentPlace API and handle the response

getCurrentPlaceLikelihoods constructs a findCurrentPlaceRequest and calls the Places API findCurrentPlace chore. If the chore is successful, it returns a findCurrentPlaceResponse, which contains a listing of placeLikelihood objects. Each of these have a number of properties, including the proper name and address of the identify, and the likelihood probability that you are in that place (a double value from 0 to 1). This method handles the response by constructing lists of identify details from the placeLikelihoods.

This code iterates through the 5 most-likely places and adds ones with a likelihood grater than 0 to a list which information technology then rendera. If you would similar to display more or less than five, edit the M_MAX_ENTRIES constant.

Paste this code after the onMapReady method.

MapsActivity.coffee getCurrentPlaceLikelihoods()

                          individual void getCurrentPlaceLikelihoods() {         // Apply fields to define the data types to return.         Listing<Place.Field> placeFields = Arrays.asList(Place.Field.Proper name, Place.Field.ADDRESS,                 Place.Field.LAT_LNG);          // Get the likely places - that is, the businesses and other points of interest that         // are the best match for the device's current location.         @SuppressWarnings("MissingPermission") final FindCurrentPlaceRequest request =                 FindCurrentPlaceRequest.builder(placeFields).build();         Job<FindCurrentPlaceResponse> placeResponse = mPlacesClient.findCurrentPlace(request);         placeResponse.addOnCompleteListener(this,                 new OnCompleteListener<FindCurrentPlaceResponse>() {                     @Override                     public void onComplete(@NonNull Job<FindCurrentPlaceResponse> task) {                         if (task.isSuccessful()) {                             FindCurrentPlaceResponse response = job.getResult();                             // Ready the count, handling cases where less than v entries are returned.                             int count;                             if (response.getPlaceLikelihoods().size() < M_MAX_ENTRIES) {                                 count = response.getPlaceLikelihoods().size();                             } else {                                 count = M_MAX_ENTRIES;                             }                              int i = 0;                             mLikelyPlaceNames = new Cord[count];                             mLikelyPlaceAddresses = new String[count];                             mLikelyPlaceAttributions = new Cord[count];                             mLikelyPlaceLatLngs = new LatLng[count];                              for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) {                                 Place currPlace = placeLikelihood.getPlace();                                 mLikelyPlaceNames[i] = currPlace.getName();                                 mLikelyPlaceAddresses[i] = currPlace.getAddress();                                 mLikelyPlaceAttributions[i] = (currPlace.getAttributions() == null) ?                                         null : TextUtils.join(" ", currPlace.getAttributions());                                 mLikelyPlaceLatLngs[i] = currPlace.getLatLng();                                  String currLatLng = (mLikelyPlaceLatLngs[i] == goose egg) ?                                         "" : mLikelyPlaceLatLngs[i].toString();                                  Log.i(TAG, String.format("Place " + currPlace.getName()                                         + " has likelihood: " + placeLikelihood.getLikelihood()                                         + " at " + currLatLng));                                  i++;                                 if (i > (count - i)) {                                     break;                                 }                             }                               // COMMENTED OUT UNTIL We Define THE METHOD                             // Populate the ListView                             // fillPlacesList();                         } else {                             Exception exception = job.getException();                             if (exception instanceof ApiException) {                                 ApiException apiException = (ApiException) exception;                                 Log.eastward(TAG, "Identify not found: " + apiException.getStatusCode());                             }                         }                     }                 });     }                      

Movement the map camera to the device's current location

If the user grants permission, the app fetches the user'due south latest location and moves the camera to center effectually that location.

If the user denies permission, the app simply moves the camera to the default location defined among the constants at the starting time of this page (in the sample code, information technology is Sydney, Australia).

Paste this code after the getPlaceLikelihoods() method:

MapsActivity.java getDeviceLocation()

                          private void getDeviceLocation() {         /*          * Get the best and most contempo location of the device, which may exist nix in rare          * cases when a location is not bachelor.          */         attempt {             if (mLocationPermissionGranted) {                 Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();                 locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {                     @Override                     public void onComplete(@NonNull Task<Location> job) {                         if (chore.isSuccessful()) {                             // Gear up the map'southward photographic camera position to the current location of the device.                             mLastKnownLocation = chore.getResult();                             Log.d(TAG, "Latitude: " + mLastKnownLocation.getLatitude());                             Log.d(TAG, "Longitude: " + mLastKnownLocation.getLongitude());                             mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(                                     new LatLng(mLastKnownLocation.getLatitude(),                                             mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));                         } else {                             Log.d(TAG, "Current location is null. Using defaults.");                             Log.e(TAG, "Exception: %south", task.getException());                             mMap.moveCamera(CameraUpdateFactory                                     .newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));                         }                         getCurrentPlaceLikelihoods();                     }                 });             }         } catch (SecurityException e)  {             Log.e("Exception: %south", e.getMessage());         }     }                      

Cheque for location permissions when the user clicks Pick Place

When the user taps Option Place, this method checks for location permissions and prompts the user for permission if it hasn't been granted.

If the user has granted permission, then the method calls getDeviceLocation to initiate the procedure of getting the electric current likely places.

  1. Add this method after getDeviceLocation():

MapsActivity.java pickCurrentPlace()

                          private void pickCurrentPlace() {         if (mMap == null) {             return;         }          if (mLocationPermissionGranted) {             getDeviceLocation();         } else {             // The user has not granted permission.             Log.i(TAG, "The user did not grant location permission.");              // Add a default marker, because the user hasn't selected a place.             mMap.addMarker(new MarkerOptions()                     .title(getString(R.cord.default_info_title))                     .position(mDefaultLocation)                     .snippet(getString(R.string.default_info_snippet)));              // Prompt the user for permission.             getLocationPermission();         }     }                      
  1. Now that pickCurrentPlace is defined, observe the line in onOptionsItemSelected() that calls pickCurrentPlace and uncomment it.

MapsActivity.java onOptionItemSelected()

                          instance R.id.action_geolocate:                  // COMMENTED OUT UNTIL WE Ascertain THE METHOD                 // Nowadays the Current Place picker                 pickCurrentPlace();                 render truthful;                      

Test information technology

If you run the app now and tap Choice Place, it should prompt for location permissions.

  • If yous allow permission, that preference is saved and you won't go prompted. If you lot deny permission, you get prompted the next time you tap the push.
  • Although getPlaceLikelihoods has fetched the likely current places, the ListView does non display them all the same. In Android Studio, you can click ⌘6 to check the logs in Logcat for statements tagged MapsActivity to verify that your new methods are working properly.
  • If y'all granted permission, the logs include a statement for Latitude: and a statement for Longitude: showing the detected location of the device. If you used Google Maps and the emulator's extended carte before to specify a location for the emulator, these statements show that location.
  • If the call to findCurrentPlace was successful, the logs include 5 statements printing the names and locations of the five almost-probable places.

d9896a245b81bf3.png

12. Populate the Current Place picker

Ready a handler for picked places

Let's think near what we want to happen when the user clicks an detail in the ListView. To confirm the user'due south option of which place they are currently, you can add a marker to the map at that place. If the user clicks that marking, an info window pops upwardly displaying the place proper noun and address.

Paste this click handler subsequently the pickCurrentPlace method.

MapsActivity.java listClickedHandler

                          private AdapterView.OnItemClickListener listClickedHandler = new AdapterView.OnItemClickListener() {         public void onItemClick(AdapterView parent, View v, int position, long id) {             // position will give us the index of which place was selected in the array             LatLng markerLatLng = mLikelyPlaceLatLngs[position];             String markerSnippet = mLikelyPlaceAddresses[position];             if (mLikelyPlaceAttributions[position] != null) {                 markerSnippet = markerSnippet + "\n" + mLikelyPlaceAttributions[position];             }              // Add together a marker for the selected place, with an info window             // showing information well-nigh that identify.             mMap.addMarker(new MarkerOptions()                     .title(mLikelyPlaceNames[position])                     .position(markerLatLng)                     .snippet(markerSnippet));             // Position the map'due south camera at the location of the marker.             mMap.moveCamera(CameraUpdateFactory.newLatLng(markerLatLng));         }     };                      

Populate the ListView

Now that you have your list of most-probable places that the user is currently visiting, you tin can present those options to the user in the ListView. yous tin can also set the ListView click listener to use the click handler you just defined.

Paste this method afterward the click handler:

MapsActivity.java fillPlacesList()

                          individual void fillPlacesList() {         // Set upwardly an ArrayAdapter to convert probable places into TextViews to populate the ListView         ArrayAdapter<String> placesAdapter =                 new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mLikelyPlaceNames);         lstPlaces.setAdapter(placesAdapter);         lstPlaces.setOnItemClickListener(listClickedHandler);     }                      

Now that fillPlacesList is divers, find the line toward the terminate of findPlaceLikelihoods that calls fillPlacesList and uncomment information technology.

MapsActivity.java fillPlaceLikelihoods()

                          // COMMENTED OUT UNTIL We DEFINE THE METHOD                 // Populate the ListView                 fillPlacesList();                      

That is all the code needed for the Current Place picker!

xiii. Run the app

Test picking a identify

  1. Run the app again.

This time when y'all tap Choice Place, the app populates the list with named places close to the location. Close to this location on Maui are places like Ululani's Hawaiian Shave Water ice and Sugar Beach Broil Shop. Considering the several places are very shut to the location coordinates, this is a list of probable places yous may be in.

  1. Click on a identify name in the ListView.

You should see a marker added to the map.

  1. Tap the marker.

You can see Identify Details.

e52303cc0de6a513.png 864c74342fb52a01.png

Examination a unlike location

If you lot want to change your location and are using the emulator, the device location doesn't automatically update when you update the location coordinates in the emulator's extended carte du jour.

To get around this, follow these steps to use the native Google Maps app to force updates to the emulator'southward location:

  1. Open Google Maps.
  2. Tap ... > Location to modify the breadth and longitude to new coordinates, and so tap Send.
  3. For example, you tin utilize Breadth: 49.2768 and Longitude: -123.1142 to set the location to downtown Vancouver, Canada.
  4. Verify that Google Maps has recentered on your new coordinates. You may need to tap the My Location push button in the Google Maps app to asking the recentering.
  5. Render to your Current Place app and tap Selection Place to get the map on the new coordinates and meet a new list of likely electric current places.

9adb99d1ce25c184.png

And that's it! You built a simple app that checks for the places at the current location and gives you a likelihood of which ones you're at. Bask!

At present go ahead and the run app with the modifications you made to complete this bonus stride!

14. Side by side steps

To preclude theft of your API key, you lot need to secure it and then but your Android app tin utilize the key. If left unrestricted, anyone with your key could employ it to telephone call Google Maps Platform APIs and cause you to get billed.

Get your SHA-i certificate

You need this later when y'all restrict your API keys. The post-obit is a ready of instructions for getting your debug certificate.

For Linux or macOS, open a final window and enter the following:

keytool -list -five -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android          

For Windows Vista and Windows 7, run the following command:

keytool -listing -five -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android          

You lot should see output like to this:

Alias name: androiddebugkey Cosmos engagement: Jan 01, 2013 Entry type: PrivateKeyEntry Certificate chain length: ane Document[1]: Owner: CN=Android Debug, O=Android, C=US Issuer: CN=Android Debug, O=Android, C=United states of america Serial number: 4aa9b300 Valid from: Mon Jan 01 08:04:04 UTC 2013 until: Monday Jan 01 18:04:04 PST 2033 Certificate fingerprints:      MD5:  AE:9F:95:D0:A6:86:89:BC:A8:70:BA:34:FF:6A:AC:F9      SHA1: BB:0D:Ac:74:D3:21:E1:43:07:71:9B:62:90:AF:A1:66:6E:44:5D:75      Signature algorithm name: SHA1withRSA      Version: 3          

The line that begins SHA1 contains the document's SHA-1 fingerprint. The fingerprint is the sequence of twenty double-digit hexadecimal numbers separated past colons.

When yous are set up to release an app, use the instructions in this documentation to remember your release certificate.

Add restrictions to your API cardinal

  1. In Cloud Panel, navigate to APIs & Services > Credentials.

The primal you used for this app should be listed under API Keys.

  1. Click 6454a04865d551e6.png to edit the key settings.

316b052c621ee91c.png

  1. On the API key page, subsequently Key restrictions, set the Application restrictions by doing the following:
  2. Select Android apps and follow the instructions.
  3. Click Add an item.
  4. Enter your package proper noun and SHA-1 certificate fingerprint (retrieved in the previous section).

For example:

            com.google.codelab.currentplace                      
BB:0D:Air-conditioning:74:D3:21:E1:43:07:71:9B:62:ninety:AF:A1:66:6E:44:5D:75s          
  1. For further protection, set the API restrictions by doing the post-obit.
  2. After API restrictions, choose Restrict central.
  3. Select the Maps SDK for Android and Places API.
  4. Click Washed and Save.

15. Congratulations

Yous built a simple app that checks for the most-probable places at the current location and adds a marker to the map for the place the user selects.

Learn more

  • To advance your development, leverage the Maps SDK for Android Utility Library. These utilities practice the heavy lifting for some of the virtually popular tasks for apps using Google Maps Platform.
  • For more code samples demonstrating most features of the Google Maps Platform SDKs for Android, clone repositories for Maps SDK for Android samples and Places SDK for Android demos.
  • To larn how to handle tri-state location permissions in Android Q, complete the Receive location updates in Android with Kotlin codelab.

wagnermadeelay42.blogspot.com

Source: https://developers.google.com/codelabs/maps-platform/location-places-android

0 Response to "What Is the Place Called Where You Can Enter the Art Places"

Enviar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel