2016-08-10 7 views
0

각도 프로젝트에서 다음 위치 정보 서비스를 사용하여 위치를 얻으려고합니다. 서비스 파일 :각도 Geolocation 서비스에서 아무 것도 반환하지 않습니다.

angular.module('myApp') 
    .service('geolocation', function ($q, $http) { 
    var getLocation = function() { 
      var defer = $q.defer(); 
      // If supported and have permission for location... 
      if (navigator.geolocation) { 
       // 
       navigator.geolocation.getCurrentPosition(function(position){ 
        var result = {latitude : position.coords.latitude , longitude : position.coords.longitude} 
        // Adding randomization since we are all in the same location... 
        result.latitude += (Math.random() >0.5? -Math.random()/100 : Math.random()/100 ); 
        result.longitude += (Math.random() >0.5? -Math.random()/100 : Math.random()/100 ); 
        getNearbyCity(result.latitude, result.longitude).then(function(data){ 
         result.address = data.data.results[1].formatted_address; 
         defer.resolve(result); 
        }); 
       }, function(error){ 
        defer.reject({message: error.message, code:error.code}); 
       }); 
      } 
      else { 
       defer.reject({error: 'Geolocation not supported'}); 
      } 
      return defer.promise; 
     } 
     var getNearbyCity = function (latitude, longitude){ 
      var defer = $q.defer(); 
      var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude +',' + longitude +'&sensor=true'; 
      $http({method: 'GET', url: url}). 
       success(function(data, status, headers, config) { 
        defer.resolve({data : data}); 
       }). 
       error(function(data, status, headers, config) { 
        defer.reject({error: 'City not found'}); 
       }); 
      return defer.promise; 
     } 
     var service = { 
      getLocation : getLocation, 
      getNearbyCity: getNearbyCity 
     }; 
     return service; 
    }); 

그리고 내 컨트롤러를 호출

angular.module('myApp') 

      .controller('HomeCtrl', function ($scope, geolocation) { 


      geolocation.getLocation().then(function(result){ 
       $scope.location = result; 
       console.log($scope.location); 
      }); 
}); 

불행히도을 console.log()는 아무 것도 반환하지 않습니다. 여기서 내가 뭘 잘못하고 있니?

답변

0

내가 당신의 코드로 문제를 볼 수있는 요청을 변경하지 마십시오 : 나는 URL을 변경

'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latitude +',' + longitude +'&sensor=true'; 

작업 Plunker

+0

, 그것은 작동하지 않습니다. 플 런커가 작동하지 않습니다. – Ericel

+0

작동합니다! 버튼을 클릭해야합니다. 이제 ng-init으로 변경했습니다. – Sajeetharan

+0

이것은 내 Windows 컴퓨터에서 잘 작동합니다. 하지만 리눅스에서는 그렇지 않다. 도대체 무슨 일이 일어나는지 확인하겠습니다. 당신의 노력에 감사드립니다. 감사합니다. – Ericel

0
window.navigator.geolocation.getCurrentPosition(function(pos){ 
    $http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng='+pos.coords.latitude+','+pos.coords.longitude+'&sensor=true').then(function(res){ 
    console.log(res.data); 
    }); 
}) 
+0

이 코드는 질문에 대답 할 수 있습니다. 이유 및/또는이 코드가 질문에 어떻게 대답하는지에 대한 추가 컨텍스트를 제공하면 장기적인 가치가 향상됩니다. 코드 만 사용하는 것은 권장하지 않습니다. – Ajean

관련 문제