You want what's called the "great-circle distance" between the two points. That's basically the shortest path between two points on the surface of a sphere. (Earth isn't quite a sphere, but it's close enough.)
Anyway, the point is to find the angle between the two lines from the center of the sphere to each point. Multiply that by the radius of the sphere, and that's your distance.
One of the most basic formulas is based on the "spherical law of cosines".
(Thanks, Wikipedia! :))
ϕ1 and ϕ2 represent the latitudes of the two points, and Δλ is the difference between the longitudes. Δσ is the angle between the two points; assuming it's in radians, you can multiply it by the radius of the sphere, and that gives you the length of the arc that connects them.
In JavaScript:
function arc_distance(loc1, loc2) {
var rad = Math.PI / 180,
earth_radius = 6371.009, // close enough
lat1 = loc1.lat * rad,
lat2 = loc2.lat * rad,
dlon = Math.abs(loc1.lon - loc2.lon) * rad,
M = Math;
return earth_radius * M.acos(
(M.sin(lat1) * M.sin(lat2)) + (M.cos(lat1) * M.cos(lat2) * M.cos(dlon))
);
}
When this formula was first used on computers, it really sucked with short distances. But numbers were quite a bit smaller back then, too. With numbers in JS being 64-bit, the accuracy is much better than some people have warned about. It can easily deal with distances less than a kilometer, and even at less than a meter it's reasonably close to other methods.