Search code examples
pythongeopy

PYTHON : Which is the best way to find distance between two points based on latitude/longitude using python?


I Am developing a location based app using python django. I want to find the distance between two points based on latitude/longitude. I found several answers but the final result(distance) is different in each. Please find me the best way to find the distance. Thanks


Solution

  • From your comments, i am assuming you need to calculate a short distance less than 50 miles, The easiest less accurate method would be to coordinate point distance formula, `aka, pythagorean distance formula enter image description here

    where a,b is obviously the latitude, longitude pair. Now one degree of latitude = 68~69miles or 111km. Remember this is just an approximation. Just multiply the result of the equation with the latitude miles. This gives a rather crude filter when coming to short distance, i use this to filter by distance when i need to make to make to many calculations, using google api to show results can be rather expensive(time, bandwidth, quota wise) considering my application needs to filter about 100 results per search. Also i suggest to add in a 20~30% variation to include actual road distance.

    Ok. If your still reading this then you need more accurate result.

    Then use this, remember to convert this code to python format. I just used the javascript code with me.

      function getDistanceLatLong(lat1,Long1,lat2,Long2) {
      var RK = 6371; // Radius of the earth in km
      var RM = 3959;
      var dLat = deg2rad(lat2-lat1);  // deg2rad below
      var dLong = deg2rad(Long2-Long1); 
    
      var a =  Math.sin(dLat/2) * Math.sin(dLat/2) +  
               Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
               Math.sin(dLong/2) * Math.sin(dLong/2); 
    
      var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
      var d = RK * c; // Distance in kiloMeters choose this or
      var d = RM * c; // Distance in Miles
      return d;
    }
    
    function deg2rad(deg) {
      return deg * (Math.PI/180)
    }