How to get String PlaceTypes from Integer value?

2019-06-13 04:30发布

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.

1条回答
淡お忘
2楼-- · 2019-06-13 05:05

[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"
}
查看更多
登录 后发表回答