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 Rust

1 Answer

0 votes
use std::f64::consts::PI;

// ------------------------------------------------------------
// Convert degrees to radians
// ------------------------------------------------------------
fn deg_to_rad(deg: f64) -> f64 {
    deg * 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.
// ------------------------------------------------------------
fn haversine(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {

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

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

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

    // Haversine formula
    // a is the Haversine of the central angle between the two points.
    let a =
        (f64::sin(dlat / 2.0)).powi(2) +
        f64::cos(rlat1) * f64::cos(rlat2) *
        (f64::sin(dlon / 2.0)).powi(2);

    // Central angle
    // c is the central angle between the two points on the Earth’s surface.
    let c = 2.0 * f64::asin(f64::sqrt(a));

    // Final distance
    R * c
}

fn main() {

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

    // Houston, Texas
    let lat2: f64 = 29.7604;
    let lon2: f64 = -95.3698;

    let distance_km: f64 = haversine(lat1, lon1, lat2, lon2);

    // Convert kilometers to miles
    let distance_miles: f64 = distance_km * 0.621371;

    println!("Distance: {:.3} km", distance_km);
    println!("Distance: {:.3} miles", distance_miles);
}



/*
run:

Distance: 235.352 km
Distance: 146.241 miles

*/

 



answered 1 day ago by avibootz
edited 1 day ago by avibootz

Related questions

...