Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,623 questions

55,358 answers

573 users

How to calculate the distance between two latitude-longitude points in JavaScript

1 Answer

0 votes
// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
function degToRad(deg) {
    return deg * Math.PI / 180.0;
}

// ------------------------------------------------------------
// Compute the great-circle distance between two points on Earth
// using the Haversine formula.
// lat1, lon1, lat2, lon2 are in degrees.
// The result is returned in kilometers.
// ------------------------------------------------------------
function haversine(lat1, lon1, lat2, lon2) {

    // Earth's mean radius in kilometers
    const R = 6371.0;

    // Convert all angles to radians
    const rlat1 = degToRad(lat1);
    const rlon1 = degToRad(lon1);
    const rlat2 = degToRad(lat2);
    const rlon2 = degToRad(lon2);

    // Differences
    const dlat = rlat2 - rlat1;
    const dlon = rlon2 - rlon1;

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    const a =
        Math.sin(dlat / 2) ** 2 +
        Math.cos(rlat1) * Math.cos(rlat2) *
        Math.sin(dlon / 2) ** 2;

    // c is the central angle between the two points on the Earth’s surface.
    const c = 2 * Math.asin(Math.sqrt(a));

    // Final distance
    return R * c;
}

// ------------------------------------------------------------
// Main 
// ------------------------------------------------------------

// Example coordinates:
// Austin, Texas
const lat1 = 30.2672;
const lon1 = -97.7431;

// Houston, Texas
const lat2 = 29.7604;
const lon2 = -95.3698;

const distanceKm = haversine(lat1, lon1, lat2, lon2);

// Convert kilometers to miles
const distanceMiles = distanceKm * 0.621371;

console.log(`Distance: ${distanceKm.toFixed(3)} km`);
console.log(`Distance: ${distanceMiles.toFixed(3)} miles`);



/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/

 



answered 1 day ago by avibootz

Related questions

...