javascript – AngularJS,Leaflet.如何从第三方服务动态获取lat和lon坐标?

我有一个简单的应用程序通过lat和lon坐标显示您当前的位置并在地图上显示.

但目前它是静态的,必须手动指定坐标.

完整的应用代码:

> index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
    <link rel="stylesheet" type="text/css" href="css/main.css">
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-leaflet-directive/0.10.0/angular-leaflet-directive.min.js"></script>
    <script src="https://code.angularjs.org/1.2.28/angular-route.min.js"></script>
    <script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
</head>
    <body ng-app="NearMeApp">

        <div class="header">
            <div class="container-fluid">
                <h1 class="pull-left">NearMe</h1>
                <a class="pull-right" href="#/about">About</a>
            </div>
        </div>

        <div ng-view></div>

        <script src="js/app.js"></script>

        <script src="js/controllers/MainController.js"></script>
        <script src="js/controllers/AboutController.js"></script>

    </body>
</html>

> pasteBin上的main.css
> main.html

<div class="main">
    <div class="container-fluid" id="map-canvas">
        <leaflet center="mapCenter"></leaflet>
    </div>
</div>

> about.html

<div class="about">
    <div class="container-fluid">
        <h1>Meet NearMe</h1>
        <h2>The best place to discover new places around you.</h2>
        <a class="btn btn-primary" href="#/">Start exploring</a>
    </div>
</div>

> app.js

var app = angular.module('NearMeApp', ['ngRoute', 'leaflet-directive']);

app.config(function($routeProvider) {
    $routeProvider
    .when('/', {
        controller: 'MainController',
        templateUrl: 'views/main.html'
    })
    .when('/about', {
        controller: 'AboutController',
        templateUrl: 'views/about.html'
    })
    .otherwise({
        redirectTo: '/'
    });

});

> AboutController.js

app.controller('AboutController', ['$scope', function($scope) {

}]);

> MainController.js

app.controller('MainController', ['$scope', function($scope) {

    $scope.mapCenter = {
        lat: 40.741934,
        lng: -74.004897,
        zoom: 17
    };

}]);

如何从第三方服务动态获取lat和lon?例如,从JSON IP API开始

我听说可以通过某种方式获取JSON数据

app.factory('latlon', ['$http', function($http) {
    return $http.get('http://ip-api.com/json')
        .success(function(data) {
            return data;
        })
        .error(function(err) {
            return err;
        });
}]);

但我不知道该怎么做以及如何在我的情况下使用它.
你能帮我解决这个问题吗?

解决了

问题解决了

MainController.js

app.controller('MainController', ['$scope', '$http', function($scope, $http) {
    $scope.mapCenter = {};
    $http.get('http://ip-api.com/json')
        .success(function(data) {

            $scope.mapCenter.lat = data.lat;
            $scope.mapCenter.lng = data.lon;
            $scope.mapCenter.zoom = 17;

        });
}]);

最佳答案 不太清楚’我怎样才能确保数据(Lat和Lon)是动态的’,你可以使用 HTML5 geolocation函数:navigator.geolocation.getCurrentPosition(success [,error [,options]])

您应该将其抽象为单独的服务或工厂,以使其更具可重用性并避免依赖于窗口

angular.module('app', []).factory('GeolocationService', ['$q', '$window', function ($q, $window) {

    function getPosition() {
      var deferred = $q.defer();

      if (!$window.navigator.geolocation) { // check if geolocation is supported
        deferred.reject('Geolocation is not supported.');
        return;
    }

    $window.navigator.geolocation.getCurrentPosition( // get the current position 
        function (position) { // ok
            deferred.resolve(position);
        },
        function (err) { // error
            deferred.reject(err);
        });

    return deferred.promise; // returned as a promise
  }

  return {
    getCurrentPosition: getCurrentPosition
  };
}]);

然后你可以从你的控制器这样调用它

geolocationSvc.getPosition().then(
   function success(position){
     $scope.mapCenter = {
      lat: pos.coords.latitude,
      lng: pos.coords.longitude,
      zoom: 17      
}, 
function error(err){
  console.log('ERROR(' + err.code + '): ' + err.message);
});

请注意,此代码尚未经过实际测试,但应为您提供如何实现此代码的概述.

点赞