Comments (4)
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.
from mui-places-autocomplete.
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.
from mui-places-autocomplete.
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?
from mui-places-autocomplete.
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:
- General geocode functionality built into
<MUIPlacesAutocomplet>
: https://github.com/Giners/mui-places-autocomplete#geocoding-utility-functions-latitudelongitude - Specific example of using the Geocoder service: https://github.com/Giners/mui-places-autocomplete#geocodebyplaceid
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
from mui-places-autocomplete.
Related Issues (20)
- Set 'z-index' to render suggestions over descendant elements/components of <MPA> HOT 7
- Provide fine grained control over the appearance of <MUIPlacesAutocomplete>
- Update dependencies
- Google logo doesn't render HOT 2
- Latitude / Longitude data in returned object? HOT 8
- Manipulate suggestion rendering? HOT 1
- Fix issues arising with material-ui v1 HOT 1
- Material UI V1 is out - breaking changes HOT 6
- How to style the suggestion popup HOT 12
- how to know when the text field is cleant
- How to get the address components of a selected suggestion HOT 1
- how to remove input underline HOT 5
- Publish new version w/ updated prop-types to remove fbjs dependency?
- Make background of suggestions non-transparent HOT 1
- cant get demo code running
- How to limit the results only to cities?
- Missing postcode when searching with anything other than postcode
- Can't resolve 'fbjs/lib/emptyFunction' HOT 1
- @material-ui/core@"^1.0.0" HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mui-places-autocomplete.