Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Google Map v3: How to calculate distance between two end points?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 253
    Comment on it

    Google Map v3: Calculate Distance

    How to calculate distance between two end points in google map v3?

    Use the Haversine formula to calculate distance between two end points.

    Note: you must add &libraries=geometry to your script source. This is the following code:

    1. <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry"></script>
    2.  
    3. var rad = function(x) {
    4. return x * Math.PI / 180;
    5. };
    6.  
    7. var getDistance = function(p1, p2) {
    8. var R = 6378137; // Earths mean radius in meter
    9. var dLat = rad(p2.lat() - p1.lat());
    10. var dLong = rad(p2.lng() - p1.lng());
    11. var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    12. Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
    13. Math.sin(dLong / 2) * Math.sin(dLong / 2);
    14. var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    15. var d = R * c;
    16. return d; // returns the distance in meter
    17. };

    Thats all!

    Thanks for reading the blog

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: