【问题标题】:How can I retrieve the latitude and longitude using Ionic?如何使用 Ionic 检索纬度和经度?
【发布时间】:2016-12-10 03:14:23
【问题描述】:

如何使用 Ionic 框架获取纬度/经度。在 Android 中,它有时会按预期提供,有时它不会使用以下内容提供纬度/经度:

navigator.geolocation.getCurrentPosition(onSuccess, onError, options);  

【问题讨论】:

    标签: android cordova ionic-framework geolocation navigator


    【解决方案1】:

    您可以调用返回 JSON 对象的 URL API,然后获取纬度和经度。以下示例调用http://freegeoip.net/json/ 并打印出结果。要访问纬度和经度,您可以使用 result.latituderesult.longitude 字段。

    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
        $("button").click(function(){
            $.getJSON("http://freegeoip.net/json/", function(result){
                $.each(result, function(i, field){
                    $("div").append(field + " ");
                });
            });
        });
    });
    </script>
    </head>
    <body>
    
    <button>Get JSON data</button>
    
    <div></div>
    
    </body>
    </html>

    【讨论】:

      【解决方案2】:

      这是一个如何使用https://github.com/apache/cordova-plugin-geolocation获取纬度、经度的示例

      .controller('MyCtrl', function($scope, $cordovaGeolocation) {
         var posOptions = {timeout: 10000, enableHighAccuracy: false};
         $cordovaGeolocation
         .getCurrentPosition(posOptions)
      
         .then(function (position) {
            var lat  = position.coords.latitude
            var long = position.coords.longitude
            console.log(lat + '   ' + long)
         }, function(err) {
            console.log(err)
         });
      
         var watchOptions = {timeout : 3000, enableHighAccuracy: false};
         var watch = $cordovaGeolocation.watchPosition(watchOptions);
      
         watch.then(
            null,
      
            function(err) {
               console.log(err)
            },
      
            function(position) {
               var lat  = position.coords.latitude
               var long = position.coords.longitude
               console.log(lat + '' + long)
            }
         );
      
         watch.clearWatch();
      
      })
      

      您还注意到了 posOptions 和 watchOptions 对象。我们使用超时来调整允许通过的最大时间长度(以毫秒为单位),并且 enableHighAccuracy 设置为 false。可以将其设置为 true 以获得最佳结果,但有时会导致一些错误。还有一个 maximumAge 选项,可用于显示接受旧职位的时间。它使用毫秒,与超时选项相同。

      当我们启动应用并打开控制台时,它会记录设备的纬度和经度。当我们的位置改变时,lat 和 long 值也会改变。

      【讨论】:

        【解决方案3】:

        不太清楚你在这里问什么,但 Ionic 不能给你地理定位,但科尔多瓦可以。如果你想让自己轻松一点,你应该研究一下 ngCordova,它是一个用于 Cordova 插件的角度包装器。看看这里:http://ngcordova.com/docs/plugins/geolocation/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-07
          • 1970-01-01
          • 1970-01-01
          • 2016-04-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多