2013-01-22 32 views
2

如何使用node.js找到兩個地理點(經度和緯度的集合)之間的距離。如何在node.js中查找兩個地理點之間的距離?

我有代碼在客戶端JavaScript使用谷歌地圖距離矩陣服務。

我想在serversidejavascript中做同樣的事情(在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); 
    } 
    } 

ü可以建議我做samething在Node.js的包帶距離矩陣的示例代碼。

回答

9

也許這個軟件包? https://github.com/manuelbieh/geolib

而且這種方法:

geolib.getDistance(object start, object end, [int accuracy]) 
+1

感謝您分享這個有用的模塊;) – Roberto14

+0

我下載了它NPM。任何機會,我可以得到一點工作幫助。我一直收到以下錯誤:Uncaught ReferenceError:未定義geolib – rashadb

+2

@rashadb在控制檯中完成'npm install geolib'之後,在代碼的開頭使用var geolib = require('geolib');'。 – maxdec

2

退房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 
}