首页 > 解决方案 > 如何使用新 Places API 中的 AddressComponents?

问题描述

我一直在使用适用于 Android 的新 Places API。我想知道如何从 AddressComponents 获取城市、国家等详细信息。

这就是我使用它的方式:

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);
    }

Place收到一个对象时onActivityResult,我如何使用AddressComponents那里收到的对象?它没有getter/setter。

标签: androidgoogle-places-api

解决方案


JSON响应应该是这样的

    "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" ]
     }

所以你可以访问这样的信息

    String floor = place.addressComponent[0].long_name

您可以在此处找到更多信息https://developers.google.com/places/web-service/details


推荐阅读