Skip to content

Commit

Permalink
fix to allow latlon in search
Browse files Browse the repository at this point in the history
  • Loading branch information
VPoussou committed Jun 20, 2024
1 parent 421976e commit ca6385c
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions src/geocoder-control.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,58 @@ export default function GeocoderControl(
): React.ReactElement {
const [marker, setMarker] = useState(null);

const coordinatesGeocoder = function (query) {
// Match anything which looks like
// decimal degrees coordinate pair.
const matches = query.match(
/^[ ]*(?:Lat: )?(-?\d+\.?\d*)[, ]+(?:Lng: )?(-?\d+\.?\d*)[ ]*$/i
);
if (!matches) {
return null;
}

function coordinateFeature(lng:any, lat:any) {
return {
center: [lng, lat],
geometry: {
type: 'Point',
coordinates: [lng, lat]
},
place_name: 'Lat: ' + lat + ' Lng: ' + lng,
place_type: ['coordinate'],
properties: {},
type: 'Feature'
};
}

const coord1 = Number(matches[1]);
const coord2 = Number(matches[2]);
const geocodes = [];

if (coord1 < -90 || coord1 > 90) {
// must be lng, lat
geocodes.push(coordinateFeature(coord1, coord2));
}

if (coord2 < -90 || coord2 > 90) {
// must be lat, lng
geocodes.push(coordinateFeature(coord2, coord1));
}

if (geocodes.length === 0) {
// else could be either lng, lat or lat, lng
geocodes.push(coordinateFeature(coord1, coord2));
geocodes.push(coordinateFeature(coord2, coord1));
}

return geocodes;
};

const geocoder = useControl<MapboxGeocoder>(
() => {
const ctrl = new MapboxGeocoder({
...props,
localGeocoder: coordinatesGeocoder,
marker: false,
accessToken: props.mapboxAccessToken,
flyTo: { duration: 0 },
Expand Down

0 comments on commit ca6385c

Please sign in to comment.