Webdesign und Medien
Leave a comment

Distance Calculator

Calculate the distance between two points on the earth. The very simple JQuery program assumes that the earth is perfectly spherical. Look in the source for more information.

from: °
°

to: °
°

The distance is: Fill the form above and you’ll see the distance.

The source code is highlighted by my Jush syntax highlighter for WordPress.

jQuery(function($) {
  $('#distance p *').change(function() {
    var ay = parseInt($('#distance_a1').val()) +
       parseInt($('#distance_a2').val())/60 +
       parseInt($('#distance_a3').val())/3600;
    if ($('#distance_a4').val()=="south") ay*=-1;
    ay=ay/180*Math.PI;

    var ax = parseInt($('#distance_b1').val()) +
       parseInt($('#distance_b2').val())/60 +
       parseInt($('#distance_b3').val())/3600;
    if ($('#distance_b4').val()=="west") ax*=-1;
    ax=ax/180*Math.PI;

    var cy = parseInt($('#distance_c1').val()) +
       parseInt($('#distance_c2').val())/60 +
       parseInt($('#distance_c3').val())/3600;
    if ($('#distance_c4').val()=="south") cy*=-1;
    cy=cy/180*Math.PI;

    var cx = parseInt($('#distance_d1').val()) +
       parseInt($('#distance_d2').val())/60 +
       parseInt($('#distance_d3').val())/3600;
    if ($('#distance_d4').val()=="west") cx*=-1;
    cx=cx/180*Math.PI;

    var distance = Math.acos(Math.sin(ay)*Math.sin(cy)+
       Math.cos(ay)*Math.cos(cy)*Math.cos(ax-cx))*6378.137;
    $('#distance_result').
       text(Math.round(distance*100)/100 + " km = " +
       Math.round(distance/0.01609344,2)/100 + " miles = " +
       Math.round(distance/0.01852,2)/100 + " nautical miles");
  });
});

Leave a Reply

Your email address will not be published. Required fields are marked *