Get country code from PlaceAutocompleteFragment android (Google Places API) - android
In Google Places API for Android, I am using PlaceAutocompleteFragment for displaying the city/country.
Here am getting the address, name, placeId, etc.
Place object contains only these fields.
#Override
public void onPlaceSelected(Place place) {
Log.i(TAG, "Place Selected: " + place.getName());
// Format the returned place's details and display them in the TextView.
mPlaceDetailsText.setText(formatPlaceDetails(getResources(), place.getName(), place.getId(),
place.getAddress(), place.getPhoneNumber()+" "+place.getAttributions()+" :: "+place.getLocale(), place.getWebsiteUri()));
}
But I want country code also. Is there any way to get the country code from places API ?
If no, Is there any alternate service for getting the country name & code while typing ?
With the Place object retrieved, you can get the Locale object associated :
Locale locale = place.getLocale();
With this Locale object you can then get the Country code via :
locale.getCountry();
And the country name with :
locale.getDisplayCountry();
You can look to more available methods at the docs :
http://developer.android.com/reference/java/util/Locale.html
EDIT :
If Locale from the Place object is null you can use a Geocoder to get information from GPS coordinates :
LatLng coordinates = place.getLatLng(); // Get the coordinates from your place
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(
coordinates.latitude,
coordinates.longitude,
1); // Only retrieve 1 address
Address address = addresses.get(0);
Then you can call these methods to get the informations you want
address.getCountryCode();
address.getCountryName();
More methods on the Address objects : http://developer.android.com/reference/android/location/Address.html
Be aware that the Geocoder methods should be call on a background thread to not block the UI and that it could also retrieve no answer.
This will give the correct country code.
TelephonyManager tm = (TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE);
String countryCode = tm.getSimCountryIso();
Here all answer points to either deprecated SDK or using TelephonyManager or GeoCoder(while OP clearly mentioned getting the country code from places SDK response. I also it should be obvious that choosing a country or country code from the OS(TelephonyManager or GeoCoder) should not necessarily match the location returned by the User selected location from the picker).
In the newer places SDK(com.google.android.libraries.places:places:2.4.0), I am managed to get the country code by following the code snippet
Make sure to include the following field(in addition to what more you require)
val fields = listOf(
Place.Field.ADDRESS_COMPONENTS,
// ... More fields that you need
)
And to parse the country code follow this code
place.addressComponents.asList().find { it.types.contains("country") }.shortName
Related
Google map API return incorrect result for searches
I am new to coding in android and I am trying to use the google map API to display places nearby. My code is: public void onClick(View v) { mMap.clear(); String search = "cvs" String url = getUrl(latitude, longitude, search); Object[] dataTransfer = new Object[2]; dataTransfer[0] = mMap; dataTransfer[1] = url; GetNearbyData getNearbyData = new GetNearbyData(); getNearbyData.execute(dataTransfer); } private String getUrl(double latitude, double longitude, String nearbyPlace) { StringBuilder googlePlacesUrl = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?"); googlePlacesUrl.append("location=" + latitude + "," + longitude); googlePlacesUrl.append("&radius=" + PROXIMITY_RADIUS); googlePlacesUrl.append("&type=" + nearbyPlace); googlePlacesUrl.append("&sensor=true"); googlePlacesUrl.append("&key=" + "{MY_KEY}"); return (googlePlacesUrl.toString()); } the URL output is: https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7692494,-73.9842065&radius=10000&type=cvs&sensor=true&key={MY_KEY} The problem starts when I change the search word, when I put (under the URL type) cvs/parks/starbucks... (and probably other places) I keep getting the same result. For example: if my location is central park NY, I keep getting results for Chrysler Building Hotel Pennsylvania Hudson New York and more. Those palaces are not related to my search word (cvs/parks/starbucks...) Important note is that for banks I do get banks' results. Can anyone explain me how to solve this problem? why for some words I do get correct results and for other I do not? Thanks
Please note that none of cvs, parks or starbucks belong to the list of supported types that you can use in nearby search. You can consult the list of supported types in the official Places API documentation: https://developers.google.com/places/supported_types I believe you have to use a keyword parameter when you construct the URL instead of the type parameter. keyword — A term to be matched against all content that Google has indexed for this place, including but not limited to name, type, and address, as well as customer reviews and other third-party content. source: https://developers.google.com/places/web-service/search#PlaceSearchRequests For example if I search 'cvs' https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7692494%2C-73.9842065&radius=10000&keyword=cvs&key=MY_API_KEY I can see places that are relevant for this search as shown in my screenshot Search for 'parks' https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7692494%2C-73.9842065&radius=10000&keyword=parks&key=MY_API_KEY gives me the following results Finally search for 'starbucks' https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=40.7692494%2C-73.9842065&radius=10000&keyword=starbucks&key=MY_API_KEY returns Starbucks places I hope this helps!
Limit Geocoder getFromLocationName scope to one specific City
The following is my method: List<Address> addresses = null; addresses = new Geocoder(passengerHomeActivity).getFromLocationName(this.addressInput.getText().toString(), 1); is there any way to limit the Geocoder getFromLocationName's scope to one specific city? Sometimes when I enter an Address without writing the city name, it leads me to an address which is the same but in another city. My idea is by getting the latitude and longitude of the user, get the value of the city, and set the limit scope to the getFromLocationName method, but I don't have any clue with the implementation. Thanks
Use this code: List<Address> addresses = new Geocoder(passengerHomeActivity).getFromLocationName((this.addressInput.getText().toString()) + ", YourCity, YourCountry", 1);`
Use the constructor passing the the Locale. Geocoder(Context context, Locale locale) Use it like this: Locale locale = new Locale(Locale.getDefault().getLanguage(), "US"); Geocoder geo = new Geocoder(context, locale) addresses = geo.getFromLocationName(term, 1); Notice that this is an aproach, because it will give you the result in that country unless nothing is found (in which case will return worldwide anyway).
How to get the latitude and longitude from city name in android?
In my application am setting a default value to latitude and longitude. When i type the cityname in edittext i need to move that point to that place where i need
Use the below code to get the lat and long of city name String location=cityName; String inputLine = ""; String result = "" location=location.replaceAll(" ", "%20"); String myUrl="http://maps.google.com/maps/geo?q="+location+"&output=csv"; try{ URL url=new URL(myUrl); URLConnection urlConnection=url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); while ((inputLine = in.readLine()) != null) { result=inputLine; } String lat = result.substring(6, result.lastIndexOf(",")); String longi = result.substring(result.lastIndexOf(",") + 1); } catch(Exception e){ e.printStackTrace(); }
My suggestion is to use Google GeoCoding REST API , not Geocoder. Because I once used it in my country,China,I have a error below: "java.io.IOException: Service not Available" after search , It`s seems that "The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists." So I turn to Google GeoCoding REST API , It`s easy , just request like this: http://maps.googleapis.com/maps/api/geocode/json?address=NewYork&sensor=false You will get a json that has geo location in it. And You can also get Address from locaiton through it: http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=false If you can read Chinese , I have a blog about this,check this out: http://wangchao.de/android%E5%88%A9%E7%94%A8google-geocoding-api%E6%9B%BF%E4%BB%A3geocoder-%E8%A7%A3%E5%86%B3%E5%9C%B0%E5%9D%80%E8%AF%AD%E8%A8%80%E9%97%AE%E9%A2%98
Use the Geocoder class. Geocode gc = new Geocoder(); List<Address> ads = gc.getFromLocationName(cityName,maxResults); From the docs : A class for handling geocoding and reverse geocoding. Geocoding is the process of transforming a street address or other description of a location into a (latitude, longitude) coordinate. Reverse geocoding is the process of transforming a (latitude, longitude) coordinate into a (partial) address. The amount of detail in a reverse geocoded location description may vary, for example one might contain the full street address of the closest building, while another might contain only a city name and postal code. The Geocoder class requires a backend service that is not included in the core android framework. The Geocoder query methods will return an empty list if there no backend service in the platform. Use the isPresent() method to determine whether a Geocoder implementation exists.
Try to get the GeoPoint of cityname GeoPoint startGP = new GeoPoint( (int) (Double.parseDouble(cityname.getText()) * 1E6)); Then u can able to get the latitude and longitude from GeoPoint by using below code. Double.toString((double)startGP.getLatitudeE6() / 1E6), Double.toString((double)dest.getLongitudeE6() / 1E6)
"Google Map" how can we get Lattitude and Longitude by passing the Address
In Google Maps how can we get Latitude and Longitude by passing the Address? and what is the Address format need to be mentioned?
To find latitude and longitude from address string ..... Make object of Geocoder Call getFromLocationName() pass the address (place name) string as argument also maximum number of results you want for that place name Here is demo ... Geocoder coder = new Geocoder(LocationMap.this); List<Address> geocodeResults = coder.getFromLocationName(placeName, 10); Iterator<Address> locations = geocodeResults.iterator(); while (locations.hasNext()) { Address loc = locations.next(); _lattitude_ = loc.getLatitude() ; _longidude_ = loc.getLongitude(); } And there are no specific address format required. For example you can try any city name, country name, hotel name, area name, road name, well known place name ( Try "Eiffel tower") ... anything (from many things).
Found this older post. Should solve your problem.
how to find continent in particular location using Geocoder in android app
i am developing android application using Geocoder services, I have an application where I try to get address of a location based on the latitude,longitude coordinates its working fine. my problem is how to get continent of particular address. example : double lat=17; double lon=78.49; List addresses = new Geocoder(Shout.this,Locale.getDefault()).getFromLocation(lat, lon, 1); i am using this code output is India,Hyderabad this address related how to find continent ,please help me some valuable solution. i am getting country name dynamically using geocoder is their any chance to get in continent name along with country.it is difficult to maintain statically i need dynamically any free services find continent based services Thanks In Advance
As we have limited number of Continents, it's good to use static list of data. We can use below json_str (found here) which have CountryCode & Continent String json_str = "{\"AD\":\"Europe\",\"AE\":\"Asia\",\"AF\":\"Asia\",\"AG\":\"North America\",\"AI\":\"North America\",\"AL\":\"Europe\",\"AM\":\"Asia\",\"AN\":\"North America\",\"AO\":\"Africa\",\"AQ\":\"Antarctica\",\"AR\":\"South America\",\"AS\":\"Australia\",\"AT\":\"Europe\",\"AU\":\"Australia\",\"AW\":\"North America\",\"AZ\":\"Asia\",\"BA\":\"Europe\",\"BB\":\"North America\",\"BD\":\"Asia\",\"BE\":\"Europe\",\"BF\":\"Africa\",\"BG\":\"Europe\",\"BH\":\"Asia\",\"BI\":\"Africa\",\"BJ\":\"Africa\",\"BM\":\"North America\",\"BN\":\"Asia\",\"BO\":\"South America\",\"BR\":\"South America\",\"BS\":\"North America\",\"BT\":\"Asia\",\"BW\":\"Africa\",\"BY\":\"Europe\",\"BZ\":\"North America\",\"CA\":\"North America\",\"CC\":\"Asia\",\"CD\":\"Africa\",\"CF\":\"Africa\",\"CG\":\"Africa\",\"CH\":\"Europe\",\"CI\":\"Africa\",\"CK\":\"Australia\",\"CL\":\"South America\",\"CM\":\"Africa\",\"CN\":\"Asia\",\"CO\":\"South America\",\"CR\":\"North America\",\"CU\":\"North America\",\"CV\":\"Africa\",\"CX\":\"Asia\",\"CY\":\"Asia\",\"CZ\":\"Europe\",\"DE\":\"Europe\",\"DJ\":\"Africa\",\"DK\":\"Europe\",\"DM\":\"North America\",\"DO\":\"North America\",\"DZ\":\"Africa\",\"EC\":\"South America\",\"EE\":\"Europe\",\"EG\":\"Africa\",\"EH\":\"Africa\",\"ER\":\"Africa\",\"ES\":\"Europe\",\"ET\":\"Africa\",\"FI\":\"Europe\",\"FJ\":\"Australia\",\"FK\":\"South America\",\"FM\":\"Australia\",\"FO\":\"Europe\",\"FR\":\"Europe\",\"GA\":\"Africa\",\"GB\":\"Europe\",\"GD\":\"North America\",\"GE\":\"Asia\",\"GF\":\"South America\",\"GG\":\"Europe\",\"GH\":\"Africa\",\"GI\":\"Europe\",\"GL\":\"North America\",\"GM\":\"Africa\",\"GN\":\"Africa\",\"GP\":\"North America\",\"GQ\":\"Africa\",\"GR\":\"Europe\",\"GS\":\"Antarctica\",\"GT\":\"North America\",\"GU\":\"Australia\",\"GW\":\"Africa\",\"GY\":\"South America\",\"HK\":\"Asia\",\"HN\":\"North America\",\"HR\":\"Europe\",\"HT\":\"North America\",\"HU\":\"Europe\",\"ID\":\"Asia\",\"IE\":\"Europe\",\"IL\":\"Asia\",\"IM\":\"Europe\",\"IN\":\"Asia\",\"IO\":\"Asia\",\"IQ\":\"Asia\",\"IR\":\"Asia\",\"IS\":\"Europe\",\"IT\":\"Europe\",\"JE\":\"Europe\",\"JM\":\"North America\",\"JO\":\"Asia\",\"JP\":\"Asia\",\"KE\":\"Africa\",\"KG\":\"Asia\",\"KH\":\"Asia\",\"KI\":\"Australia\",\"KM\":\"Africa\",\"KN\":\"North America\",\"KP\":\"Asia\",\"KR\":\"Asia\",\"KW\":\"Asia\",\"KY\":\"North America\",\"KZ\":\"Asia\",\"LA\":\"Asia\",\"LB\":\"Asia\",\"LC\":\"North America\",\"LI\":\"Europe\",\"LK\":\"Asia\",\"LR\":\"Africa\",\"LS\":\"Africa\",\"LT\":\"Europe\",\"LU\":\"Europe\",\"LV\":\"Europe\",\"LY\":\"Africa\",\"MA\":\"Africa\",\"MC\":\"Europe\",\"MD\":\"Europe\",\"ME\":\"Europe\",\"MG\":\"Africa\",\"MH\":\"Australia\",\"MK\":\"Europe\",\"ML\":\"Africa\",\"MM\":\"Asia\",\"MN\":\"Asia\",\"MO\":\"Asia\",\"MP\":\"Australia\",\"MQ\":\"North America\",\"MR\":\"Africa\",\"MS\":\"North America\",\"MT\":\"Europe\",\"MU\":\"Africa\",\"MV\":\"Asia\",\"MW\":\"Africa\",\"MX\":\"North America\",\"MY\":\"Asia\",\"MZ\":\"Africa\",\"NA\":\"Africa\",\"NC\":\"Australia\",\"NE\":\"Africa\",\"NF\":\"Australia\",\"NG\":\"Africa\",\"NI\":\"North America\",\"NL\":\"Europe\",\"NO\":\"Europe\",\"NP\":\"Asia\",\"NR\":\"Australia\",\"NU\":\"Australia\",\"NZ\":\"Australia\",\"OM\":\"Asia\",\"PA\":\"North America\",\"PE\":\"South America\",\"PF\":\"Australia\",\"PG\":\"Australia\",\"PH\":\"Asia\",\"PK\":\"Asia\",\"PL\":\"Europe\",\"PM\":\"North America\",\"PN\":\"Australia\",\"PR\":\"North America\",\"PS\":\"Asia\",\"PT\":\"Europe\",\"PW\":\"Australia\",\"PY\":\"South America\",\"QA\":\"Asia\",\"RE\":\"Africa\",\"RO\":\"Europe\",\"RS\":\"Europe\",\"RU\":\"Europe\",\"RW\":\"Africa\",\"SA\":\"Asia\",\"SB\":\"Australia\",\"SC\":\"Africa\",\"SD\":\"Africa\",\"SE\":\"Europe\",\"SG\":\"Asia\",\"SH\":\"Africa\",\"SI\":\"Europe\",\"SJ\":\"Europe\",\"SK\":\"Europe\",\"SL\":\"Africa\",\"SM\":\"Europe\",\"SN\":\"Africa\",\"SO\":\"Africa\",\"SR\":\"South America\",\"ST\":\"Africa\",\"SV\":\"North America\",\"SY\":\"Asia\",\"SZ\":\"Africa\",\"TC\":\"North America\",\"TD\":\"Africa\",\"TF\":\"Antarctica\",\"TG\":\"Africa\",\"TH\":\"Asia\",\"TJ\":\"Asia\",\"TK\":\"Australia\",\"TM\":\"Asia\",\"TN\":\"Africa\",\"TO\":\"Australia\",\"TR\":\"Asia\",\"TT\":\"North America\",\"TV\":\"Australia\",\"TW\":\"Asia\",\"TZ\":\"Africa\",\"UA\":\"Europe\",\"UG\":\"Africa\",\"US\":\"North America\",\"UY\":\"South America\",\"UZ\":\"Asia\",\"VC\":\"North America\",\"VE\":\"South America\",\"VG\":\"North America\",\"VI\":\"North America\",\"VN\":\"Asia\",\"VU\":\"Australia\",\"WF\":\"Australia\",\"WS\":\"Australia\",\"YE\":\"Asia\",\"YT\":\"Africa\",\"ZA\":\"Africa\",\"ZM\":\"Africa\",\"ZW\":\"Africa\"}"; And From Geocoder() we can get CountryCode like below: try { JSONObject jsonObject = new JSONObject(json_str); Geocoder geocoder = new Geocoder(this, Locale.ENGLISH); List<Address> addresses = geocoder.getFromLocation(latitude, longitude, 1); if (addresses.size() > 0) { Address fetchedAddress = addresses.get(0); // getCountryCode from Address String countryCode = fetchedAddress.getCountryCode(); // get continentName here String continentName = jsonObject.getString(countryCode); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); }
I don't think there is such information given by Google's API. The only solution I can think of is to have some kind of static data structure mapping country names to continent names (which you would presumably have to find yourself somehow, for instance by scraping this web page... ). Then you could text search the string that GeoCoder gives you and return the continent corresponding to the closest matching country name (which would be the key in your String mapping). (You would also have to treat the special case of US addresses which, annoyingly, end just with the state code)