admin管理员组

文章数量:1410705

$http.get('*****').success(function(data,dealers,response)
{    
 $scope.items = data;
 $scope.item ='';
 console.log(data);
var shoplatit=data.S_Location.Latitude;
 var shoplong=data.S_Location.Longitude;
															
});

$scope.nearme = function($scope) {
 if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
                mysrclat = position.coords.latitude; 
                mysrclong = position.coords.longitude;
                console.log(mysrclat);
                console.log(mysrclong);
        });
        
    }
  i tried like this but its not working getting  deg2rad is not defined erro
var lat1 =15.008809;
var lat2 =78.659096;

var lon1 =13.90457539;
var lon2 =78.5855514

  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1); 
  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ; 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = R * c; // Distance in km
   console.log(d);
<div ng-controller="ListingCtrl" >
  <div data-ng-init="nearme()">
    
    <div class="list card" data-ng-repeat="item in items">
    <h2>{{item.Store_Name}} </h2>{{item.S_Location.Latitude}}<br>{{item.S_Location.Longitude}}
    <p>{{item.S_Address}}</p> 
   <h1>here i want show distance in km</h1>
  </div>
    </div>
  </div>

$http.get('*****').success(function(data,dealers,response)
{    
 $scope.items = data;
 $scope.item ='';
 console.log(data);
var shoplatit=data.S_Location.Latitude;
 var shoplong=data.S_Location.Longitude;
															
});

$scope.nearme = function($scope) {
 if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
                mysrclat = position.coords.latitude; 
                mysrclong = position.coords.longitude;
                console.log(mysrclat);
                console.log(mysrclong);
        });
        
    }
  i tried like this but its not working getting  deg2rad is not defined erro
var lat1 =15.008809;
var lat2 =78.659096;

var lon1 =13.90457539;
var lon2 =78.5855514

  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1); 
  var a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ; 
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
  var d = R * c; // Distance in km
   console.log(d);
<div ng-controller="ListingCtrl" >
  <div data-ng-init="nearme()">
    
    <div class="list card" data-ng-repeat="item in items">
    <h2>{{item.Store_Name}} </h2>{{item.S_Location.Latitude}}<br>{{item.S_Location.Longitude}}
    <p>{{item.S_Address}}</p> 
   <h1>here i want show distance in km</h1>
  </div>
    </div>
  </div>

I have stored store latitude and longitude in mongodb. In listing page i am getting customer latitude and langitude using navigator.geolocation.i want to calculate distance between two latitiude and longitude .i have enclosed my code

Share Improve this question asked Jul 10, 2015 at 5:18 its meits me 5426 gold badges30 silver badges67 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

This lat-long debug may help you to debug geographical distance and other aspects easily.

Below is the functional JS code to calculate it; also it has deg2rad() function, which is used for converting the number in degrees to the radian equivalent (which appears to be missing in your code).

I have used two coordinates provided by you, and the distance returned is 123.04 km, also crosschecked through Google Maps to verify same.

/* 
Title: Get Distance from two Latitude / Longitude in Kilometers.

Description: This Javascript snippet calculates great-circle distances between the two points 
—— that is, the shortest distance over the earth’s surface; using the ‘Haversine’ formula.
*/

function _getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
  var R = 6371; // Radius of the earth in kilometers
  var dLat = deg2rad(lat2 - lat1); // deg2rad below
  var dLon = deg2rad(lon2 - lon1);
  var a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c; // Distance in KM
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI / 180)
}



// Point 1: 15.008809, 78.659096
// Point 2: 13.90457539, 78.5855514

var _lat1 = 15.008809;
var _lon1 = 78.659096;

var _lat2 = 13.90457539;
var _lon2 = 78.5855514;

// precise value
var _d = "Precise value: " + _getDistanceFromLatLonInKm(_lat1, _lon1, _lat2, _lon2);
console.log(_d); // alert(_d);


// round value
_d = "Round value: " +
  Math.round(_getDistanceFromLatLonInKm(_lat1, _lon1, _lat2, _lon2) * 100) / 100 +
  " km";
console.log(_d); // alert(_d);

Considering that you mention you have the data for the locations you seem to be trying to list "near" the current location of the device making the query, then you are going about this all wrong.

MongoDB supports geospatial queries, where your data is formatted correctly of course. From here you can let the "server" do the distance calculation for you rather than trying to work out the distance between two points in your client code. It just takes a little setup.

Presuming you are following the "MEAN" stack thing and therefore using mongoose on your nodejs server ( which of course you have don't you? ) then you will probably want to set up a schema something like this:

var placeSchema = new Schema({
    "name": String,
    "location": {
        "type": String,
        "coordinates": []
    }
});

placeSchema.index({ "location": "2dsphere" })
module.exports = mongoose.model("Place",placeSchema);

That set's up your collection "places" with some data and most importantly the "location" field stored in GeoJSON format. It's a good idea to follow that standard as it's widely supported across many API's, and words well for getting "correct" distances around the globe.

The other thing you will see there is the "2dsphere" index. This is used by the sort of geospatial query you will be using in order to find things "near" to the location you are being used to query.

The data in the collection then should look something like this:

{
    "name": "Sydney",
    "location": {
        "type": "Point",
        "coordinates": [150.9224326,-33.7969235]
    }
}

Note that the order of coordinates here is "longitude" then "latitude" in order to be valid.

All you need now is to execute in your controller code ( server ) the MongoDB method to query the data. In order to return a "distance" the operation used must be something that returns that "distance" field. There are two options being the geoNear database mand for which mongoose provides a wrapper, or the $geoNear aggregation framework operator. We'll stick with the aggregate operator since there is a bit more flexibility there.

var coordinates = [150.9418357,-33.7775636]

Place.aggregate(
    [
       { "$geoNear": {
            "near": {
                "type": "Point",
                "coordinates": coordinates
            },
            "distanceField": "distance",
            "distanceMultiplier": 0.001,
            "spherical": true
        }}
     ],
    function(err,results) {
         // send results in the response
    }
);

That will return results that are both "ordered" by nearest distance from the queried point and also with the "distance" calculated to kilometers:

{ 
    "_id" : ObjectId("559f68366274d659c90d02b8"),
    "name" : "Parramatta",
    "location" : { 
        "type" : "Point",
        "coordinates" : [ 151.0082989, -33.8151255 ]
    },
    "distance" : 8.255873925464623
},
{
     "_id" : ObjectId("559f68366274d659c90d02b7"),
     "name" : "Sydney",
     "location" : { 
         "type" : "Point", 
         "coordinates" : [ 151.2094, -33.865 ]
     }, 
     "distance" : 27.46479097844148
 }

So have your service issue your navigator coordinates to your server API ( in correct order ) and then issue the query to return the results. The response data can then be ouput to your template without the need to calculate the distance in your client code.

Could not be more simple than that.

本文标签: javascripthow to calculate distance between two latitude and longitude using angulajsStack Overflow