# What NPM package should I use for finding the nearest city.

## Problem

I am using Node.js and MongoDB. Let say I have predefined few cities (e.g. Seattle, Miami, New York) with Lat & Lon. and there is a user click to my website and I know his IP address, and find out the lat & lon. Then I want to know which city that I've defined is the closest to the user.

I know I can do it using Mongo's geospatial feature. but it would be quite 'expensive' to use DB to calculate that for every web request.

Is there a Node.js NPM package that can do the geo feature as I described above?

Problem courtesy of: murvinlai

## Solution

If you already have the user's location and the location of each city, it should be quite fast to compute the distance to the nearest. Check out this site: http://www.movable-type.co.uk/scripts/latlong.html I have used the first algorithm a few times.

``````  function getDistance(lat1,lat2,lon1,lon2){
var R = 6371; // km
var c = Math.PI / 180;
var dLat = (lat2-lat1) * c;
var dLon = (lon2-lon1) * c;
var lat1 = lat1 * c;
var lat2 = lat2 * c;

var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
var closest, dist = Number.MAX_VALUE;
for(var i = 0, l=cities.length;i``````

You might want to add some exception handling here :)

Solution courtesy of: Jørgen

## Discussion

This post first appeared on Node.js Recipes, please read the originial post: here

# Share the post

What NPM package should I use for finding the nearest city.

×