migrating to Places API, cannot resolve GEO_DATA_API GeoDataApi - android

I'm going through the process of migrating from depricated Places SDK to the Places API as described here, using the compatibility library. Everything had been working fine prior to attempting the migration. I've
1) Updated my dependencies
2) Changes my import statements
3) Min SDK was already 21
I am getting two (seemingly related) errors. cannot find symbol variable GEO_DATA_API and cannot find symbol variable GeoDataApi
the code
googleApiClient = new GoogleApiClient.Builder(PlacesActivity.this)
.addApi(Places.GEO_DATA_API) //***HERE***
.enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
.addConnectionCallbacks(this)
.build();
and
private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) {
if (googleApiClient !=null) {
PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi.getAutocompletePredictions( // ***AND HERE***
googleApiClient,
constraint.toString(),
latLngBounds,
autocompleteFilter
);
// Wait for predictions, set the timeout.
AutocompletePredictionBuffer autocompletePredictions = results.await(60, TimeUnit.SECONDS);
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
//auto complete fail
autocompletePredictions.release();
return null;
}
//auto complete success
Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator();
ArrayList<PlaceAutocomplete> resultList = new ArrayList<>(autocompletePredictions.getCount());
while (iterator.hasNext()) {
AutocompletePrediction prediction = iterator.next();
resultList.add(new PlaceAutocomplete(prediction.getPlaceId(), prediction.getFullText(null)));
}
// Buffer release
autocompletePredictions.release();
return resultList;
}
return null;
}

An entire re write of code is required. Here is working code for getting lat, lng, and name (for example)
public class MainActivity extends AppCompatActivity {
String TAG = "placeautocomplete";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize Places.
Places.initialize(getApplicationContext(), "YOUR_API_KEY");
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
// Initialize the AutocompleteSupportFragment.
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
// Specify the types of place data to return.
autocompleteFragment.setPlaceFields(Arrays.asList(
Place.Field.NAME,
Place.Field.LAT_LNG
));
// Set up a PlaceSelectionListener to handle the response.
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
String name = place.getName();
double lat, lng;
if (place.getLatLng() !=null){
lat =place.getLatLng().latitude;
lng =place.getLatLng().longitude;
}
//do something
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i(TAG, "An error occurred: " + status);
}
});
}
}
example xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<android.support.v7.widget.CardView
android:id="#+id/idCardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
app:cardCornerRadius="4dp"
>
<fragment
android:id="#+id/autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
/>
</android.support.v7.widget.CardView>
</LinearLayout>

Problem 1: cannot find symbol variable GEO_DATA_API
Solution 1:
First of all lets understand the usage of Places.GEO_DATA_API
It says that "The Geo Data API provides access to getting information about places by place ID, autocompleting a user's search query by name or address, and adding new places to Google's Places database."
source (https://developers.google.com/android/reference/com/google/android/gms/location/places/GeoDataApi)
So if we want to get place information from place id then we have to
use below code:
// Define a Place ID.
String placeId = "INSERT_PLACE_ID_HERE";
// Specify the fields to return (in this example all fields are returned).
List<Place.Field> placeFields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
// Construct a request object, passing the place ID and fields array.
FetchPlaceRequest request = FetchPlaceRequest.builder(placeId, placeFields).build();
placesClient.fetchPlace(request).addOnSuccessListener((response) -> {
Place place = response.getPlace();
Log.i(TAG, "Place found: " + place.getName());
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
int statusCode = apiException.getStatusCode();
// Handle error with given status code.
Log.e(TAG, "Place not found: " + exception.getMessage());
}
});
Problem 2: cannot find symbol variable GeoDataApi
Solution 2: As new places api indicates that "Use findAutocompletePredictions() to return place predictions in response to user search queries. findAutocompletePredictions() functions similarly to getAutocompletePredictions()."
source (https://developers.google.com/places/android-sdk/client-migration)
So to get auto complete predictions we can use below code:
// Create a new token for the autocomplete session. Pass this to FindAutocompletePredictionsRequest,
// and once again when the user makes a selection (for example when calling fetchPlace()).
AutocompleteSessionToken token = AutocompleteSessionToken.newInstance();
// Create a RectangularBounds object.
RectangularBounds bounds = RectangularBounds.newInstance(
new LatLng(-33.880490, 151.184363),
new LatLng(-33.858754, 151.229596));
// Use the builder to create a FindAutocompletePredictionsRequest.
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
// Call either setLocationBias() OR setLocationRestriction().
.setLocationBias(bounds)
//.setLocationRestriction(bounds)
.setCountry("au")
.setTypeFilter(TypeFilter.ADDRESS)
.setSessionToken(token)
.setQuery(query)
.build();
placesClient.findAutocompletePredictions(request).addOnSuccessListener((response) -> {
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Log.i(TAG, prediction.getPlaceId());
Log.i(TAG, prediction.getPrimaryText(null).toString());
}
}).addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.e(TAG, "Place not found: " + apiException.getStatusCode());
}
});

Replace GoogleApiClient with GeoDataClient
mGoogleApiClient = Places.getGeoDataClient(this, null);
Replace AutocompletePredictionBuffer with AutocompletePredictionBufferResponse
private ArrayList getAutocomplete(CharSequence constraint) {
if (mGoogleApiClient != null) {
// Submit the query to the autocomplete API and retrieve a PendingResult that will
// contain the results when the query completes.
Task<AutocompletePredictionBufferResponse> results = mGoogleApiClient.getAutocompletePredictions(constraint.toString(), null, mPlaceFilter);
// This method should have been called off the main UI thread. Block and wait for at most 60s
// for a result from the API.
try {
Tasks.await(results, 60, TimeUnit.SECONDS);
} catch (ExecutionException | InterruptedException | TimeoutException e) {
Utils.handleException(e);
}
AutocompletePredictionBufferResponse autocompletePredictions = results.getResult();
// Freeze the results immutable representation that can be stored safely.
return DataBufferUtils.freezeAndClose(autocompletePredictions);
}
return null;
}

Related

Android Task is not Completing using Places API

I am trying to basically copy the code from the Places API docs, found here, however, while the code seems to work, the task never returns successful or complete and not executing that code block. This is my code, but it is mostly the same as the Google docs with some changes.
public void refreshLocation(TextView textView, PlacesClient placesClient) {
// Use fields to define the data types to return.
textView.setText("Loading...");
List<Place.Field> placeFields = Collections.singletonList(Place.Field.NAME);
// Use the builder to create a FindCurrentPlaceRequest.
FindCurrentPlaceRequest request = FindCurrentPlaceRequest.newInstance(placeFields);
textView.setText("Starting task . . .");
Task<FindCurrentPlaceResponse> placeResponse = placesClient.findCurrentPlace(request);
textView.setText("Task set . . .");
placeResponse.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Double likelihood = 0.0;
String name = "";
FindCurrentPlaceResponse response = task.getResult();
for (PlaceLikelihood placeLikelihood : response.getPlaceLikelihoods()) {
textView.setText("Task successful");
if (placeLikelihood.getLikelihood() > likelihood) {
likelihood = placeLikelihood.getLikelihood();
name = placeLikelihood.getPlace().getName();
}
}
if (likelihood != 0.0) {
likelihood = likelihood * 100;
textView.setText(String.format("You are at {}. \n {}% accurate", name, likelihood));
} else {
textView.setText("Error: No Location Found.");
}
} else {
Exception exception = task.getException();
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
Log.e(TAG, "Place not found: " + apiException.getStatusCode());
}
}
});
}
Am I missing something in regards to starting the task? Is there some way to kick it off or execute it? Is this something that would be solved with AsyncTask, even though the Google Docs don't use it?

PlaceAutocompleteAdapter with Places SDK compat Library

I am working on google maps and search.
The only option to search on the map is the Google Places API.
https://developers.google.com/places/android-sdk/intro
Which also states that you play service version of SDK is deprecated.
So I was trying to implement it with the new SDK.
Now what I want is instead of Autocomplete to Open a new Activity I want it to be displayed as a list on my autocomplete.
So I tried to implement this : https://github.com/googlesamples/android-play-places/blob/master/PlaceCompleteAdapter/Application/src/main/java/com/example/google/playservices/placecomplete/PlaceAutocompleteAdapter.java
But the issue is it works with Play service version but not with Compat version because the classes and imports are different.
This is the part of the code that I am having trouble with :
// Submit the query to the autocomplete API and retrieve a PendingResult that will
// contain the results when the query completes.
PendingResult<AutocompletePredictionBuffer> results =
Places.GeoDataApi
.getAutocompletePredictions(mGoogleApiClient, constraint.toString(),
mBounds, mPlaceFilter);
// This method should have been called off the main UI thread. Block and wait for at most 60s
// for a result from the API.
AutocompletePredictionBuffer autocompletePredictions = results
.await(60, TimeUnit.SECONDS);
// Confirm that the query completed successfully, otherwise return null
final Status status = autocompletePredictions.getStatus();
if (!status.isSuccess()) {
Toast.makeText(getContext(), "Error contacting API: " + status.toString(),
Toast.LENGTH_SHORT).show();
Log.e(TAG, "Error getting autocomplete prediction API call: " + status.toString());
autocompletePredictions.release();
return null;
}
If anyone has implemented PlacesAutoCompleteAdapter with New Places API library. Please guide me with changing the above code.
Thank you.
Reference link:
https://developers.google.com/places/android-sdk/autocomplete#get_place_predictions_programmatically
Step 1. Intialize new PlaceClient
// Initialize Places.
Places.initialize(getApplicationContext(), apiKey);
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
Step 2. Create request
// contain the results when the query completes.
FindAutocompletePredictionsRequest request = FindAutocompletePredictionsRequest.builder()
// similar to previous mBounds
// but you have to use Rectangular bounds (Check reference link)
.setLocationRestriction(mBounds)
.setQuery(constraint.toString()) // similar to previous constraint
.setTypeFilter(TypeFilter.ADDRESS) // similar to mPlaceFilter
.build();
Step 3. Send request object to response method
Task<FindAutocompletePredictionsResponse> task =
placeClient.findAutocompletePredictions(request);
Step 4. Handle OnSuccess code here
task.addOnSuccessListener(
(response) -> {
for (AutocompletePrediction prediction : response.getAutocompletePredictions()) {
Timber.d("prediction result: " + prediction);
// add result to your arraylist
}
// return your arraylist outside foreach loop
});
Step 5. Handle OnFailure code here
task.addOnFailureListener((exception) -> {
if (exception instanceof ApiException) {
ApiException apiException = (ApiException) exception;
// places not found exception code
Timber.i("error message %s", apiException.getMessage());
}
});
Step 6. Handle OnComplete code here
task.addOnCompleteListener((response) -> {
Exception e = task.getException();
if (e instanceof ApiException) {
ApiException apiException = (ApiException) e;
if (!task.isSuccessful()) {
// your code
}
}
});
}

Mapbox Offlne (Android)

I'm working on MapBox off line. The code was OK, able to download map but after adding some peice of code which have nothing to do with the map, the download stop to work and the give an HTTP401 Error.
I've noticed that depending on where you call MapboxAccountManager.start sometimes it fails.
Here's the code:
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
DB_Handler db_ansb = new DB_Handler(Init_Carte.this,null,null,1);
// Get data from DB, about the map
HashMap<String, String> data_mapbox = db_ansb.do_get_mapbox(0);
the_mapbox_token = data_mapbox.get("tmapbox_token");
the_mapbox_style = data_mapbox.get("tmapbox_style");
the_mapbox_zoom_min = Integer.parseInt(data_mapbox.get("tmapbox_zoom_min"));
the_mapbox_zoom_max = Integer.parseInt(data_mapbox.get("tmapbox_zoom_max"));
the_mapbox_inter = Double.parseDouble(data_mapbox.get("tmapbox_inter"));
OfflineManager offlineManager = OfflineManager.getInstance(this);
MapboxAccountManager.start(this,the_mapbox_token);
setContentView(R.layout.activity_init_carte);
// Menu with APP compat
// https://developer.android.com/training/appbar/setting-up.html
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
// Find our truck GPS position for road map
HashMap<String, String> my_truck = db_ansb.do_get_my_truck();
String str_truck_lagps = my_truck.get("frota_lagps");
String str_truck_logps = my_truck.get("frota_logps");
the_lagps_truck = Double.parseDouble(str_truck_lagps);
the_logps_truck = Double.parseDouble(str_truck_logps);
// Find accident location for road map
HashMap<String, String> my_inter = db_ansb.do_get_inter_resume();
String str_inter_lagps = my_inter.get("inter_lagps");
String str_inter_logps = my_inter.get("inter_logps");
the_lagps_inter = Double.parseDouble(str_inter_lagps);
the_logps_inter = Double.parseDouble(str_inter_logps);
// Compute area to get
HashMap<String, Double> data_gps_inter = db_ansb.do_get_bounds_inter(the_lagps_inter,the_logps_inter,the_mapbox_inter);
final double inter_lagps_ne = data_gps_inter.get("inter_max_lagps"); // Nord Est
final double inter_logps_ne = data_gps_inter.get("inter_max_logps");
final double inter_lagps_so = data_gps_inter.get("inter_min_lagps"); // Sud Ouest
final double inter_logps_so = data_gps_inter.get("inter_min_logps");
// Display what we're doing
tmp_id_msg = (TextView) findViewById(R.id.txt_action);
tmp_id_msg.setText(R.string.str_telechargement_carte);
// Create zone
LatLngBounds latLngBounds = new LatLngBounds.Builder()
.include(new LatLng(inter_lagps_ne, inter_logps_ne)) // Northeast
.include(new LatLng(inter_lagps_so, inter_logps_so)) // Southwest
.build();
OfflineTilePyramidRegionDefinition definition = new OfflineTilePyramidRegionDefinition(
the_mapbox_style,
latLngBounds,
the_mapbox_zoom_min,
the_mapbox_zoom_max,
(Init_Carte.this).getResources().getDisplayMetrics().density);
byte[] metadata;
try
{
JSONObject jsonObject = new JSONObject();
jsonObject.put(JSON_FIELD_REGION_NAME, "Carte");
String json = jsonObject.toString();
metadata = json.getBytes(JSON_CHARSET);
} catch (Exception e)
{
Log.e("TAG", "Failed to encode metadata: " + e.getMessage());
metadata = null;
}
// Get data
offlineManager.createOfflineRegion(definition, metadata, new OfflineManager.CreateOfflineRegionCallback()
{
#Override
public void onCreate(OfflineRegion offlineRegion)
{
offlineRegion.setDownloadState(OfflineRegion.STATE_ACTIVE);
// Monitor the download progress using setObserver
offlineRegion.setObserver(new OfflineRegion.OfflineRegionObserver()
{
#Override
public void onStatusChanged(OfflineRegionStatus status)
{
Log.i("DBUG","onStatusChanged");
// Calculate the download percentage and update the progress bar
double percentage = status.getRequiredResourceCount() >= 0 ?
(100.0 * status.getCompletedResourceCount() / status.getRequiredResourceCount()) :
0.0;
long long_pourcentage = Math.round(percentage);
String str_pourcentage = Long.toString(long_pourcentage)+" %";
// Display on screen
tmp_id_valeur = (TextView) findViewById(R.id.val_action);
tmp_id_valeur.setText(str_pourcentage);
Log.i("DBUG",str_pourcentage+"%");
if (status.isComplete())
{
// OK so now, ask the road
do_get_trajet();
}
}
#Override
public void onError(OfflineRegionError error)
{
// If an error occurs, print to logcat
Log.i("DBUG", "onError reason: " + error.getReason());
Log.e("DBUG", "onError message: " + error.getMessage());
}
#Override
public void mapboxTileCountLimitExceeded(long limit)
{
// Notify if offline region exceeds maximum tile count
Log.i("DBUG", "Mapbox tile count limit exceeded: " + limit);
}
});
}
#Override
public void onError(String error)
{
Log.e("TAG", "Error: " + error);
}
});
}
I enter the Aysnc part, get 3 or 4 times
Log.i("DBUG",str_pourcentage+"%");
with a value of 0% then get I get:
I/System.out: [CDS]rx timeout:10000
D/NativeCrypto: ssl=0x619629c8 sslWrite buf=0x41e60068 len=222 write_timeout_millis=0
D/NativeCrypto: ssl=0x619629c8 sslRead buf=0x41e60068 len=8192,timeo=10000
I/DBUG: onError reason: REASON_OTHER
E/DBUG: onError message: HTTP status code 401
D/com.mapbox.mapboxsdk.http.HTTPRequest: [HTTP] Request with response code = 401: Unauthorized
I've noticed same strange behaviour on another page: depending on the fact you perform or not, action before of after MapboxAccountManager.start(this,the_mapbox_token); it works or not.
Notice the token is correct.
Any idea?
After changing the token in our DB, it was OK but only for a short time: I was able to download 26% of the map and then, I get again the HTTP 401 message...
Found. In fact there is a small mistake in the code that help me understand: how can this code work sometimes, as I call
OfflineManager offlineManager = OfflineManager.getInstance(this);
MapboxAccountManager.start(this,the_mapbox_token);
so as I call the init after the use of the Lib? In fact all example at Mapbox are made with one activity performing all the jobs. So when you have more than one activity using Mapbox, you quickly believe you need to put a MapboxAccountManager.start in each ones. Which is wrong. In that case (more than one activity), you must call MapboxAccountManager.start at App level. Like that:
public class App_Start extends Application
{
#Override
public void onCreate()
{
super.onCreate();
String the_mapbox_token = "pk.eyJ1IjoiYW5.....";
MapboxAccountManager.start(this,the_mapbox_token);
}
public void customAppMethod()
{
// Custom application method
}
}
and add this class at application level on your Manifest:
<application android:icon="#drawable/ic_launcher" android:label="#string/app_name" android:theme="#style/AppTheme" android:name="net.ansb_brasil.xxxx.App_Start">
Concerning the fact the second activity was performing two times the download, it came from the fact the if (status.isComplete()) part of the onStatusChanged() is always called two times. Seems to be a bug in the Lib. On some example at Mapbox, they use a boolean flag in order to avoid taking two times this call in account.
As my first activity was downloading one map and then call a second activity for a second map, this "double call" had as result two call for the second activity and so many troubles.
Hope this will avoid headaches to others

Country Specific google place autocomplete

I am following http://examples.javacodegeeks.com/android/android-google-places-autocomplete-api-example/ this tutorial to get google place autocomplete in my app,
Now that it is working fine but I need to keep the place suggestion country specific, I have tried giving country like india , china but it is not showing any result.
Could you please help me out and tell where should I need to change the code to get it done.
Thanks,
Prashant
From Documentation for Places API
To get a list of predicted place names and/or addresses, call
GeoDataApi.getAutocompletePredictions(), passing the following
parameters:
Required: A query string containing the text typed by the user.
Required: A LatLngBounds object, restricting the results to a specific
area specified by latitude and longitude bounds.
When making request
You can specify bounds for India.
This can serve you
String apiKey = getString(R.string.places_api_key);
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), apiKey);
PlacesClient placesClient = Places.createClient(this);
}else{
Toast.makeText(PlaceAutocompleteActivity.this, "-----initialize-----", Toast.LENGTH_LONG).show();
}
// Initialize the AutocompleteSupportFragment.
AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
// PlaceFields
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
// autocompleteFragment.setOnPlaceSelectedListener(MapsActivity.this);
try {
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place place) {
displayLocation(place.getLatLng().latitude,place.getLatLng().longitude,place.getName());
Toast.makeText(getApplicationContext(), "getName: " + place.getName() + " getLatLng: "+ place.getLatLng(), Toast.LENGTH_LONG).show();
// Intent i = Intent(this, idnow.se MainActivity.class);
// i.putExtra("getLatLng",place.getLatLng());
// startActivity(i);
// finish();
}
#Override
public void onError(#NonNull Status status) {
Toast.makeText(getApplicationContext(), "" + status.toString(), Toast.LENGTH_LONG).show();
}
});
} catch (Exception e) {
Toast.makeText(PlaceAutocompleteActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
// PlaceFields - HERE
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG));
https://github.com/EddyEU/GooglePlaceAutocomplete

Android get lat&long from google address

I have implemented Google Place API autocomplete functionality for my application like this: https://developers.google.com/places/training/autocomplete-android
No it just makes a Toast with that address.
How can I get the latitude and longitude from the selected address?
Use the method
public List<Address> getFromLocationName (String locationName, int maxResults) from Android Geocoder API, pass in the location name and the maximum number of results you would like and you should be good to go.
Eg.
Geocoder coder = new Geocoder(this);
try {
ArrayList<Address> adresses = (ArrayList<Address>) coder.getFromLocationName("Some Address", 10);
for(Address add : adresses){
double longitude = add.getLongitude();
double latitude = add.getLatitude();
}
} catch (IOException e) {
e.printStackTrace();
} catch(IllegalArgumentException e){
e.printStackTrace();
}
If it helps, I've recently created a library in Java for Google Places API.
Autocompletion is as simple as:
GooglePlaces client = new GooglePlace("apiKey");
List<Prediction> predictions = client.getPlacePredictions("Empire");
for (Prediction prediction : predictions) {
String description = prediction.getDescription();
// etc etc
}
And getting a latitude-longitude from an address is as simple as.
List<Place> places = client.getPlacesByQuery(address, GooglePlaces.MAXIMUM_RESULTS);
for (Place place : places) {
if (place.getAddress().equals(address)) {
double lat = place.getLatitude();
double lng = place.getLongitude();
}
}
https://github.com/windy1/google-places-api-java
You can simply use google maps api to get the lat and long
http://maps.google.com/maps/api/geocode/json?address=&sensor=false
In the above link u have to add the address next to "address=" and u can get the json data with lat and long and some other infos.
Try GeoDataClient. Refer GeoDataClient and Place IDs and details.
geoDataClient.getPlaceById(autoCompletePredictionItem.getPlaceId())
.addOnCompleteListener(new OnCompleteListener<PlaceBufferResponse>() {
#Override
public void onComplete(#NonNull Task<PlaceBufferResponse> task) {
if (task.isSuccessful()) {
PlaceBufferResponse places = task.getResult();
Place myPlace = places.get(0);
Log.e(TAG, "Place found: " + myPlace.getLatLng().toString());
places.release();
} else {
Log.e(TAG, "Place not found.");
}
}
});
According to updated documents, GeoDAtaClient is deprecated. New way is to use this:
// Define a Place ID. val placeId = "INSERT_PLACE_ID_HERE"
// Specify the fields to return. val placeFields = listOf(Place.Field.ID, Place.Field.NAME)
// Construct a request object, passing the place ID and fields array. val request = FetchPlaceRequest.newInstance(placeId, placeFields)
placesClient.fetchPlace(request)
.addOnSuccessListener { response: FetchPlaceResponse ->
val place = response.place
Log.i(PlaceDetailsActivity.TAG, "Place found: ${place.name}")
}.addOnFailureListener { exception: Exception ->
if (exception is ApiException) {
Log.e(TAG, "Place not found: ${exception.message}")
val statusCode = exception.statusCode
TODO("Handle error with given status code")
}
}
https://developers.google.com/maps/documentation/places/android-sdk/place-details#maps_places_get_place_by_id-kotlin

Categories

Resources