lumbung-kios-cms/src/customFields/geoPicker/GeoPicker.tsx

69 lines
2.1 KiB
TypeScript
Raw Permalink Normal View History

2024-02-21 12:07:31 +00:00
import * as React from 'react';
2024-02-21 15:36:39 +00:00
import { useField } from 'payload/components/forms';
2024-02-21 12:07:31 +00:00
export const GeoPicker: React.FC<{ path: string }> = ({ path }) => {
const { value, setValue } = useField<string>({ path });
2024-02-26 10:40:27 +00:00
const [longitude, setLongitude] = React.useState(value[0] || 0);
const [latitude, setLatitude] = React.useState(value[1] || 0);
const [error, setError] = React.useState("")
2024-02-21 12:07:31 +00:00
2024-02-21 15:33:04 +00:00
const handleCityEnter = async (e) => {
2024-02-21 12:07:31 +00:00
if (e.key === 'Enter') {
try {
const response = await fetch(
2024-02-21 15:33:04 +00:00
`https://nominatim.openstreetmap.org/search?format=json&q=${e.target.value}`
2024-02-21 12:07:31 +00:00
);
const data = await response.json();
if (data && data.length > 0) {
2024-02-21 15:33:04 +00:00
const { lat, lon } = data[0];
setLatitude(lat);
setLongitude(lon);
setValue([lon, lat]);
2024-02-21 12:07:31 +00:00
}
2024-02-26 10:40:27 +00:00
} catch (err) {
setError(e)
console.error('Error fetching geolocation:', e);
2024-02-21 12:07:31 +00:00
}
}
};
2024-02-21 15:33:04 +00:00
const handleLatitudeChange = (e) => {
setLatitude(e.target.value);
};
const handleLongitudeChange = (e) => {
setLongitude(e.target.value);
};
2024-02-21 12:07:31 +00:00
return (
<div>
<div className='field-type text'>
<label className='field-label'>
City
</label>
<input
type="text"
className='field-name'
2024-02-21 15:33:04 +00:00
onKeyDown={handleCityEnter}
2024-02-21 12:07:31 +00:00
placeholder="Enter city to get coordinates"
/>
</div>
2024-02-26 10:40:27 +00:00
{error != "" &&
<p>{error}</p>
}
2024-02-21 12:07:31 +00:00
<div className="field-type point">
<ul className='point__wrap'>
<li>
<label className='field-label'>Location - Longitude</label>
2024-02-21 15:33:04 +00:00
<input id="field-longitude-location" type="number" name="location.longitude" value={longitude} onChange={handleLongitudeChange}></input>
2024-02-21 12:07:31 +00:00
</li>
<li>
<label className='field-label'>Location - Latitude</label>
2024-02-21 15:33:04 +00:00
<input id="field-latitude-latitude" type="number" name="location.latitude" value={latitude} onChange={handleLatitudeChange}></input>
2024-02-21 12:07:31 +00:00
</li>
</ul>
</div>
</div>
);
};