smeijer / leaflet-geosearch

A geocoding/address-lookup library supporting various api providers.
https://smeijer.github.io/leaflet-geosearch/
MIT License
1.04k stars 273 forks source link

Question: Reverse geocoding #247

Open cargallo opened 3 years ago

cargallo commented 3 years ago

Hi, first of all thanks for this great library. I have a doubt, does the library handle reverse geocoding for Open strett map? I'm asking because I didn't find any in documentation but in the code it seems that it was taked into consideration but I didn't find any reverse function implemented. Tnx in advance!

cargallo commented 3 years ago

For those whom need this behaviour in typescript. A temporary solution:

import axios from 'axios';
import { SearchResult } from 'leaflet-geosearch/src/providers/provider';

const service_url = "https://nominatim.openstreetmap.org/reverse?format=json";
const API_KEY = null; // if too many calls are made you need to provide an email to avoid access denied

export interface GeoLocationResult extends SearchResult { };

export const searchReverseLocation = async ({ latitude, longitude, zoom = 18 }): Promise<GeoLocationResult> => {
    let url = `${service_url}&lat=${latitude}&lon=${longitude}&zoom=${zoom}`;
    url = API_KEY ? `${url}&key=${API_KEY}` : url;
    try {
        const response = await axios.get(url);
        console.log(response.data);
        return {
            x: response.data.lon,
            y: response.data.lat,
            label: response.data.display_name,
            bounds: response.data.boundingbox,
            raw: response.data
        }
    } catch (error) {
        console.error(error);
        return error.toString();
    }
}
Ninosaurier commented 3 years ago

Nice solution. Worked for me!