# Algorithm for Calculating Distance Between Two Points

I'm working on an API that identifies points within a given proximity to a specific latitude and longitude. I'm leveraging three ESRI geometry services. The first is the buffer service that returns all locations within the proximity to the discrete lat/lon. The second service is a query that finds all points in my feature service that are within the buffer polygon. These two steps result in two requests to ArcGIS Server. I'm pushing the results to a simple table that is generated from the JSON response. I'd like to add a column to the table that shows the distance each point is from the given lat/lon. I was able to get the data by making requests to a third geometry service - the distance service. The problem with this is that the API might have to make a maximum of nearly 900 separate requests to the distance service. Virtually all calls to the API will result in no more than 10 features being returned and runtime is great up to a couple hundred. Runtime goes up to about 25 seconds for all features. I'm really not a fan of sending 900 requests to a REST endpoint, so I did some research and came up with an equation that will determine the distance between the two points. The equation is below. The trouble I'm having here is that the distances are off by a relatively small degree when compared to what ESRI's distance service returns. I've also tested using Leaflet's distance and distanceTo tools and those values are very close to what is returned from the equation below. I'm almost certain the discrepancy is due to the Earth_Radius parameter below. The parameter in the equation treats the radius of Earth as a constant whereas I believe ESRI has some fancy formula that adjusts the value based on lat/lon value.

So here is the question.

(1) Does anybody know where to find the equation ESRI uses to calculate distance? When I run the API with the equation runtime is superb.

``````lon1 = lon1*Math.PI/180;
lat1 = lat1*Math.PI/180;
lon2 = lon2*Math.PI/180;
lat2 = lat2*Math.PI/180;
var deltaLat = lat2 - lat1;
var deltaLon = lon2 - lon1;
var a = Math.pow(Math.sin(deltaLat/2), 2) + Math.cos(lat1) * Math.cos(lat2)
* Math.pow(Math.sin(deltaLon/2), 2);
var c = 2 * Math.asin(Math.sqrt(a));