title: Finding the closest difference between 2 degrees of a compass - Javascript
body: <p>I'm basically trying to find how many degrees apart two points of a compass are.  For example if a person is facing 270 and their compass is 280 there are 10 degrees between those 2 points.  I'd also like a negative number if it's to the left and positive to the right, relative to the 1st heading.</p>
  
  <p>The problem comes when the to headings are 350 and 020 for example.  These two points are 30 degrees apart but would give a result of -330.</p>
  
  <p>Below is an example of my code:</p>
  
  <pre><code>function ConvertToRadians(_var)
  {
      return _var * (Math.PI/180);
  }
  function ConvertToDegrees(_var)
  {
      return _var * (180/Math.PI);
  }
  function GetHeadingDiff(_Heading1, _Heading2)
  {   
      return ConvertToDegrees((ConvertToRadians(_Heading2) - ConvertToRadians(_Heading1)));
  }
  
  $(document).ready(function (){
      $('#process').click(function (e){
          e.preventDefault();
          var Hdg1 = parseFloat($('#heading1').val());
          var Hdg2 = parseFloat($('#heading2').val());
          $('#results').html(GetHeadingDiff(Hdg1,Hdg2));
      });
  });
  
  &lt;input id="heading1" type="text" /&gt;
  &lt;input id="heading2" type="text" /&gt;
  &lt;button id="process" type="button"&gt;Submit&lt;/button&gt;
  &lt;div id="results"&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>I'm sure there is some simple math function I'm missing, I just can't seem to figure it out.</p>
  
  <p>Here is a jsfiddle link <a href="http://jsfiddle.net/dTmPn/3/" rel="nofollow">http://jsfiddle.net/dTmPn/3/</a></p>