如何获得lat和lon地理位置坐标?

时间:2015-12-15 03:42:45

标签: javascript angularjs json api geolocation

我有应用程序通过lat和lon坐标显示您当前的位置并在地图上显示。此应用程序中还有一个功能显示标记表示景点。我使用lat和lon坐标从api wiki获得这些标记。 但问题是此刻的坐标是完全静态的,必须自己写入代码。我如何从第三方服务动态获得lat和lon?例如,来自JSON IP API

目前负责检索数据的代码

app.factory('places', ['$http', function($http) {

    return $http.jsonp('https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=5000&gscoord=' + 43.1056 + '%7C' + 131.8735 + '&gslimit=30&format=json&callback=JSON_CALLBACK')
        .success(function(data) {
            return data
        })
        .error(function(err) {
            return err
        })

}])

我试着这样做

app.factory('places', ['$http', '$scope', function($http, $scope) {

  $scope.coordinates = {};
  $http.get('http://ip-api.com/json')
    .success(function(data) {
      $scope.coordinates.lat = data.lat;
      $scope.coordinates.lon = data.lon;
    });

    return $http.jsonp('https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=5000&gscoord=' + coordinates.lat + '%7C' + coordinates.lon + '&gslimit=30&format=json&callback=JSON_CALLBACK')
        .success(function(data) {
            return data
        })
        .error(function(err) {
            return err
        })

}])

app.factory('places', ['$http', function($http) {

  $http.get('http://ip-api.com/json')
    .success(function(coordinates) {
         return $http.jsonp('https://en.wikipedia.org/w/api.php?action=query&list=geosearch&gsradius=5000&gscoord=' + coordinates.lat + '%7C' + coordinates.lon + '&gslimit=30&format=json&callback=JSON_CALLBACK')
                .success(function(data) {
                    return data
                })
                .error(function(err) {
                    return err
                })
    });

}])

但它不起作用。你能帮我解决这个问题吗? 如果您需要完整地查看应用程序的完整代码,可以在此处https://www.dropbox.com/s/qiu91hhdrc0qy5o/GeoApp.rar?dl=0

下载

1 个答案:

答案 0 :(得分:3)

您可以使用浏览器的HTML5功能,只需编写一个函数来获取当前坐标:

var deferred;

$scope.currentPosition = function() {
    deferred = $q.defer();

    if (window.navigator && window.navigator.geolocation) {
        window.navigator.geolocation.getCurrentPosition(currentPosition, handleErrorOnTrackCurrentPosition);
    } else {
        deferred.reject({msg: "Browser does not supports HTML5 geolocation"});
    }
    return deferred.promise;
};

function currentPosition(position) {
    deferred.resolve({latitude: position.coords.latitude, longitude: position.coords.longitude});
}

function handleError(error) {
    deferred.reject({msg: error.message});
}

现在,当你想获得当前坐标时,只需写下:

$scope.currentPosition().then(function(data) {
    console.log(data.latitude, data.longitude);
});
相关问题