如何使用离子检索经度和纬度?
问题描述:
如何使用Ionic Framework获取经度/纬度?在Android中有时将它作为预期的,有时它不使用给纬度/经度如下:如何使用离子检索经度和纬度?
navigator.geolocation.getCurrentPosition(onSuccess, onError, options);
答
不太清楚你问在这里,但离子不能给你geolocations,科尔多瓦但是可以。如果你想让自己变得容易,你应该看看ngCordova,它是一个cordova插件的角度包装。看看这里:http://ngcordova.com/docs/plugins/geolocation/
答
这是一个例子,如何使用长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选项可用于显示接受的旧位置。它使用毫秒,与超时选项相同。
当我们启动我们的应用程序并打开控制台时,它会记录设备的经度和纬度。当我们的位置发生变化时,纬度和长度值将会改变。
答
您可以使用对URL API的调用返回JSON对象,然后获取经度和纬度。以下示例调用http://freegeoip.net/json/并打印出结果。要访问纬度和经度,您可以使用result.latitude
和result.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>