Create basic geolocation custom field
This commit is contained in:
parent
0d646c5d6b
commit
8473d0d4d6
55
src/customFields/GeoPicker/GeoPicker.tsx
Normal file
55
src/customFields/GeoPicker/GeoPicker.tsx
Normal file
@ -0,0 +1,55 @@
|
||||
import * as React from 'react';
|
||||
import { useField } from 'payload/components/forms';
|
||||
|
||||
export const GeoPicker: React.FC<{ path: string }> = ({ path }) => {
|
||||
const { value, setValue } = useField<string>({ path });
|
||||
const [latitude, setLatitude] = React.useState(null);
|
||||
const [longitude, setLongitude] = React.useState(null);
|
||||
|
||||
const handleKeyPress = async (e) => {
|
||||
if (e.key === 'Enter') {
|
||||
try {
|
||||
const response = await fetch(
|
||||
`https://nominatim.openstreetmap.org/search?format=json&q=${value}`
|
||||
);
|
||||
const data = await response.json();
|
||||
if (data && data.length > 0) {
|
||||
setLatitude(parseFloat(data[0].lat));
|
||||
setLongitude(parseFloat(data[0].lon));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error fetching geolocation:', error);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className='field-type text'>
|
||||
<label className='field-label'>
|
||||
City
|
||||
</label>
|
||||
<input
|
||||
type="text"
|
||||
className='field-name'
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
onKeyDown={handleKeyPress}
|
||||
placeholder="Enter city to get coordinates"
|
||||
/>
|
||||
</div>
|
||||
<div className="field-type point">
|
||||
<ul className='point__wrap'>
|
||||
<li>
|
||||
<label className='field-label'>Location - Longitude</label>
|
||||
<input id="field-longitude-location" type="number" name="location.longitude" value={longitude}></input>
|
||||
</li>
|
||||
<li>
|
||||
<label className='field-label'>Location - Latitude</label>
|
||||
<input id="field-latitude-latitude" type="number" name="location.latitude" value={latitude}></input>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
12
src/customFields/GeoPicker/field.ts
Normal file
12
src/customFields/GeoPicker/field.ts
Normal file
@ -0,0 +1,12 @@
|
||||
import { Field } from 'payload/types';
|
||||
import { GeoPicker} from './GeoPicker';
|
||||
|
||||
export const GeoPickerField: Field = {
|
||||
name: 'GeoPicker',
|
||||
type: 'point',
|
||||
admin: {
|
||||
components: {
|
||||
Field: GeoPicker,
|
||||
},
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user