Baskar
Baskar

Reputation: 1140

How to find a distance between two geopoints in node.js?

How to find a distance between two geopoints(set of langitude and longitude) using node.js.

I have code in client side javascript using google maps distance matrix service.

I want to do same thing in serversidejavascript(In node.js router.js or datamodel.js).

My Client Side Javascript code:

  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);
    }
  }

Can u suggest me to do samething in node.js package with distance matrix sample code.

Upvotes: 2

Views: 14111

Answers (2)

Etcher
Etcher

Reputation: 90

Check out 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);
});

This will output:

{
  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
}

Upvotes: 3

maxdec
maxdec

Reputation: 5725

Maybe this package? https://github.com/manuelbieh/geolib

And this method:

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

Upvotes: 11

Related Questions