【问题标题】:how to get distance and sort by distance in angularjs?如何在angularjs中获取距离并按距离排序?
【发布时间】:2017-09-10 01:56:54
【问题描述】:

我正在尝试获取记录与用户位置之间的距离。并由离我最近的人订购。 我正在使用类似于 hacersine 的公式,但我仍然没有得到距离。谢谢。

我的代码html:

    <div ng-app="my-app" id="por_logo.html">     
      <ons-page ng-controller="PorlogoCtl">
         <div class="cliente" ng-repeat="cliente in porlogo.clientes" ng-if="cliente.estado == '1'">
      <p>{{cliente.nombre}} <span>{{distancia2}}</span></p>
      </div>       
 </ons-page>
 </div>

类似于haversine:

function getDistanceFromLatLonInKm(lat1,lon1,lat2,lon2) {
          var R = 6878; // 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
          return d;
        };
        function deg2rad(deg) {
          return deg * (Math.PI/180)
        };

代码JS:

var app = angular.module('my-app', ['onsen']).factory('position', function( $rootScope ){

        // console.log('building position')
        var position = {};

          // 1ST / AUTO GEOLOCATION OF USER 
          // displays a popup to indicate current user location - (disabled)
          // onSuccess Callback - This method accepts a Position object, which contains the current GPS coordinates
         var onSuccess = function(position2) {

              console.log(position2.coords.latitude )
              console.log(position2.coords.longitude)

              position.latitude = position2.coords.latitude;
              position.longitude = position2.coords.longitude;
              $rootScope.$digest()
          };

        function onError(error) { // onError Callback receives a PositionError object
            // alert('code: '    + error.code    + '\n' +
                  // 'message: ' + error.message + '\n');
                  alert('No podemos acceder a su ubicación');
        }

        navigator.geolocation.getCurrentPosition(onSuccess, onError);

      return position;

    });
    app.controller("PorlogoCtl", function($scope, $http, position, $rootScope) {
      $http.get('https://viveenunclick.com/api.php/clientes?transform=1').
      success(function(data, status, headers, config) {
        $scope.porlogo = data;
        $rootScope.latitude = position.latitude;
        $rootScope.longitud = position.longitude;
        $rootScope.distancia2 = getDistanceFromLatLonInKm(position.latitude,position.longitude,$rootScope.latitude,$rootScope.longitud).toFixed(1);
        console.log($rootScope.longitud);
      }).
      error(function(data, status, headers, config) {});
    });

Post Demo in Codepen

【问题讨论】:

  • 你用的是什么数据库?

标签: angularjs angularjs-ng-repeat angularjs-orderby haversine


【解决方案1】:

坐标在返回的数据中,你会得到它:$scope.porlogo[iteration].Latitud & $scope.porlogo[iteration].Longitud

因此,要获得论文,您需要进行迭代。您可以在视图中使用迭代:

 <p>{{cliente.nombre}} <span>{{distancia(cliente)}}</span></p>

在您的控制器中,添加此 distancia 函数以返回正确的距离:

重要提示: 但是如果你需要使用 toFixed(1) 来返回一个字符串(顺序将是一个字符串),你需要添加 parseFloat() 所以它会返回一个数字并且顺序是正确的。

$scope.distancia = function(item) {
    //it's item.Latitud & item.Longitud, from the data
    return parseFloat(getDistanceFromLatLonInKm(position.latitude,position.longitude,item.Latitud,item.Longitud).toFixed(1));
}

您也可以使用此功能进行排序,

<div class="cliente" ng-repeat="cliente in porlogo.clientes | orderBy: distancia: false">

Working pen

【讨论】:

  • 看起来距离很远。但是,订单没有正确排序:3.1, 20.3, 20.2,.... 19.4, 1.9 你知道如何解决这种情况吗?
  • 我找到了这段代码,尝试改编它,但没有成功。 jsfiddle.net/6tp92nfn
  • 如果你删除 .toFixed(1) 返回正确的顺序。你知道为什么?因为 toFixed() 将返回一个字符串:D 添加 parseFloat 来修复它(对不起,我关闭了)
  • 我通过添加 parseFloat 更新了我的答案
  • 谢谢,尝试 parseFloat 没有结果。通过将其添加到您的代码并删除 toFixed() 来解决订单,因为您所说的会导致问题:

    {{distancia(cliente) | number:1}} 公里

    和中提琴!,非常感谢!
猜你喜欢
  • 2018-11-18
  • 1970-01-01
  • 1970-01-01
  • 2014-03-09
  • 2013-11-11
  • 1970-01-01
  • 2017-07-29
  • 2018-02-02
  • 2015-04-27
相关资源
最近更新 更多