In our codebase, we use the GooglePlacesAutocomplete component to accept user-input for Facility locations, but also to display locations for Facilities that have already been saved to our database.
<GooglePlacesAutocomplete
apiKey={GOOGLE_MAPS_API_KEY}
viewValue={facility.city ? formatCity(facility.city) : ''}
types={['(cities)']}
fields={['geometry', 'formatted_address', 'address_components']}
on:placeChanged={e => handlePlaceChange(e, facility)}
on:clear={() => handlePlaceChange(null, facility)}
/>
<script>
export function formatCity(city: City, short = false): string {
if (!city?.name) {
return 'Unknown city';
}
const locationParts = [city.name];
if (city.state && city.state !== last(locationParts)) {
locationParts.push(city.state);
}
if (city.country.shortCode !== 'US') {
locationParts.push(short ? city.country.shortCode : city.country.name);
}
return locationParts.join(', ');
}
</script>
For existing Facilities in our implementation:
- We make use of the
viewValue prop to be able to show our saved location
- However,
currentPlace is not set upon initialization of the field
- Therefore, if you click into the input field, then click out, the
blur function calls clear because viewValue !== currentPlace?.[viewLabel]
For new Facilities in our implementation:
- If the location entered is in Canada and you click into the field then out,
blur does NOT call clear because our viewValue formats the location in the same way as currentPlace[viewLabel]
- If the location entered is in the US and you click into the field then out,
blur DOES call clear because our viewValue formatting drops "USA" off of the location, therefore viewValue !== currentPlace[viewLabel]
- If the location is anywhere else, it is hit or miss, depending on whether our
viewValue location matches the currentPlace[viewLabel] value
In our codebase, we use the
GooglePlacesAutocompletecomponent to accept user-input for Facility locations, but also to display locations for Facilities that have already been saved to our database.For existing Facilities in our implementation:
viewValueprop to be able to show our saved locationcurrentPlaceis not set upon initialization of the fieldblurfunction callsclearbecauseviewValue!==currentPlace?.[viewLabel]For new Facilities in our implementation:
blurdoes NOT callclearbecause ourviewValueformats the location in the same way ascurrentPlace[viewLabel]blurDOES callclearbecause ourviewValueformatting drops "USA" off of the location, thereforeviewValue !== currentPlace[viewLabel]viewValuelocation matches thecurrentPlace[viewLabel]value