How to use AddressComponents from the new Places API? - android

I've been using the new Places API for Android. I want to know how to get City, Country etc details from AddressComponents.
This is how I'm using it:
private void initializePlacesAPI()
{
if(!Places.isInitialized())
{
Places.initialize(context.getApplicationContext(), Constants.GOOGLE_API_KEY);
}
}
private void launchPlacesAPI(int requestCode)
{
// Set the fields to specify which types of place data to return after the user has made a selection.
List<Place.Field> fields = Arrays.asList(Place.Field.NAME, Place.Field.LAT_LNG, Place.Field.ADDRESS, Place.Field.ADDRESS_COMPONENTS);
// Start the autocomplete intent.
Intent intent = new Autocomplete.IntentBuilder(
AutocompleteActivityMode.OVERLAY, fields)
.setCountry(Constants.COUNTRY_CODE_CANADA)
.setHint(context.getString(R.string.start_typing_an_address))
.build(context);
startActivityForResult(intent, requestCode);
}
When a Place object is received in onActivityResult, how do I use the AddressComponents object received there? It has no getters/setters.

The JSON response should look something like this
"address_components" : [
{
"long_name" : "5",
"short_name" : "5",
"types" : [ "floor" ]
},
{
"long_name" : "48",
"short_name" : "48",
"types" : [ "street_number" ]
},
{
"long_name" : "Pirrama Road",
"short_name" : "Pirrama Rd",
"types" : [ "route" ]
}
SO you can acess information like this
String floor = place.addressComponent[0].long_name
You can find more informations here https://developers.google.com/places/web-service/details

Related

Google Places: Android API: Place class missing some data

I find that Place class from Android Library for Google Places API misses a lot of data which is available in Web-Service API.
Android class:
https://developers.google.com/android/reference/com/google/android/gms/location/places/Place
Web-Service reply:
https://developers.google.com/places/web-service/details?hl=en
For example, class definition has nothing about Reviews or Opening Hours. Why it is so? Is it possible to fix it without converting all the app to Web-Service API calls and json-parsing? Perhaps there is an ability to convert Place object to its raw JSON-form to find some additional data?
Places api in android only returns a few details like place name, latitude, longitude etc. if you want more details you have to call webservice api . This is the URl
https://maps.googleapis.com/maps/api/place/details/json?key={API_KEY}&placeid={PLACE_ID}
Here PLACE_ID will get from Place Object in Android Places Api
Sample output:
{
"html_attributions" : [],
"result" : {
"address_components" : [
{
"long_name" : "7167",
"short_name" : "7167",
"types" : [ "street_number" ]
},
{
"long_name" : "Sunset Boulevard",
"short_name" : "Sunset Blvd",
"types" : [ "route" ]
},
{
"long_name" : "Central LA",
"short_name" : "Central LA",
"types" : [ "neighborhood", "political" ]
},
{
"long_name" : "Los Angeles",
"short_name" : "Los Angeles",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Los Angeles County",
"short_name" : "Los Angeles County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "California",
"short_name" : "CA",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
},
{
"long_name" : "90046",
"short_name" : "90046",
"types" : [ "postal_code" ]
}
],
"adr_address" : "\u003cspan class=\"street-address\"\u003e7167 Sunset Blvd\u003c/span\u003e, \u003cspan class=\"locality\"\u003eLos Angeles\u003c/span\u003e, \u003cspan class=\"region\"\u003eCA\u003c/span\u003e \u003cspan class=\"postal-code\"\u003e90046\u003c/span\u003e, \u003cspan class=\"country-name\"\u003eUSA\u003c/span\u003e",
"formatted_address" : "7167 Sunset Blvd, Los Angeles, CA 90046, USA",
"geometry" : {
"location" : {
"lat" : 34.098341,
"lng" : -118.346263
},
"viewport" : {
"northeast" : {
"lat" : 34.0995122302915,
"lng" : -118.3449154697085
},
"southwest" : {
"lat" : 34.0968142697085,
"lng" : -118.3476134302915
}
}
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id" : "7143e0743707f66cfa1cda945779f18e8350060e",
"name" : "7167 Sunset Blvd",
"place_id" : "ChIJn_0bqti-woARRtpNvG7kuq4",
"reference" : "CmRbAAAAuU6CDhPuLqrS9F4XCZIV61wveIeU44RMua7FSCZHtwJeC58_OJksQvLI9Nudb9-N8RhfJDUECkxvdB-llxe6WIqrkDQMBs2vz3mBky0DH70jIcFS7f0_7yivdsxmmLzaEhAtwgzDs0va2soGuFyzuNTGGhR-xVrIvyeZwY0OGDmEp3FJmrbbeQ",
"scope" : "GOOGLE",
"types" : [ "street_address" ],
"url" : "https://maps.google.com/?q=7167+Sunset+Blvd,+Los+Angeles,+CA+90046,+USA&ftid=0x80c2bed8aa1bfd9f:0xaebae46ebc4dda46",
"utc_offset" : -420,
"vicinity" : "Los Angeles"
},
"status" : "OK"
}
Sample JSON Parsing in android
String postalCode="";
String city="";
String state="";
String address="";
JSONObject jsonObj=new JSONObject(rs);
JSONArray addressComponents = jsonObj.getJSONObject("result").getJSONArray("address_components");
for(int i = 0; i < addressComponents.length(); i++) {
JSONArray typesArray = addressComponents.getJSONObject(i).getJSONArray("types");
for (int j = 0; j < typesArray.length(); j++) {
if (typesArray.get(j).toString().equalsIgnoreCase("postal_code")) {
postalCode = addressComponents.getJSONObject(i).getString("long_name");
}else if (typesArray.get(j).toString().equalsIgnoreCase("locality")) {
city = addressComponents.getJSONObject(i).getString("long_name");
}else if (typesArray.get(j).toString().equalsIgnoreCase("administrative_area_level_1")) {
state = addressComponents.getJSONObject(i).getString("long_name");
}else {
String types=typesArray.get(j).toString();
if(types.equalsIgnoreCase("street_number")
||types.equalsIgnoreCase("route")
||types.equalsIgnoreCase("neighborhood")
||types.equalsIgnoreCase("sublocality_level_1")
)
address+=addressComponents.getJSONObject(i).getString("long_name")+", ";
}
}
}

How to get String PlaceTypes from Integer value?

I am new to learning Google Places API and have been searching for an answer to this problem without much luck.
So in the first part of my app, I wish to retrieve the placeTypes of my current location. I have successfully done that, but it returns a list of Integer values, which then correlate to different Place.TYPE_*s.
My overall goal, though, is to get the current placeTypes of my location, then do a PlaceSearch via URL. To do so, I need to convert the Integers in my list of the location, to the string types so I can insert them into my URL.
Note: I have tried inserting the integer value for "restaurant" instead of just the word "restaurant" in the URL, but it returned wrong results such as hotels, office buildings that were not returned when I used the word instead.
For example, my URL would look like:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=" + lat + "," + lng+"&radius=2000&type=restaurant&key=my_key
Notice the word "restaurant" in the URL. That is where I have replaced it with the Integer value and it did not return correct results.
[EDITED]
You can try this.
private String getPlaceTypeForValue(int value) throws Exception {
Field[] fields = Place.class.getDeclaredFields();
String name;
for (Field field : fields) {
name = field.getName().toLowerCase();
if (name.startsWith("type_") && field.getInt(null) == value) {
return name.replace("type_", "");
}
}
throw new IllegalArgumentException("place value " + value + " not found.");
}
I created a test to validate it, should work, just missing some types: administrative_area_level_4, administrative_area_level_5, postal_code_suffix and street_number.
public class ConvertingPlaceTypesUnitTest {
private enum Types {
accounting,
airport,
amusement_park,
aquarium,
art_gallery,
atm,
bakery,
bank,
bar,
beauty_salon,
bicycle_store,
book_store,
bowling_alley,
bus_station,
cafe,
campground,
car_dealer,
car_rental,
car_repair,
car_wash,
casino,
cemetery,
church,
city_hall,
clothing_store,
convenience_store,
courthouse,
dentist,
department_store,
doctor,
electrician,
electronics_store,
embassy,
establishment,
finance,
fire_station,
florist,
food,
funeral_home,
furniture_store,
gas_station,
general_contractor,
grocery_or_supermarket,
gym,
hair_care,
hardware_store,
health,
hindu_temple,
home_goods_store,
hospital,
insurance_agency,
jewelry_store,
laundry,
lawyer,
library,
liquor_store,
local_government_office,
locksmith,
lodging,
meal_delivery,
meal_takeaway,
mosque,
movie_rental,
movie_theater,
moving_company,
museum,
night_club,
painter,
park,
parking,
pet_store,
pharmacy,
physiotherapist,
place_of_worship,
plumber,
police,
post_office,
real_estate_agency,
restaurant,
roofing_contractor,
rv_park,
school,
shoe_store,
shopping_mall,
spa,
stadium,
storage,
store,
subway_station,
synagogue,
taxi_stand,
train_station,
travel_agency,
university,
veterinary_care,
zoo,
administrative_area_level_3,
// administrative_area_level_4, Not in Place.class
// administrative_area_level_5, Not in Place.class
colloquial_area,
floor,
geocode,
intersection,
natural_feature,
neighborhood,
political,
point_of_interest,
post_box,
postal_code_prefix,
// postal_code_suffix, Not in Place.class
postal_town,
premise,
room,
route,
street_address,
// street_number, Not in Place.class
sublocality_level_4,
sublocality_level_5,
sublocality_level_3,
sublocality_level_2,
sublocality_level_1,
subpremise,
transit_station,
locality,
sublocality,
postal_code,
country,
administrative_area_level_1,
administrative_area_level_2
};
#Test
public void extracPlaces() throws Exception {
assertEquals("accounting", getPlaceTypeForValue(Place.TYPE_ACCOUNTING));
assertEquals("local_government_office", getPlaceTypeForValue(Place.TYPE_LOCAL_GOVERNMENT_OFFICE));
}
#Test
public void testAllTypes() throws Exception {
for (Types type : Types.values()) {
final String name = type.toString();
int value = getPlaceTypeValue("TYPE_" + name.toUpperCase());
assertEquals(name, getPlaceTypeForValue(value));
}
}
private int getPlaceTypeValue(String fieldName) throws Exception {
Field field = Place.class.getDeclaredField(fieldName);
return field.getInt(null);
}
private String getPlaceTypeForValue(int value) throws IllegalAccessException {
Field[] fields = Place.class.getDeclaredFields();
String name;
for (Field field : fields) {
name = field.getName().toLowerCase();
if (name.startsWith("type_") && field.getInt(null) == value) {
return name.replace("type_", "");
}
}
throw new IllegalArgumentException("place value " + value + " not found.");
}
}
[OLD]
I didn't understand where type integer is coming from, in documentation it's always referred as string.
type — Restricts the results to places matching the specified type. Only one type may be specified (if more than one type is provided, all types following the first entry are ignored). See the list of supported types.
{
"html_attributions" : [],
"result" : {
"address_components" : [
{
"long_name" : "48",
"short_name" : "48",
"types" : [ "street_number" ]
},
{
"long_name" : "Pirrama Road",
"short_name" : "Pirrama Road",
"types" : [ "route" ]
},
{
"long_name" : "Pyrmont",
"short_name" : "Pyrmont",
"types" : [ "locality", "political" ]
},
{
"long_name" : "NSW",
"short_name" : "NSW",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "AU",
"short_name" : "AU",
"types" : [ "country", "political" ]
},
{
"long_name" : "2009",
"short_name" : "2009",
"types" : [ "postal_code" ]
}
],
"adr_address" : "5,
\u003cspan class=\"street-address\"\u003e48 Pirrama Rd\u003c/span\u003e,
\u003cspan class=\"locality\"\u003ePyrmont\u003c/span\u003e
\u003cspan class=\"region\"\u003eNSW\u003c/span\u003e
\u003cspan class=\"postal-code\"\u003e2009\u003c/span\u003e,
\u003cspan class=\"country-name\"\u003eAustralia\u003c/span\u003e",
"formatted_address" : "48 Pirrama Road, Pyrmont NSW, Australia",
"formatted_phone_number" : "(02) 9374 4000",
"geometry" : {
"location" : {
"lat" : -33.8669710,
"lng" : 151.1958750
},
"viewport" : {
"northeast" : {
"lat" : -33.8665053,
"lng" : 151.1960371
},
"southwest" : {
"lat" : -33.8669293,
"lng" : 151.1952183
}
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/generic_business-71.png",
"id" : "4f89212bf76dde31f092cfc14d7506555d85b5c7",
"international_phone_number" : "+61 2 9374 4000",
"name" : "Google Sydney",
"place_id" : "ChIJN1t_tDeuEmsRUsoyG83frY4",
"scope" : "GOOGLE",
"alt_ids" : [
{
"place_id" : "D9iJyWEHuEmuEmsRm9hTkapTCrk",
"scope" : "APP"
}
],
"rating" : 4.70,
"reference" : "CnRsAAAA98C4wD-VFvzGq-KHVEFhlHuy1TD1W6UYZw7KjuvfVsKMRZkbCVBVDxXFOOCM108n9PuJMJxeAxix3WB6B16c1p2bY1ZQyOrcu1d9247xQhUmPgYjN37JMo5QBsWipTsnoIZA9yAzA-0pnxFM6yAcDhIQbU0z05f3xD3m9NQnhEDjvBoUw-BdcocVpXzKFcnMXUpf-nkyF1w",
"reviews" : [
{
"aspects" : [
{
"rating" : 3,
"type" : "quality"
}
],
"author_name" : "Simon Bengtsson",
"author_url" : "https://plus.google.com/104675092887960962573",
"language" : "en",
"rating" : 5,
"text" : "Just went inside to have a look at Google. Amazing.",
"time" : 1338440552869
},
{
"aspects" : [
{
"rating" : 3,
"type" : "quality"
}
],
"author_name" : "Felix Rauch Valenti",
"author_url" : "https://plus.google.com/103291556674373289857",
"language" : "en",
"rating" : 5,
"text" : "Best place to work :-)",
"time" : 1338411244325
},
{
"aspects" : [
{
"rating" : 3,
"type" : "quality"
}
],
"author_name" : "Chris",
"language" : "en",
"rating" : 5,
"text" : "Great place to work, always lots of free food!",
"time" : 1330467089039
}
],
"types" : [ "establishment" ],
"url" : "http://maps.google.com/maps/place?cid=10281119596374313554",
"vicinity" : "48 Pirrama Road, Pyrmont",
"website" : "http://www.google.com.au/"
},
"status" : "OK"
}

Google Places API: Are "place_id" or "id" unique to any city in the world?

When doing a autocomplete API call for a location, I request a JSON response from google.
What is the difference between the "id" and "place_id" string?
Are these two id's unique to any city in the world?
Does google places assign every city in the world an id?
For example, does Somers, NY, USA have the same id as Somers, New York, United States?
Is there an easy way to get an id for a city? (from a google maps url or something?)
Here is the JSON response from a autocomplete api call of Somers NY USA:
{
"html_attributions" : [],
"result" : {
"address_components" : [
{
"long_name" : "Somers",
"short_name" : "Somers",
"types" : [ "administrative_area_level_3", "political" ]
},
{
"long_name" : "Westchester County",
"short_name" : "Westchester County",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "New York",
"short_name" : "NY",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "United States",
"short_name" : "US",
"types" : [ "country", "political" ]
}
],
"adr_address" : "\u003cspan class=\"locality\"\u003eSomers\u003c/span\u003e, \u003cspan class=\"region\"\u003eNY\u003c/span\u003e, \u003cspan class=\"country-name\"\u003eUSA\u003c/span\u003e",
"formatted_address" : "Somers, NY, USA",
"geometry" : {
"location" : {
"lat" : 41.29963050000001,
"lng" : -73.7360175
},
"viewport" : {
"northeast" : {
"lat" : 41.3550988,
"lng" : -73.65881709999999
},
"southwest" : {
"lat" : 41.2379047,
"lng" : -73.78000709999999
}
}
},
"icon" : "http://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
"id" : "8e846f7cdf419380d138e6d605137e739075b777",
"name" : "Somers",
"place_id" : "ChIJ6wv7yGixwokRIwjh6OWI4I0",
"reference" : "CoQBcgAAAKxvwwjlyK3ZaVA5DAM52DU8tMMplyvamYxXVJuMyDplQ3SUs-9ONvZgIN4sDW_sUz9z7wdoBCmPcgWHY9Oi_l0hImvMtiE8s6TKaUCDju2vzlcSEGXtDW0bvixVbbuF35AP2stRw80YjcrnwuMDglKEHKUVdH8vzSVG91WNOcOcEhBda300E-VstT6ZQ1zCx30eGhQBUGcFLuUeB484h1AzDw75Aw5wxA",
"scope" : "GOOGLE",
"types" : [ "administrative_area_level_3", "political" ],
"url" : "https://maps.google.com/maps/place?q=Somers,+NY,+USA&ftid=0x89c2b168c8fb0beb:0x8de088e5e8e10823"
},
"status" : "OK"
}
"id" and "reference" have been deprecated and will be removed from the results in mid-2015. They were not "unique" in the sense that you could look up somewhere from that info.
Placeid is different - it is both unique to the location and the location generally only has one Placeid. (This is true in most cases. However a "place" can have additional IDs that refer to different scopes (Google scope vs user scope) or if a business has moved to a different place giving it a new place_id. However in all cases, place_id is still persistent.) Furthermore you use the Placeid to access the Details API.
See the deprecation notice here: https://developers.google.com/places/documentation/search
Note: The id and reference fields are deprecated as of June 24, 2014.
They are replaced by the new place ID, a unique identifier that can be
used to compare places and to retrieve information about a place. The
Places API currently returns a place_id in all responses, and accepts
a placeid in the Place Details and Place Delete requests. Soon after
June 24, 2015, the API will stop returning the id and reference fields
in responses. Some time later, the API will no longer accept the
reference in requests. We recommend that you update your code to use
the new place ID instead of id and reference as soon as possible.

Json parsing using gson to get the location

Please help me to write the POJO class for this Json result. I tried a lot but it doesn't work for me.This is the result return form google maps api
{
"results" : [
{
"address_components" : [
{
"long_name" : "Salem - Kochi - Kanyakumari Highway",
"short_name" : "National Highway 47",
"types" : [ "route" ]
},
{
"long_name" : "Thampanoor",
"short_name" : "Thampanoor",
"types" : [ "sublocality_level_1", "sublocality", "political" ]
},
{
"long_name" : "Thiruvananthapuram",
"short_name" : "TVM",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Thiruvananthapuram",
"short_name" : "TVM",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Kerala",
"short_name" : "KL",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
},
{
"long_name" : "695014",
"short_name" : "695014",
"types" : [ "postal_code" ]
}
],
"formatted_address" : "Salem - Kochi - Kanyakumari Highway, Thampanoor, Thiruvananthapuram, Kerala 695014, India",
Thanks in advance
You can use certain tools/website to generate POJO from JSON, one of such website is: http://www.jsonschema2pojo.org/. On this website, you just need to paste your JSON response and it will generate required POJO classes. It does also support annotation styles like GSON and Jackson.
Be a lazy but a productive developer!
When in doubt on how to create a POJO from a JSON, I'd recommend you to try this site: http://www.jsonschema2pojo.org/
It outputs you a full java class that works for a given json type;
For most cases I'd recommend you to use this config (from the website above): Source type: Json Annotation style: None And check ONLY use primitives.
Hope it helps !
I would do it like this:
public class Poi {
#SerializedName("long_name")
private String longName;
#SerializedName("short_name")
private String shortName;
#SerializedName("types")
private String[] types;
}
Then do it like this
Gson gson = new Gson();
List<Poi> pois = new ArrayList<Poi>();
JSONObject result = new JSONObject(response);
JSONArray array = result.getJSONArray("results");
for(int i = 0; i < array.length(); i ++) {
pois.add(gson.fromJson(array.get(i).toString(), Poi.class);
}

Retrieve info from json on after google search details

I am working on an android app that makes a request to google places (details) and gets a json object in return. Here is the object https://developers.google.com/places/documentation/details#PlaceDetailsResponses
`{
"html_attributions" : [],
"result" : {
"address_components" : [
{
"long_name" : "48",
"short_name" : "48",
"types" : [ "street_number" ]
},
{
"long_name" : "Pirrama Road",
"short_name" : "Pirrama Road",
"types" : [ "route" ]
},
{
"long_name" : "Pyrmont",
"short_name" : "Pyrmont",
"types" : [ "locality", "political" ]
},
{
"long_name" : "NSW",
"short_name" : "NSW",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "AU",
"short_name" : "AU",
"types" : [ "country", "political" ]
},
{
"long_name" : "2009",
"short_name" : "2009",
"types" : [ "postal_code" ]
}
],
"events" : [
{
"event_id" : "9lJ_jK1GfhX",
"start_time" : 1293865200,
"summary" : "<p>A visit from author John Doe, who will read from his latest book.</p>
<p>A limited number of signed copies will be available.</p>",
"url" : "http://www.example.com/john_doe_visit.html"
}
], ETC`
How can I get a specific detail from that json. If I try json.getJSONArray("result") it is telling me json is not from that type or if I try json.getString("results") it says no value for results. So how could I extract the information for example for short_name, etc?
Thanks in advance
You should try like
json.getJSONObject("result");
How to get short_name
JSONObject json=new JSONObject("json");
JSONObject result=json.getJSONObject("result");
JSONArray array=result.getJSONArray("address_components");
for(int i=0;i<array.length();i++)
{
JSONObject obj = array.getJSONObject(i);
String short_name=obj.getString("short_name");
System.out.println("Short Name:"+short_name);
}

Categories

Resources