Get city name and postal code from Google Place API on Android

后端 未结 6 1456
醉话见心
醉话见心 2021-01-01 16:21

I\'m using Google Place API for Android with autocomplete

Everything works fine, but when I get the result as shown here, I don\'t have the city and postal code info

6条回答
  •  有刺的猬
    2021-01-01 16:47

    private Geocoder geocoder;
    private final int REQUEST_PLACE_ADDRESS = 40;
    

    onCreate

    Places.initialize(context, getString(R.string.google_api_key));
    
    Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.FULLSCREEN, Arrays.asList(Place.Field.ADDRESS_COMPONENTS, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG)).build(context);
    startActivityForResult(intent, REQUEST_PLACE_ADDRESS);
    

    onActivityResult

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == REQUEST_PLACE_ADDRESS && resultCode == Activity.RESULT_OK) {
            Place place = Autocomplete.getPlaceFromIntent(data);
            Log.e("Data",Place_Data: Name: " + place.getName() + "\tLatLng: " + place.getLatLng() + "\tAddress: " + place.getAddress() + "\tAddress Component: " + place.getAddressComponents());
    
            try {
                List
    addresses; geocoder = new Geocoder(context, Locale.getDefault()); try { addresses = geocoder.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1); // Here 1 represent max location result to returned, by documents it recommended 1 to 5 String address1 = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex() String address2 = addresses.get(0).getAddressLine(1); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex() String city = addresses.get(0).getLocality(); String state = addresses.get(0).getAdminArea(); String country = addresses.get(0).getCountryName(); String postalCode = addresses.get(0).getPostalCode(); Log.e("Address1: ", "" + address1); Log.e("Address2: ", "" + address2); Log.e("AddressCity: ", "" + city); Log.e("AddressState: ", "" + state); Log.e("AddressCountry: ", "" + country); Log.e("AddressPostal: ", "" + postalCode); Log.e("AddressLatitude: ", "" + place.getLatLng().latitude); Log.e("AddressLongitude: ", "" + place.getLatLng().longitude); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); //setMarker(latLng); } } }

提交回复
热议问题