Google Maps DistanceMatrix

时光总嘲笑我的痴心妄想 提交于 2019-12-25 18:27:06

问题


I am using Google API, what I need to do is get two different distances in miles. At the moment I have the following:-

var start = arrObjLatLngs[0];
var end = arrObjLatLngs[arrObjLatLngs.length - 1];

var base = new google.maps.LatLng(52.781048888889, -1.2110222222222546);

var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
  {
    origins: [base, base],
    destinations: [start, end],
    travelMode: google.maps.TravelMode.DRIVING,
    avoidHighways: false,
    avoidTolls: false
  }, callback);


function callback(response, status) {
  if (status == google.maps.DistanceMatrixStatus.OK) {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      for (var j = 0; j < results.length; j++) {
        var element = results[j];
        var distance = element.distance.text;
        var duration = element.duration.text;
        var from = origins[i];
        var to = destinations[j];
      }
    }
  }
}

What I need to have is two variables; $runinPickup and $runinDestination that contains the distance between 1.) base and start (which will be $runinPickup) and 2.) base and end (which will be $runinDestination)

If I alert distance I get the response:-

13.9 km

5.2 km

13.9 km

5.2 km

Firstly, I'm just wanting to know how I can get the distance of just the distance between base and start as $runinPickup. Secondly, is there a way I can do this so it doesn't include the decimal? So instead of 13.9 km for the first value, it would just be 13.

Then I would need to convert it into miles, which I'm guessing once I can get the value I would do it as follows:

var pickup_distance = parseInt(($fieldPickup / 8) * 5); ?

Any help would be much appreciated! :)


回答1:


Did you read the documentation? Passing the same address twice in the origins array:

   origins: [base, base],
   destinations: [start, end],

Is going to give you the same result twice. This should work (not tested), and give you 2 results:

   origins: [base],
   destinations: [start, end],

To get miles I would suggest setting the unitSystem to IMPERIAL (although I can't find a definition of what that means in the documentation):

unitSystem (optional) — The unit system to use when displaying distance. Accepted values are:

google.maps.UnitSystem.METRIC (default)
google.maps.UnitSystem.IMPERIAL

You can of course convert METRIC units to miles.

Example showing the two values, with distances in IMPERIAL units. Modified from the example in the documentation.

code snippet:

var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];

var base = new google.maps.LatLng(55.930385, -3.118425);
var start = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var end = new google.maps.LatLng(50.087692, 14.421150);

var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';

function initialize() {
  var opts = {
    center: new google.maps.LatLng(55.53, 9.4),
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map'), opts);
  geocoder = new google.maps.Geocoder();
  calculateDistances();
}

google.maps.event.addDomListener(window, 'load', initialize);

function calculateDistances() {
  var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix({
    origins: [base],
    destinations: [start, end],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.IMPERIAL,
    avoidHighways: false,
    avoidTolls: false
  }, callback);
}

function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var outputDiv = document.getElementById('outputDiv');
    outputDiv.innerHTML = '<table border="1">';
    deleteOverlays();
    var stringArray = ['$runinPickup', '$runinDestination'];
    var htmlString = '<table border="1">';
    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      addMarker(origins[i], false);
      for (var j = 0; j < results.length; j++) {
        addMarker(destinations[j], true);
        htmlString += '<tr><td>' + stringArray[j] + '</td><td>' + results[j].distance.text + '</td></tr>';
        outputDiv.innerHTML += '<tr><td>' + stringArray[j] + '</td><td>' + results[j].distance.text + '</td></tr>';
      }
    }
    htmlString += '</table>';
    // outputDiv.innerHTML += '</table>';
    outputDiv.innerHTML = htmlString;
    // alert(htmlString);
  }
}

function addMarker(location, isDestination) {
  var icon;
  if (isDestination) {
    icon = destinationIcon;
  } else {
    icon = originIcon;
  }
  geocoder.geocode({
    'address': location
  }, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      bounds.extend(results[0].geometry.location);
      map.fitBounds(bounds);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        icon: icon
      });
      markersArray.push(marker);
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}
body {
  margin: 20px;
  font-family: courier, sans-serif;
  font-size: 12px;
}
#map {
  height: 480px;
  width: 640px;
  border: solid thin #333;
  margin-top: 20px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="outputDiv"></div>
<div id="map"></div>


来源:https://stackoverflow.com/questions/15413922/google-maps-distancematrix

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!