Compare commits

...

3 Commits

Author SHA1 Message Date
f152476d8f Set lon/lat on data fetch
All checks were successful
continuous-integration/drone/push Build is passing
2024-02-21 16:36:39 +01:00
26eb75646b Geopicker field saves correct values 2024-02-21 16:33:04 +01:00
8473d0d4d6 Create basic geolocation custom field 2024-02-21 13:07:31 +01:00
3 changed files with 77 additions and 5 deletions

View File

@ -1,4 +1,5 @@
import { CollectionConfig } from 'payload/types';
import { geoPickerField } from "../customFields/geoPicker/field";
const Makers: CollectionConfig = {
slug: 'makers',
@ -14,11 +15,7 @@ const Makers: CollectionConfig = {
type: 'text', // required
required: true,
},
{
name: 'location',
type: 'point',
label: 'Location',
},
geoPickerField,
{
name: 'products', // required
type: 'relationship', // required

View File

@ -0,0 +1,63 @@
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 [longitude, setLongitude] = React.useState(value[0]);
const [latitude, setLatitude] = React.useState(value[1]);
const handleCityEnter = async (e) => {
if (e.key === 'Enter') {
try {
const response = await fetch(
`https://nominatim.openstreetmap.org/search?format=json&q=${e.target.value}`
);
const data = await response.json();
if (data && data.length > 0) {
const { lat, lon } = data[0];
setLatitude(lat);
setLongitude(lon);
setValue([lon, lat]);
}
} catch (error) {
console.error('Error fetching geolocation:', error);
}
}
};
const handleLatitudeChange = (e) => {
setLatitude(e.target.value);
};
const handleLongitudeChange = (e) => {
setLongitude(e.target.value);
};
return (
<div>
<div className='field-type text'>
<label className='field-label'>
City
</label>
<input
type="text"
className='field-name'
onKeyDown={handleCityEnter}
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} onChange={handleLongitudeChange}></input>
</li>
<li>
<label className='field-label'>Location - Latitude</label>
<input id="field-latitude-latitude" type="number" name="location.latitude" value={latitude} onChange={handleLatitudeChange}></input>
</li>
</ul>
</div>
</div>
);
};

View File

@ -0,0 +1,12 @@
import { PointField } from 'payload/types';
import { GeoPicker } from './GeoPicker';
export const geoPickerField: PointField = {
name: 'Location',
type: 'point',
admin: {
components: {
Field: GeoPicker,
},
},
}