开发者

Trying to find the distance between two LatLng objects using googlemaps api and javascript

Hi I am playing with html5 geolocation and have used the navigator.geolocation.getCurrentPosition(success, fail) object to get the users position.

In the success function I then created a variable called coords to hold the coordinates and a variable coords2 to hold other coordinates i made up.

 var coords = new google.maps.LatLng(position.coords.latitude position.coords.longitude); 
 var coords2 = new google.maps.LatLng(55.8619788, -4.2867578);

Using the following code I position the two points on the map as markers:

 var mapOptions = {

                zoom: 16,
                center: coords,
              开发者_如何转开发  mapTypeControl: false,
                navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
                mapTypeId: google.maps.MapTypeId.ROADMAP,

        };


 map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);  


 var marker = new google.maps.Marker({
                position: coords,
                map: map,
                title: "Your current location!"
        });


 var marker2 = new google.maps.Marker({
                position: coords2,
                map: map,
                title: "Nearest Person!"
        });

What I then want to do is work out the distance between these points. I cant seem to find a method that does it.

Here is what I am trying:

  var distance = computeDistanceBetween(coords, coords2);
  alert(distance);

Any idead what im doing wrong?Cheers! Paul


In v2, you can do

coords.distanceFrom(coords2);

It's documented at http://code.google.com/apis/maps/documentation/javascript/v2/reference.html#GLatLng

Edit: I think you may be using v3. If so, I believe you'll need the full namespace:

var distance = google.maps.geometry.spherical.computeDistanceBetween(coords, coords2);


There is the computeDistanceBetween() in the new V3 Geometry Library


The google.maps.geometry library is not loaded by default. You have to explicitly specify to load it also, in the bootstrap request:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=true_or_false"></script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜