Rev 10124 | AutorÃa | Comparar con el anterior | Ultima modificación | Ver Log |
import React, { useEffect, useRef } from "react";
import { useState } from "react";
let autoComplete;
const loadScript = (url, callback) => {
let script = document.createElement("script");
script.type = "text/javascript";
if (script.readyState) {
script.onreadystatechange = function () {
if (script.readyState === "loaded" || script.readyState === "complete") {
script.onreadystatechange = null;
callback();
}
};
} else {
script.onload = () => callback();
}
script.src = url;
document.getElementsByTagName("head")[0].appendChild(script);
};
function SearchLocationInput({ googleApiKey, setValue, value, updateData }) {
const autoCompleteRef = useRef(null);
const [data, setData] = useState({})
function handleScriptLoad(updateQuery, autoCompleteRef) {
autoComplete = new window.google.maps.places.Autocomplete(
autoCompleteRef.current,
{ types: ["(cities)"] }
);
autoComplete.addListener("place_changed", () =>
handlePlaceSelect(updateQuery)
);
}
async function handlePlaceSelect(updateQuery) {
const place = await autoComplete.getPlace()
let obj = {
formatted_address: '',
address1: '',
address2: '',
country: '',
state: '',
city1: '',
city2: '',
postal_code: '',
latitude: 0,
longitude: 0,
location_search: ''
}
obj.formatted_address = place.formatted_address
obj.latitude = place.geometry?.location.lat()
obj.longitude = place.geometry?.location.lng()
await place.address_components?.map((address_component) => {
if (address_component.types[0] == "route") {
obj.address1 = address_component.long_name
}
if (address_component.types[0] == "sublocality") {
obj.address2 = address_component.long_name
}
if (address_component.types[0] == "locality") {
obj.city1 = address_component.long_name
}
if (address_component.types[0] == "administrative_area_level_2") {
obj.city2 = address_component.long_name
}
if (address_component.types[0] == "administrative_area_level_1") {
obj.state = address_component.long_name
}
if (address_component.types[0] == "country") {
obj.country = address_component.long_name
}
if (address_component.types[0] == "postal_code") {
obj.postal_code = address_component.long_name
}
})
updateQuery(place.formatted_address)
setData(obj)
}
useEffect(() => {
loadScript(
`https://maps.googleapis.com/maps/api/js?key=${googleApiKey}&libraries=places`,
() => handleScriptLoad(setValue, autoCompleteRef)
);
}, []);
useEffect(() => {
updateData(data)
}, [data]);
return (
<div className="form-group">
<input
ref={autoCompleteRef}
onChange={event => setValue(event.target.value)}
placeholder="Enter a City"
value={value}
className="form-control"
/>
</div>
);
}
export default SearchLocationInput;