0

I am working on a project in which I need to calculate the distance between two points. I just used the distancefrom function. I am just cruious, when I alert, the result is correct. However, When I use document.getElementById, it does not work. I am wondering whether anybody here can help me to figure out what happened in my code...... Thank you so much!

<html>
<head>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
    google.maps.LatLng.prototype.distanceFrom = function(newLatLng) {
        if (newLatLng==undefined) return false;

        var dLat = (newLatLng.lat()-this.lat()) * Math.PI / 180;
        var dLon = (newLatLng.lng()-this.lng()) * Math.PI / 180;
        var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(this.lat() * Math.PI / 180 ) * Math.cos(newLatLng.lat() * Math.PI / 180 )* Math.sin(dLon/2) * Math.sin(dLon/2);
        return 6371000 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      }

</script>
</head>
<body>
<script>
var loc1 = new google.maps.LatLng(52.5773139, 1.3712427);
var loc2 = new google.maps.LatLng(52.4788314, 1.7577444);
alert (Math.round(loc1.distanceFrom(loc2)/10)/160 + 'mi');
document.getElementById("1").innerHTML=Math.round(loc1.distanceFrom(loc2)/10)/160 + 'mi';
</script>
        <p id="1">xyz
        </p>


        </body>
</html>
2
  • A quick Google search provided this page, movable-type.co.uk/scripts/latlong.html - it has Javascript variables with the math behind how to calculate distance and bearing.
    – Enijar
    Sep 24, 2013 at 22:48
  • 1
    Please elaborate "it does not work". Nothing happens? Getting unexpected results? An error occurs? Other? Ähh.. actually put your p before the script.
    – Teemu
    Sep 24, 2013 at 22:51

1 Answer 1

0

Your script is including the Google Maps Javascript API v3:

<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>

That API does not have a distanceFrom method of google.maps.LatLng objects. To calculate the (straight-line) distance between two coordinates in the v3 API use the geometry library computeDistanceBetween method.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.