Skip to content

Instantly share code, notes, and snippets.

@k1sul1
Last active September 9, 2016 10:13
Show Gist options
  • Save k1sul1/ff1a7e0a8904d905ff705cc0c94f58d8 to your computer and use it in GitHub Desktop.
Save k1sul1/ff1a7e0a8904d905ff705cc0c94f58d8 to your computer and use it in GitHub Desktop.
ES6 function to asynchronously get user region by IP.
import Cookies from 'cookies-js';
export function getRegion() {
return new Promise((resolve, reject) => {
function deg2rad(deg) {
return deg * (Math.PI / 180);
}
function getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
const R = 6371; // Radius of the earth in km
const dLat = deg2rad(lat2 - lat1);
const dLon = deg2rad(lon2 - lon1);
const a =
Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon / 2) * Math.sin(dLon / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
const d = R * c; // Distance in km
return d;
}
const provinces = {
'Etela-Suomi': {
lat: 60.3845675,
long: 25.0254808,
},
'Keski-Suomi': {
lat: 62.4576291,
long: 27.0149535,
},
'Ita-Suomi': {
lat: 61.2935055,
long: 28.4981116,
},
'Lansi-Suomi': {
lat: 60.8023989,
long: 22.746071,
},
};
let userRegion;
if (window.location.pathname === '/') {
userRegion = Cookies.get('userRegion');
} else if (Object.keys(provinces).indexOf(window.location.pathname.substring(1)) > -1) {
userRegion = window.location.pathname.substring(1);
} else {
userRegion = Cookies.get('userRegion');
}
if (userRegion) {
resolve(userRegion);
} else {
const fallback = setTimeout(() => {
reject('Unable to get location');
}, 5000);
fetch('//freegeoip.net/json/')
.then(response => response.text())
.then(body => {
const response = JSON.parse(body);
const lat = response.latitude;
const long = response.longitude;
Object.keys(provinces).forEach(key => {
const pLat = provinces[key].lat;
const pLong = provinces[key].long;
provinces[key].distanceTo = getDistanceFromLatLonInKm(lat, long, pLat, pLong);
});
let distanceTo = 999999;
Object.keys(provinces).forEach(key => {
if (provinces[key].distanceTo < distanceTo) {
distanceTo = provinces[key].distanceTo;
userRegion = key;
}
});
resolve(userRegion);
Cookies.set('userRegion', userRegion);
clearTimeout(fallback);
});
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment