Search code examples
javascriptreactjsgeolocationleaflet

How to get user location data without rendering the map - Leaflet


I want get user location to variable (or session variable) for print on map later in next component.

So, I made js file with this code:

import L from "leaflet";

let geolocation;
//Make map
let map = L.map('map').fitWorld();

// Locate you
map.locate({setView: true, maxZoom: 16});
function onLocationFound (e) {
    console.log(e);
    geolocation = e;
}
map.on('locationfound', onLocationFound);

function onLocationError (e) {
    alert(e.message);
}

map.on('locationerror', onLocationError);


export default geolocation;

My task is to obtain a shortened name of the state, for example: I am in Germany, after downloading the location I need the abbreviation "DE" I tried to do this with the "leaflet" plugin, but maybe there are other better ways. And while executing the code, I am forced to indicate where the map under which ID will be placed


Solution

  • I found a solution to the problem. I will use api for this "http://ip-api.com/json/"