0

레코드와 사용자 위치 사이의 거리를 가져 오려고합니다. 그리고 나에게 가장 가까운 사람에게 주문하십시오. 나는 hacersine과 비슷한 공식을 사용하고 있지만, 아직 거리를 얻지 못하고 있습니다. 감사. angularjs에서 거리를 얻고 거리별로 정렬하는 방법?

내 코드 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> 

는 하버 사인하기 :

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

+0

사용하고있는 데이터베이스? –

답변

0

좌표는, 당신은 다음을 통해 얻을 수 있습니다 : $scope.porlogo[iteration].Latitud & $scope.porlogo[iteration].Longitud

따라서 논문을 가지고 있으려면 반복해야합니다.

중요 : 적절한 거리를 돌아갑니다 distancia 기능을 추가,

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

및 컨트롤러에서 : 당신은보기에서 반복을 사용할 수 그러나 당신이 사용해야 할 경우 에서는 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

+0

아주 잘 거리를 얻는 것 같습니다. 그러나 순서는 올바르게 주문하지 않습니다 : ** 3.1, 20.3, 20.2, .... 19.4, 1.9 ** 이 사건을 어떻게 해결할 생각이 있습니까? –

+0

이 코드는 적응 시키려고 시도하지만 성공하지는 않습니다. http://jsfiddle.net/6tp92nfn/ –

+0

.toFixed (1)을 제거하면 올바른 순서로 반환됩니다. 왜 그런지 알아? toFixed()가 문자열을 반환 할 것이기 때문에 : D parseFloat을 수정하여 (미안 해요) – Fetrarij