I'm working on a project that requires me to capture latitude, longitude, an array of zip codes, and country information using a single IP address. It thought it might be helpful to share an example of how to do that using ES6. I've written the examples using Class methods and even show two different ways to use Promises.
const axios = require("axios");
const geo2zip = require('geo2zip');
const geolib = require('geolib');
const satelize = require('satelize');
const usZips = require('us-zips');
const zipcodes = require('zipcodes');
const _ = require('lodash');
class GeoUtils {
/* ** ** ** ** ** ** ** * ** ** ** ** ** ** ** *
* Search city info by Name of City
*
* ** ** ** ** ** ** ** * ** ** ** ** ** ** ** **/
static searchByName = async (cityName, state) => {
return await zipcodes.lookupByName(cityName, state)
.then(response => response)
.catch(LookupError => LookupError)
}
/* ** ** ** ** ** ** ** * ** ** ** ** ** ** ** *
* Satelize Data
* content_code, continent, country_code, country, latitude, longitude, timezone
* ** ** ** ** ** ** ** * ** ** ** ** ** ** ** **/
static getSatelizeData = async (ip) => {
return await new Promise( async (resolve, reject) => {
try{
satelize.satelize({ip: ip}, (err, payload) => {
if(err) {
console.log('timeout', err.message)
if( _.contains( err, "timeout" ) ){
let tryAgain = getSatelizeData(ip);
setTimeout(tryAgain, 200);
} else {
reject(err);
}
}
resolve(payload);
});
} catch (IPError) {
reject(IPError)
}
});
}
/* ** ** ** ** ** ** ** * ** ** ** ** ** ** ** *
* Convert IP address to Lat / Lng
*
* This Google Hosted App is very finicky so the request is hand crafted
* ** ** ** ** ** ** ** * ** ** ** ** ** ** ** **/
//http://stackoverflow.com/questions/6432693/post-data-with-request-module-on-node-js
static getMyIP = async () => {
return await axios({
"method": "GET",
"url": "http://www.trackip.net/ip",
"headers": { "Content-Type": "application/json" }
})
.then(response => response.data)
.catch(GetIPError => GetIPError)
}
/* ** ** ** ** ** ** ** * ** ** ** ** ** ** ** *
* Get Zip codes from a single Latitude Longitude
* return an array
* ** ** ** ** ** ** ** * ** ** ** ** ** ** ** **/
static getZipCodes = async (coords) => {
return await geo2zip(coords, { limit: 5 })
.then(zipcodes => { return { zipcodes: zipcodes } })
.catch(ZipCodeError => ZipCodeError)
}
}
(async () => {
// A. Get the client IP address
let ip = await GeoUtils.getMyIP();
// B. Get lat, lon, and more.
let geoObj = await GeoUtils.getSatelizeData(ip)
// C. Capture a collection of surrounding zipcodes based on a geo coords
let coords = { lat: geoObj.latitude, lng: geoObj.longitude };
let zipcodes = GeoUtils.getZipCodes(coords);
// D. Create a new object
let clone = Object.assign(geoObj, await zipcodes);
console.log(clone);
})();
Get latitude, longitude, surrounding zip codes and country data from an IP address.