2016-08-10 10 views
0

角度のあるプロジェクトで次の場所の測位サービスを使用して場所を取得しようとしています。 サービスファイル:角度測位サービスでは何も返されません

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コンピュータでうまくいきます。しかし、Linuxではそうではありません。私は何が起こっているのか確認するためにチェックします。私はあなたの努力に感謝します。ありがとう – 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

関連する問題