Giners / mui-places-autocomplete

Google Material Design (Material-UI) styled React component using Google Maps Places Autocomplete
MIT License
34 stars 26 forks source link

How to get address and city ? #44

Open atifaziz2 opened 5 years ago

atifaziz2 commented 5 years ago

Hi! I am using mui-places-autocomplete, in a suggestion how i get address , postcode, city and country?

Giners commented 5 years ago

Hi @atifaziz2,

The suggestion that is returned to you in the onSuggestionSelected function is the same info that is returned to you by the Google getPlacePredictions() API. Check out the documentation and let me know if you can figure out the information you are looking for. If not let me know and we will see if we can find it together.

atifaziz2 commented 5 years ago

Hi @Giners , I am getting this response on onSuggestionSelected function

{description: "Istanbul, Turkey", id: "f8837dbe3fd95c9dcd9519b75e8a39159c205c3d", matched_substrings: Array(1), place_id: "ChIJawhoAASnyhQR0LABvJj-zOE", reference: "ChIJawhoAASnyhQR0LABvJj-zOE", …}description: "Istanbul, Turkey"id: "f8837dbe3fd95c9dcd9519b75e8a39159c205c3d"matched_substrings: [{…}]place_id: "ChIJawhoAASnyhQR0LABvJj-zOE"reference: "ChIJawhoAASnyhQR0LABvJj-zOE"structured_formatting: {main_text: "Istanbul", main_text_matched_substrings: Array(1), secondary_text: "Turkey"}terms: (2) [{…}, {…}]types: (3) ["locality", "political", "geocode"]:

can you please guide me how to get city and country from this response?

Giners commented 5 years ago

Hey @atifaziz2,

The responses returned are simply suggestions of places that a person might be searching for. The suggestion is contained in the description key of the response that is returned. As a result address, city, country code, etc., details aren't contained in it.

What you need to do to get address, city, country code, etc., details from a suggestion is to take its place ID (contained in the place_id key of the suggestion response) and make a call to the Google Geocoder service. Given a place ID it can look up as much details as a given suggestion has.

Check out these docs:

Note that in the example it simply looks for the geometry property off of the results returned by the geocodeByPlaceID() function. In addition to the geometry property there ought to be a property called address_components. This will contain the details such as address, city, country code, etc.

There is a demo file called DemoGeocodeLatLong.jsx that makes uses of a utility function called geocodeBySuggestion(). This will make calls out to the Geocoder service for you. Here is an example of how to use it for guidance: https://github.com/Giners/mui-places-autocomplete/blob/2f0137fe4f246cd5f590d6c05e4b1c430ee0dc50/demo/DemoGeocodeLatLong.jsx

richardwardza commented 4 years ago

This is a bit late but could be of use for anyone reading this:

I used the following to get the various address details (this is the "core" code I used):

  import MUIPlacesAutocomplete, { geocodeByPlaceID } from 'mui-places-autocomplete';

  function parseAddress(components: AddressComponent[]): Address {
    const result = {
        line1: ["", "", ""], // Make line1 an arry so we an arr.join(' ').trim() and not have to worry about fields being there or not
        suburb: "",
        city: "",
        county: "",
        country: "",
        postcode: "",
    };

    components.forEach((component) => {
        component.types.forEach((type) => {
            if (type === 'subpremise') {
                result.line1[0] = component.long_name;
            }
            if (type === 'street_number') {
                result.line1[1] = component.long_name;
            }
            if (type === 'route') {
                result.line1[2] = component.long_name;
            }
            if (['neighborhood', 'sublocality', 'sublocality_level_2'].includes(type)) {
                result.suburb = component.long_name;
            }
            if (['locality', 'postal_town', 'administrative_area_level_1'].includes(type)) {
                result.city = component.long_name;
            }
            if (type === 'administrative_area_level_2') {
                result.county = component.long_name;
            }
            if (type === 'country') {
                result.country = component.long_name;
            }

            if (['postal_code', 'postal_code_prefix'].includes(type)) {
                result.postcode = component.long_name;
            }
        });
    });

    return {
        line1: result.line1.join(' ').trim(),
        suburb: result.suburb,
        city: result.city,
        county: result.county,
        country: result.country,
        postcode: result.postcode,
    };
}

  const onSuggestionSelected = (suggestion: AddressSuggestion) => {
        geocodeByPlaceID(suggestion.place_id).then((results: GeoResults[]) => {
            const { geometry } = results[0];

            const coordinates = {
                lat: geometry.location.lat(),
                lng: geometry.location.lng(),
            };
            const parsedAddress = parseAddress(results[0].address_components);
            const selectedAddress = {
                placeId: suggestion.place_id,
                description: suggestion.description,
                address: parsedAddress,
                coordinates
            };
            console.log(selectedAddress);
 // From here, do what you want with `selectedAddress` - it has the address and lat lng.
//probably you want to set it as values on your input form:
//eg Formik: 
//        setFieldValue("address.line1", address.address.line1);
//        setFieldValue("address.line2", "");
//        setFieldValue("address.suburb", address.address.suburb);
//        setFieldValue("address.city", address.address.city);
//        setFieldValue("address.county", address.address.county);
//        setFieldValue("address.country", address.address.country);
//        setFieldValue("address.postcode", address.address.postcode);
//        setFieldValue("address.latitude", address.coordinates.lat);
//        setFieldValue("address.longitude", address.coordinates.lng);
        }).catch((err: any) => {
            console.log("Error retrieving location: ", err);
        });
    };

    return (
        <MUIPlacesAutocomplete
            onSuggestionSelected={onSuggestionSelected}
            renderTarget={() => (
                <div />
            )}
        />

    );

onSuggestionSelected calls geocodeByPlaceID which returns what is needed, the results[0].address_components. The parseAddress function is based off (as Giners mentioned) the info from https://developers.google.com/maps/documentation/javascript/reference/geocoder#GeocoderAddressComponent ( long_name, short_name, type) with the types being defined here: https://developers.google.com/maps/documentation/javascript/geocoding#GeocodingAddressTypes

Please modify the parseAddress function as works for you - I found this worked for the country I was looking. Some countries use sublocality_level_1, others have the equivalent data in administrative_area_level_2 - run some test, console.log out the results[0].address_components and tweak accordingly.