3

如何使用 node.js 查找两个地理点(一组经度和经度)之间的距离。

我有使用谷歌地图距离矩阵服务的客户端javascript代码。

我想在服务器端javascript(在 node.js router.js 或 datamodel.js 中)做同样的事情。

我的客户端 Javascript 代码:

  function calculateDistances() {
          var gs =require('googlemaps');
            var latlong = { 'latitude': 52.5112, 'longitude': 13.45155};
         var origin1 = gs.LatLng(13.125511084202,80.029651635576);
      var origin2 = new google.maps.LatLng(12.9898593006481,80.2497744326417);;
           var destinationA = new google.maps.LatLng(13.125511084202,80.029651635576);;
          var destinationB = new google.maps.LatLng(12.9898593006481,80.2497744326417);
       var service = new google.maps.DistanceMatrixService();
      service.getDistanceMatrix(
  {
    origins: [origin1, origin2],
    destinations: [destinationA, destinationB],
    travelMode: google.maps.TravelMode.DRIVING,
    unitSystem: google.maps.UnitSystem.METRIC,
    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  = '';
      deleteOverlays();

      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);
          outputDiv += origins[i] + ' to ' + destinations[j]
              + ': ' + results[j].distance.text + ' in '
              + results[j].duration.text + '';
        }

      }
      console.log(outputDiv);
    }
  }

你能建议我用距离矩阵示例代码在 node.js 包中做同样的事情吗?

4

2 回答 2

11

也许这个包?https://github.com/manuelbieh/geolib

而这个方法:

geolib.getDistance(object start, object end, [int accuracy])
于 2013-01-22T10:21:57.697 回答
3

查看https://github.com/edwlook/node-google-distance

var distance = require('google-distance');

distance.get(
  {
    origin: 'San Francisco, CA',
    destination: 'San Diego, CA'
  },
  function(err, data) {
    if (err) return console.log(err);
    console.log(data);
});

这将输出:

{
  index: null,
  distance: '807 km',
  distanceValue: 807366,
  duration: '7 hours 30 mins',
  durationValue: 26981,
  origin: 'San Francisco, CA, USA',
  destination: 'San Diego, CA, USA',
  mode: 'driving',
  units: 'metric',
  language: 'en',
  avoid: null,
  sensor: false
}
于 2014-04-23T17:14:13.523 回答