How to get country, city from place picker's address?

浪尽此生 提交于 2019-12-01 15:10:03

问题


I am using a place picker's intent to get the place. Now I want to save address in separated form as country,city,pincode,state. How can I get all this from the place picker's address?

Code:

public class NameOfBusinessFragment extends Fragment {

    int PLACE_PICKER_REQUEST = 1;
    int RESULT_OK = -1;
    PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
    EditText category,location;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_name_of_business,
                    container, false);

            location = (EditText)view.findViewById(R.id.location);

            location.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    try {

                        startActivityForResult(builder.build(getActivity()), PLACE_PICKER_REQUEST);
                    }
                    catch (GooglePlayServicesRepairableException e)
                    {
                        Toast.makeText(getActivity(),"ServiceRepaire Exception",Toast.LENGTH_SHORT).show();
                    }
                    catch (GooglePlayServicesNotAvailableException  e)
                    {
                        Toast.makeText(getActivity(),"SeerviceNotAvailable Exception",Toast.LENGTH_SHORT).show();
                    }
                }
            });

            return view;
        }
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PLACE_PICKER_REQUEST) {
            if (resultCode == RESULT_OK) {
                Place place = PlacePicker.getPlace(data, getActivity());
                String toastMsg = String.format("Place: %s", place.getName());


                Toast.makeText(getActivity(), toastMsg, Toast.LENGTH_LONG).show();
                location.setText(place.getName());
            }
        }
    }
}

This is how I implemented place picker and getting the place name onActivityResult. Can I get this using reverse geocode or something? Can anyone help me out with this please? Thank you.


回答1:


I think it's not possible using Place class directly, but you can ask it to google starting from latitude and longitude. Below an example of your onActivityResult method:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == RESULT_OK) {
            // get place data
            Place place = PlacePicker.getPlace(data, getActivity());

            // ask for geolocation data
            Geocoder gcd = new Geocoder(this, Locale.getDefault());
            List<Address> addresses = null;
            try {
                addresses = gcd.getFromLocation(place.getLatLng().latitude, place.getLatLng().longitude, 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (addresses.size() > 0) {
                String toastMsg = String.format("Place: %s", addresses.get(0).getLocality() + " - " + addresses.get(0).getCountryName() + " - " + addresses.get(0).getCountryCode());
                Toast.makeText(getActivity(), toastMsg, Toast.LENGTH_LONG).show();


                // NOW SET HERE CORRECT DATA
                //location.setText(place.getName());

            }
        }
    }
}



回答2:


Best way to solve your problem is using Geocoder to get address from latitude and longitude but if by any reason if you don't want to use it following workaround may help you.

Though it is not 100% reliable you can use it till Google provides those detailed information. It may not give perfect result for some random cases but works for most.

 public void getAddressDetails(Place place) {
        if (place.getAddress() != null) {
            String[] addressSlice = place.getAddress().toString().split(", ");
            country = addressSlice[addressSlice.length - 1];
            if (addressSlice.length > 1) {
                String[] stateAndPostalCode = addressSlice[addressSlice.length - 2].split(" ");
                if (stateAndPostalCode.length > 1) {
                    postalCode = stateAndPostalCode[stateAndPostalCode.length - 1];
                    state = "";
                    for (int i = 0; i < stateAndPostalCode.length - 1; i++) {
                        state += (i == 0 ? "" : " ") + stateAndPostalCode[i];
                    }
                } else {
                    state = stateAndPostalCode[stateAndPostalCode.length - 1];
                }
            }
            if (addressSlice.length > 2)
                city = addressSlice[addressSlice.length - 3];
            if (addressSlice.length == 4)
                stAddress1 = addressSlice[0];
            else if (addressSlice.length > 3) {
                stAddress2 = addressSlice[addressSlice.length - 4];
                stAddress1 = "";
                for (int i = 0; i < addressSlice.length - 4; i++) {
                    stAddress1 += (i == 0 ? "" : ", ") + addressSlice[i];
                }
            }
        }
        if(place.getLatLng()!=null)
        {
            latitude = "" + place.getLatLng().latitude;
            longitude = "" + place.getLatLng().longitude;
        }
    }



回答3:


If you want the components of the Place object address (street, city, country, etc) separated, you have two options.

  1. Use Place.getLatLng(). Then, reverse geocode the latitude and longitude.
  2. Parse the address.

Now, parsing an address is not very easy. But, reverse geocoding the latitude and longitude is not precise. I suggest parsing the address. There are good address parsing services out there, and some even validate the address against address databases. (I suggest SmartyStreets. If you go to the SmartyStreets demo page, select "Freeform address" from the drop down, then see what kind of information comes back when you search for an address.)


Here is why reverse geocoding may be a poor solution. When you reverse geocode, you take a latitude and longitude and algorithmically match it to an address. Some algorithms match the latitude and longitude to the closest real address. In this case, the address might not be the address of your location. On the other hand, some algorithms approximate an address that would reasonably fit the latitude and longitude. In this case, the address may not be a real address. Another complication is mentioned in the documentation for getLatLng():

The location is not necessarily the center of the Place, or any particular entry or exit point, but some arbitrarily chosen point within the geographic extent of the Place.

Because the latitude and longitude are arbitrary points within the geographic extent of the place, it is hard to make trustworthy reverse-geocoding algorithms.

But, you may not care about exactness. If that is the case&emdash;that you want an address that is "close enough," reverse geocoding might be a good choice.


Another thing to note:

static Place getPlace(Intent intent, Context context) This method was deprecated. Use getPlace(Context, Intent) instead.

I think you should replace your line:

Place place = PlacePicker.getPlace(data, getActivity());

with this:

Place place = PlacePicker.getPlace(getActivity(), data);

Full disclosure: I work for SmartyStreets.



来源:https://stackoverflow.com/questions/37873415/how-to-get-country-city-from-place-pickers-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!