我正在編寫一個使用nativescript-geolocation
API的簡單應用程序。 函數getCurrentLocation基本上可以正常工作,但是當我移動到另一個名爲maps-module.js
的文件並從文件detail.js
的主線程調用它時,它返回的對象位置爲NULL。 打印後控制對象,我意識到變量returned_location是在函數完成查找位置之前返回的。 我認爲它的多線程問題,但我真的不知道如何解決它。 這是我的文件。NativeScript - 地理位置:使用getCurrentLocation承諾函數的正確方法
detail.js
var Frame = require("ui/frame");
var Observable = require("data/observable");
var MapsModel = require("../../view-models/maps-model");
var defaultMapInfo = new MapsModel({
latitude: "10.7743332",
longitude: "106.6345204",
zoom: "0",
bearing: "0",
tilt: "0",
padding: "0"
});
var page;
var mapView;
exports.pageLoaded = function(args) {
page = args.object;
var data = page.navigationContext;
page.bindingContext = defaultMapInfo;
}
exports.onBackTap = function() {
console.log("Back to home");
var topmost = Frame.topmost();
topmost.goBack();
}
function onMapReady(args) {
mapView = args.object;
mapView.settings.zoomGesturesEnabled = true;
}
function onMarkerSelect(args) {
console.log("Clicked on " + args.marker.title);
}
function onCameraChanged(args) {
console.log("Camera changed: " + JSON.stringify(args.camera));
}
function getCurPos(args) {
var returned_location = defaultMapInfo.getCurrentPosition(); // variable is returned before function finished
console.dir(returned_location);
}
exports.onMapReady = onMapReady;
exports.onMarkerSelect = onMarkerSelect;
exports.onCameraChanged = onCameraChanged;
exports.getCurPos = getCurPos;
地圖 - module.js
var Observable = require("data/observable");
var Geolocation = require("nativescript-geolocation");
var Gmap = require("nativescript-google-maps-sdk");
function Map(info) {
info = info || {};
var _currentPosition;
var viewModel = new Observable.fromObject({
latitude: info.latitude || "",
longitude: info.longitude || "",
zoom: info.zoom || "",
bearing: info.bearing || "",
tilt: info.bearing || "",
padding: info.padding || "",
});
viewModel.getCurrentPosition = function() {
if (!Geolocation.isEnabled()) {
Geolocation.enableLocationRequest();
}
if (Geolocation.isEnabled()) {
var location = Geolocation.getCurrentLocation({
desiredAccuracy: 3,
updateDistance: 10,
maximumAge: 20000,
timeout: 20000
})
.then(function(loc) {
if (loc) {
console.log("Current location is: " + loc["latitude"] + ", " + loc["longitude"]);
return Gmap.Position.positionFromLatLng(loc["latitude"], loc["longitude"]);
}
}, function(e){
console.log("Error: " + e.message);
});
if (location)
console.dir(location);
}
}
return viewModel;
}
module.exports = Map;
這就是我要找的,我的代碼現在非常簡單,謝謝XD – Sea