javascript javascript中两个位置之间的距离

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20579783/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:49:19  来源:igfitidea点击:

Distance between two locations in javascript

javascriptjquerygoogle-mapsgoogle-maps-api-3

提问by user3101497

Can some one help me what went wrong on this code snippet ? My ultimate aim to find distance two locations using googles javascript API . I have used geocomplete jquery function for address autocomplete. On click of search nothing is happening.Im just a beginner please help

有人可以帮助我这个代码片段出了什么问题吗?我的最终目标是使用 googles javascript API 找到两个位置的距离。我已经使用 geocomplete jquery 函数进行地址自动完成。点击搜索什么也没有发生。我只是一个初学者,请帮忙

<!DOCTYPE html>
<html>
  <head>
    <title>Distance between Two Places</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="styles.css" />
     <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"></script>
     <script type="text/javascript">

    var geocoder, location1, location2;

    function initialize() {
        geocoder = new GClientGeocoder();
    }

    function showLocation() {
        geocoder.getLocations(document.forms[0].address1.value, function (response) {
            if (!response || response.Status.code != 200)
            {
                alert("Sorry, we were unable to geocode the first address");
            }
            else
            {
                location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                geocoder.getLocations(document.forms[0].address2.value, function (response) {
                    if (!response || response.Status.code != 200)
                    {
                        alert("Sorry, we were unable to geocode the second address");
                    }
                    else
                    {
                        location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                        calculateDistance();
                    }
                });
            }
        });
    }

    function calculateDistance()
    {
        try
        {
            var glatlng1 = new GLatLng(location1.lat, location1.lon);
            var glatlng2 = new GLatLng(location2.lat, location2.lon);
            var miledistance = glatlng1.distanceFrom(glatlng2, 3959).toFixed(1);
            var kmdistance = (miledistance * 1.609344).toFixed(1);

            document.getElementById('results').innerHTML = '<strong>Distance: </strong>' + miledistance + ' miles (or ' + kmdistance + ' kilometers)';
        }
        catch (error)
        {
            alert(error);
        }
    }



    </script>
  </head>
  <body onload="initialize()">

    <form action="#" onsubmit="showLocation(); return false;">
      <input id="geocomplete" type="text" name="address1" placeholder="Type in an address" size="90" />
        <input id="geocomplete1" type="text" name="address2" placeholder="Type in an address" size="90" />
     <input type="submit" name="find" value="Search" />
    </form>

   <p id="results"></p>

    <script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

    <script src="../jquery.geocomplete.js"></script>
    <script src="logger.js"></script>

    <script>
      $(function(){

        $("#geocomplete").geocomplete()
          .bind("geocode:result", function(event, result){
            $.log("Result: " + result.formatted_address);
          })
          .bind("geocode:error", function(event, status){
            $.log("ERROR: " + status);
          })
          .bind("geocode:multiple", function(event, results){
            $.log("Multiple: " + results.length + " results found");
          });

          $("#geocomplete1").geocomplete()
          .bind("geocode:result", function(event, result){
            $.log("Result: " + result.formatted_address);
          })
          .bind("geocode:error", function(event, status){
            $.log("ERROR: " + status);
          })
          .bind("geocode:multiple", function(event, results){
            $.log("Multiple: " + results.length + " results found");
          });

        $("#find").click(function(){
          $("#geocomplete").trigger("geocode");
        });


        $("#examples a").click(function(){
          $("#geocomplete").val($(this).text()).trigger("geocode");
          return false;
        });

      });
    </script>
  </body>
</html>

回答by Nouphal.M

You could use DistanceMatrixServiceof google map for calculating distance between two points.

您可以使用谷歌地图的DistanceMatrixService来计算两点之间的距离。

The following functions calculates the

以下函数计算

function calculateDistances() {
  origin = document.getElementById('source').value; //Get the source string
  destination = document.getElementById('dest').value; //Get the destination string
  var service = new google.maps.DistanceMatrixService(); //initialize the distance service
  service.getDistanceMatrix(
    {
      origins: [origin], //set origin, you can specify multiple sources here
      destinations: [destination],//set destination, you can specify multiple destinations here
      travelMode: google.maps.TravelMode.DRIVING, //set the travelmode
      unitSystem: google.maps.UnitSystem.METRIC,//The unit system to use when displaying distance
      avoidHighways: false,
      avoidTolls: false
    }, calcDistance); // here calcDistance is the call back function
}

Code for callback function calcDistance

回调函数calcDistance的代码

function calcDistance(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) { // check if there is valid result
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    deleteOverlays();

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;

      for (var j = 0; j < results.length; j++) {

        alert ('Distance from '+origins[i] + ' to ' + destinations[j]
            + ': ' + results[j].distance.text ); // alert the result
      }
    }
  }
}

You can find a working demo here

你可以在这里找到一个工作演示

回答by Denis

When you call calculateDistance(), give location1and location2as parameters

调用时calculateDistance(),将location1location2作为参数

var earthRadius = 6371;

function calculateDistance(posA, posB) {
    var lat = posB.lat-posA.lat; // Difference of latitude
    var lon = posB.lon-posA.lon; // Difference of longitude

    var disLat = (lat*Math.PI*earthRadius)/180; // Vertical distance
    var disLon = (lon*Math.PI*earthRadius)/180; // Horizontal distance

    var ret = Math.pow(disLat, 2) + Math.pow(disLon, 2); 
    ret = Math.sqrt(ret); // Total distance (calculated by Pythagore: a^2 + b^2 = c^2)

    // Now you have the total distance in the variable ret
} 

回答by ChrisSwires

You could also simply use the function computeDistanceBetween() exposed as part of api v3. Docs available Here.

您也可以简单地使用作为 api v3 的一部分公开的函数 computeDistanceBetween()。文档可用在这里

The function takes two latlng's as parameters and returns the distance between the two in metres.

该函数将两个 latlng 作为参数并返回两者之间的距离(以米为单位)。

回答by Sandesh

Add this to the starting of your JavaScript:

将此添加到您的开头JavaScript

google.maps.LatLng.prototype.distanceFrom = function(latlng) {
  var lat = [this.lat(), latlng.lat()]
  var lng = [this.lng(), latlng.lng()]
  var R = 6378137;
  var dLat = (lat[1]-lat[0]) * Math.PI / 180;
  var dLng = (lng[1]-lng[0]) * Math.PI / 180;
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
  Math.cos(lat[0] * Math.PI / 180 ) * Math.cos(lat[1] * Math.PI / 180 ) *
  Math.sin(dLng/2) * Math.sin(dLng/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return Math.round(d);
}

and then use the functionlike this:

然后function像这样使用:

var loc1 = new GLatLng(52.5773139, 1.3712427);
var loc2 = new GLatLng(52.4788314, 1.7577444);
var dist = loc2.distanceFrom(loc1);
alert(dist/1000);