Get country code from PlaceAutocomplete android (Google Places API) - android

We are using Google PlaceAutocomplete for city picker. We need to get country code for picked city. I am trying to use place.getLocale() but its null. Is there a way I can get Country ISO code from PlaceAutocomplete returned data.
in gradle:
compile 'com.google.android.gms:play-services-places:10.0.1'
code:
private void openCityPicker() {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_CITIES)
.build();
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
.setFilter(typeFilter)
.build(this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
com.google.android.gms.location.places.Place googleApiPlace = PlaceAutocomplete.getPlace(this, data);
Log.d(TAG, "onActivityResult: " + googleApiPlace.getAddress());
Log.d(TAG, " googleApiPlace.getLocale().getCountry(): " + googleApiPlace.getLocale().getCountry());
Log.d(TAG, " googleApiPlace.getLocale().getDisplayCountry(): " + googleApiPlace.getLocale().getDisplayCountry());
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}

late but right answer
you can get country code using this
add Place.Field.ADDRESS_COMPONENTS field into your fields list
List<Place.Field> fields = Arrays.asList(Place.Field.ADDRESS_COMPONENTS);
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.FULLSCREEN, fields)
.setTypeFilter(TypeFilter.CITIES)
.build(mActivity);
startActivityForResult(intent, requestCode);
when you get the result into onActivityResult() you'll get full details of location into that you will find country
if (place.getAddressComponents() != null) {
List<AddressComponent> addressComponents = place.getAddressComponents().asList();
for (int i = 0; i < addressComponents.size(); i++) {
if (addressComponents.get(i).getTypes().get(0).equals("country")) {
countryCode = addressComponents.get(i).getShortName();
break;
}
}
}

Related

Google maps Autocomplete returns Place with null

I'm trying to get a Place from the Autocomplete of Google maps and then using its' longitude and latitude but every time I get a Place with the right name and all the other attributes got null in them. Does anyone know how to fix that?
Example of a Place I get:
I/System.out: Place{address=null, addressComponents=null, businessStatus=null, attributions=[], id=ChIJOwg_06VPwokRYv534QaPC8g, latLng=null, name=New York, openingHours=null, phoneNumber=null, photoMetadatas=null, plusCode=null, priceLevel=null, rating=null, types=null, userRatingsTotal=null, utcOffsetMinutes=null, viewport=null, websiteUri=null}
The code [the problem is at "setTargetPlace" (method is down the page)]:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place newTargetPlace = Autocomplete.getPlaceFromIntent(data);
System.out.println(newTargetPlace);
dataCenter.setTargetPlace(newTargetPlace);
dataCenter.createParty();
String response = dataCenter.getNextResponse();
System.out.println(response);
String[] commandAndPara = dataCenter.getCommandFromMsg(response);
String command = commandAndPara[0];
String para = commandAndPara[1];
if(command.equals(DataCenter.MSG_OK)) {
dataCenter.setPartyCode(para);
moveToParty();
}
else {
if(command.equals(DataCenter.MSG_FULL)) {
System.out.println("FULL");
}
else { //ERROR
System.out.println("ERROR");
}
}
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
The method:
public void setTargetPlace(Place targetPlace) {
this.targetPlace = targetPlace;
this.target = this.targetPlace.getName();
LatLng targetCords = this.targetPlace.getLatLng();
this.targetX = targetCords.longitude;
this.targetY = targetCords.latitude;
}
The reason why you are getting the latitude and longitude as null is because you didn't include LAT_LNG as part of the fields you want to retrieve. See the code snippet below to see how you can include it
val fields = listOf(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG)
So when you create the intent and pass the field variable, and then go ahead to launch it like this
val intent = Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields)
.build(requireContext())
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE)
it will return with the latitude and longitude in onActivityResult()

How can i clear text of selected Place name from AutocompleteSupportFragment?

i create my project for ride booking app. I use AutocompleteSupportFragment for search place . After selecting Place , i filter that location if you are in Delhi then set Text of AutocompleteSupportFragment other wise set Hint like "Please select valid place".
I try
autocompleteFragment_to.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(#NonNull Place place) {
if (!getStateName(place.getLatLng().latitude, place.getLatLng().longitude).equals("Madhya Pradesh")) {
Common.myLatLong = null;
Common.placeName1 = null;
Common.placeName1City = null;
Log.e("FRagmentData",""+autocompleteFragment_to.a.getText().toString());
autocompleteFragment_to.a.getText().toString();
autocompleteFragment_to.a.setText("");
autocompleteFragment_to.a.setHint("Please select Valid Place");
autocompleteFragment_to.getView().findViewById(R.id.places_autocomplete_clear_button).performClick();
autocompleteFragment_to.a.setText("");
Toast.makeText(context, "Please select Valid Place", Toast.LENGTH_SHORT).show();
} else {
destination = place.getLatLng();
Common.myLatLong = place.getLatLng();
Common.placeName1 = place.getName();
Log.e("FRagmentData",""+autocompleteFragment_to.a.getText().toString());
Common.placeName1City = getAddress(context, place.getLatLng().latitude, place.getLatLng().longitude);
if (mMap != null) {
mMap.clear();
}
mapFragment.getMapAsync(MainActivity.this);
}
}
#Override
public void onError(#NonNull Status status) {
Toast.makeText(context, "try again later", Toast.LENGTH_SHORT).show();
}
});
I try all these approch but it's not working
Use AutoComplete IntentBuilder instead of fragment..
Just initialise Places inside oncreate()
// Initialize Places.
Places.initialize(getApplicationContext(), "***YOUR API KEY***");
// Create a new Places client instance.
PlacesClient placesClient = Places.createClient(this);
then call intentbuilder in textview.onclick()
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.FULLSCREEN, fields)
.build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
onActivity result you will get selected place.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
// TODO: Handle the error.
Status status = Autocomplete.getStatusFromIntent(data);
Log.i(TAG, status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
After that, just set the selected place in the Textview.
Textview.setText(place.getName());
refer:https://stackoverflow.com/a/55045772/10579969

AutocompleteActivity Google Places API onActivityResult nothing happening

I followed this guide on implementing placesautocomplete
https://developers.google.com/places/android-sdk/autocomplete
I followed the intent one not the fragment. Nothing happens when I select a place. It just shows me this picture when I click on a place :
enter image description here
I tried implementing the fragment version but same thing. Nothing happens.
#OnClick(R.id.editText) void searchLocation() {
List<Place.Field> fields = Arrays.asList(Place.Field.ID, Place.Field.NAME);
Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, fields).setTypeFilter(TypeFilter.ADDRESS).setCountry("PH").build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
displayLocationSettingsRequest(getApplicationContext());
break;
case AUTOCOMPLETE_REQUEST_CODE:
if (resultCode == RESULT_OK) {
Place place = Autocomplete.getPlaceFromIntent(data);
LatLng latLng = place.getLatLng();
String address = place.getAddress();
if (getIntent().getIntExtra("switch", 0) == 0) {
returnIntent.putExtra("pickup", address);
returnIntent.putExtra("latlng", latLng);
} else {
returnIntent.putExtra("dropoff", address);
returnIntent.putExtra("latlng", latLng);
}
selectedAddress = address;
editText.setText(address);
location.setText(address);
Toast.makeText(getApplicationContext(), address, Toast.LENGTH_SHORT).show();
} else if (resultCode == AutocompleteActivity.RESULT_ERROR) {
Status status = Autocomplete.getStatusFromIntent(data);
Toast.makeText(getApplicationContext(), status.toString(), Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
Toast.makeText(getApplicationContext(), "CANCELLED", Toast.LENGTH_SHORT).show();
}
}
}
I am forced to cancel the operation as selecting a place doesnt do anything and so resultcode always returns RESULT_CANCELLED

google placeautocomplete view close automatically

I have a problem with google map api. I used Api Key in my project and also i linked release SHA1 Key. It is working correctly in debug apk, but in release apk place autocompleteview is close automatically. I checked the Logcat, in logcat the api key is different from the key i used in meta-data in android manifest file.
private void manualLocation() {
try {
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN).build((Activity) context);
startActivityForResult(intent, 1);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
Log.e("Tag", "Place: " + place.getAddress() + place.getPhoneNumber());
Log.e("Tag", "Place: " + place.getLatLng() + place.getPlaceTypes());
if (signup.matches("1")) {
latitude = String.valueOf(place.getLatLng().latitude);
longitude = String.valueOf(place.getLatLng().longitude);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
Log.e("Tag", status.getStatusMessage());
locationStatus = "0";
AppPreferences.savePreferences(Location.this, "locationStatus", locationStatus);
} else if (resultCode == RESULT_CANCELED) {
locationStatus = "0";
AppPreferences.savePreferences(Location.this, "locationStatus", locationStatus);
// The user canceled the operation.
}
}
}
}
I used the key in meta-data "AIzaSyBH9saN7RRHev1QNKWqtIjejojvqJuCswU" but in Logcat the key is different. i show you the Logcat. Can anyone help me?
BasicNetwork.performRequest: Unexpected response code 403 for https://www.googleapis.com/placesandroid/v1/autocompleteWidget?key=AIzaSyBb2MNLJEmWt-FLJqN28D_-WuxQiMwzUhU
this is the Logcat response

android app implement google auto complete activity for 2 inputs

I have 2 edit text inputs in my app.One is from place and another one to place.For these 2 inputs I have implemented google auto complete activity but problem when user click on any one of these inputs google autocomplete intent after user place selection completed intent call onActivityResult().
In onActivityResult() how to know which input clicked.
here is my code
fromPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
toPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
String fullName= (String) place.getAddress();
#// here I want to know which input clicked and set fullname in input text#
fromPlaceEdit.setText(fullName);
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
Log.i("fdfdf", status.getStatusMessage());
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
I did it different way.
I have created two global boolean value each for from place and to place.
then when user click on from place or to place change boolean value of same place then on onActivityResult check which boolean value is true and set result place name to same input box.
Code follows:
public boolean fromplaceSlected =false ;
public boolean toplaceSlected =false;
fromPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
toPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
.setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS).setTypeFilter(AutocompleteFilter.TYPE_FILTER_GEOCODE)
.build();
Intent intent =
new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY).setFilter(typeFilter)
.build(MainActivity.this);
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("request", String.valueOf(requestCode));
// Check that the result was from the autocomplete widget.
if (requestCode == REQUEST_CODE_AUTOCOMPLETE) {
if (resultCode == RESULT_OK) {
// Get the user's selected place from the Intent.
Place place = PlaceAutocomplete.getPlace(getContext(), data);
String fullName = (String) place.getAddress();
if(fromplaceSlected){
Log.e("from place",fullName);
fromPlaceEdit.setText(fullName);
fromplaceSlected=false;
toplaceSlected=false;
}
else if(toplaceSlected){
Log.e("toplace" ,fullName);
toPlaceEdit.setText(fullName);
fromplaceSlected=false;
toplaceSlected=false;
}
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getContext(), data);
Log.e("sdsdsdd", "Error: Status = " + status.toString());
fromplaceSlected=false;
toplaceSlected=false;
} else if (resultCode == RESULT_CANCELED) {
// Indicates that the activity closed before a selection was made. For example if
// the user pressed the back button.
fromplaceSlected=false;
toplaceSlected=false;
}
}
}
Your code may work, but it's a bit hacky. Here is the good way to do it:
public static final int PLACE_AUTOCOMPLETE_FROM_PLACE_REQUEST_CODE=1;
public static final int PLACE_AUTOCOMPLETE_TO_PLACE_REQUEST_CODE=2;
fromPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Do your stuff from place
startActivityForResult(intent, PLACE_AUTOCOMPLETE_FROM_PLACE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
toPlaceEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
//Do your stuff to place
startActivityForResult(intent, PLACE_AUTOCOMPLETE_TO_PLACE_REQUEST_CODE);
} catch (GooglePlayServicesRepairableException e) {
// TODO: Handle the error.
} catch (GooglePlayServicesNotAvailableException e) {
// TODO: Handle the error.
}
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_FROM_PLACE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
//Do your ok >from place< stuff here
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
//Handle your error >from place<
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
} else if (requestCode == PLACE_AUTOCOMPLETE_TO_PLACE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
//Do your ok >to place< stuff here
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
//Handle your error >to place<
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
From documentation:
requestCode int: If >= 0, this code will be returned in onActivityResult() when the activity exits.

Categories

Resources