NativeScript - 地理定位:使用 getCurrentLocation promise 函数的正确方法
NativeScript - Geolocation: right way to use getCurrentLocation promise function
我正在编写一个使用 nativescript-geolocation
API 的简单应用程序。
函数 getCurrentLocation 基本上工作正常,但是当我移动到另一个名为 maps-module.js
的文件并从文件 detail.js
的主线程调用它时,它的对象位置 return 为 NULL。
打印控制台对象后,我意识到变量 returned_location 在函数完成查找位置之前被 returned。
我认为这是多线程问题,但我真的不知道如何解决。
这是我的文件。
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;
由于获取位置是一个异步过程,因此您的 viewModel.getCurrentPosition 应该 return 一个承诺,并且看起来像这样,
viewModel.getCurrentPosition() {
return new Promise((resolve, reject) => {
geolocation
.getCurrentLocation({
desiredAccuracy: enums.Accuracy.high,
updateDistance: 0.1,
maximumAge: 5000,
timeout: 20000
})
.then(r => {
resolve(r);
})
.catch(e => {
reject(e);
});
});
}
然后当你使用它时,它看起来像这样
defaultMapInfo.getCurrentPosition()
.then(latlng => {
// do something with latlng {latitude: 12.34, longitude: 56.78}
}.catch(error => {
// couldn't get location
}
}
希望对您有所帮助 :)
更新:顺便说一句,geolocation.enableLocationRequest() 也是一种异步方法。
如果湿婆普拉萨德的脚注...
"geolocation.enableLocationRequest() is also an asynchorous method"
... 是正确的,那么由 geolocation.enableLocationRequest()
编辑的 Promise return 必须适当地处理并且代码将发生相当大的变化。
试试这个:
viewModel.getCurrentPosition = function(options) {
var settings = Object.assign({
'desiredAccuracy': 3,
'updateDistance': 10,
'maximumAge': 20000,
'timeout': 20000
}, options || {});
var p = Promise.resolve() // Start promise chain with a resolved native Promise.
.then(function() {
if (!Geolocation.isEnabled()) {
return Geolocation.enableLocationRequest(); // return a Promise
} else {
// No need to return anything here.
// `undefined` will suffice at next step in the chain.
}
})
.then(function() {
if (Geolocation.isEnabled()) {
return Geolocation.getCurrentLocation(settings); // return a Promise
} else { // <<< necessary to handle case where Geolocation didn't enable.
throw new Error('Geolocation could not be enabled');
}
})
.then(function(loc) {
if (loc) {
console.log("Current location is: " + loc.latitude + ", " + loc.longitude);
return Gmap.Position.positionFromLatLng(loc.latitude, loc.longitude);
} else { // <<< necessary to handle case where loc was not derived.
throw new Error('Geolocation enabled, but failed to derive current location');
}
})
.catch(function(e) {
console.error(e);
throw e; // Rethrow the error otherwise it is considered caught and the promise chain will continue down its success path.
// Alternatively, return a manually-coded default `loc` object.
});
// Now race `p` against a timeout in case enableLocationRequest() hangs.
return Promise.race(p, new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error('viewModel.getCurrentPosition() timed out'));
}, settings.timeout);
}));
}
return viewModel;
备注:
使用已解析的本机 Promise 启动链与包装在 new Promise(...)
中的效果大致相同,但更清晰,主要是因为链中的意外抛出保证会传递一个 Error 对象链的错误路径而不需要 try/catch/reject()
。此外,在标记为 "return a Promise" 的两行中,我们不需要关心 return 是一个 Promise 还是一个值;两者都会被原生的 Promise 链同化。
包含两个 else
子句以应对不会自动抛出的失败情况。
Promise.race()
不是必需的,但它是针对报告的问题 here 的保障措施。内置的 'timeout' 机制可能就足够了。这种额外的超时机制是一项 "belt-and-braces" 措施。
包含一种机制,通过传递 options
对象来覆盖 viewModel.getCurrentPosition
中的硬编码默认值。要使用默认值 运行,只需调用 viewModel.getCurrentPosition()
。引入此功能主要是为了允许 settings.timeout
在 Promise.race()
.
中重复使用
编辑:
感谢@grantwparks 提供 Geolocation.isEnabled()
也 return 承诺的信息。
所以现在我们可以用 p = Geolocation.isEnabled()....
启动 Promise 链并测试异步传递的布尔值。如果 false
则尝试启用。
从那时起,如果地理定位最初已启用或已启用,则将遵循 Promise 链的成功路径。启用地理定位的进一步测试消失了。
这应该有效:
viewModel.getCurrentPosition = function(options) {
var settings = Object.assign({
'desiredAccuracy': 3,
'updateDistance': 10,
'maximumAge': 20000,
'timeout': 20000
}, options || {});
var p = Geolocation.isEnabled() // returned Promise resolves to true|false.
.then(function(isEnabled) {
if (isEnabled) {
// No need to return anything here.
// `undefined` will suffice at next step in the chain.
} else {
return Geolocation.enableLocationRequest(); // returned Promise will cause main chain to follow success path if Geolocation.enableLocationRequest() was successful, or error path if it failed;
}
})
.then(function() {
return Geolocation.getCurrentLocation(settings); // return Promise
})
.then(function(loc) {
if (loc) {
console.log("Current location is: " + loc.latitude + ", " + loc.longitude);
return Gmap.Position.positionFromLatLng(loc.latitude, loc.longitude);
} else { // <<< necessary to handle case where loc was not derived.
throw new Error('Geolocation enabled, but failed to derive current location');
}
})
.catch(function(e) {
console.error(e);
throw e; // Rethrow the error otherwise it is considered caught and the promise chain will continue down its success path.
// Alternatively, return a manually-coded default `loc` object.
});
// Now race `p` against a timeout in case Geolocation.isEnabled() or Geolocation.enableLocationRequest() hangs.
return Promise.race(p, new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error('viewModel.getCurrentPosition() timed out'));
}, settings.timeout);
}));
}
return viewModel;
我正在编写一个使用 nativescript-geolocation
API 的简单应用程序。
函数 getCurrentLocation 基本上工作正常,但是当我移动到另一个名为 maps-module.js
的文件并从文件 detail.js
的主线程调用它时,它的对象位置 return 为 NULL。
打印控制台对象后,我意识到变量 returned_location 在函数完成查找位置之前被 returned。
我认为这是多线程问题,但我真的不知道如何解决。
这是我的文件。
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;
由于获取位置是一个异步过程,因此您的 viewModel.getCurrentPosition 应该 return 一个承诺,并且看起来像这样,
viewModel.getCurrentPosition() {
return new Promise((resolve, reject) => {
geolocation
.getCurrentLocation({
desiredAccuracy: enums.Accuracy.high,
updateDistance: 0.1,
maximumAge: 5000,
timeout: 20000
})
.then(r => {
resolve(r);
})
.catch(e => {
reject(e);
});
});
}
然后当你使用它时,它看起来像这样
defaultMapInfo.getCurrentPosition()
.then(latlng => {
// do something with latlng {latitude: 12.34, longitude: 56.78}
}.catch(error => {
// couldn't get location
}
}
希望对您有所帮助 :)
更新:顺便说一句,geolocation.enableLocationRequest() 也是一种异步方法。
如果湿婆普拉萨德的脚注...
"geolocation.enableLocationRequest() is also an asynchorous method"
... 是正确的,那么由 geolocation.enableLocationRequest()
编辑的 Promise return 必须适当地处理并且代码将发生相当大的变化。
试试这个:
viewModel.getCurrentPosition = function(options) {
var settings = Object.assign({
'desiredAccuracy': 3,
'updateDistance': 10,
'maximumAge': 20000,
'timeout': 20000
}, options || {});
var p = Promise.resolve() // Start promise chain with a resolved native Promise.
.then(function() {
if (!Geolocation.isEnabled()) {
return Geolocation.enableLocationRequest(); // return a Promise
} else {
// No need to return anything here.
// `undefined` will suffice at next step in the chain.
}
})
.then(function() {
if (Geolocation.isEnabled()) {
return Geolocation.getCurrentLocation(settings); // return a Promise
} else { // <<< necessary to handle case where Geolocation didn't enable.
throw new Error('Geolocation could not be enabled');
}
})
.then(function(loc) {
if (loc) {
console.log("Current location is: " + loc.latitude + ", " + loc.longitude);
return Gmap.Position.positionFromLatLng(loc.latitude, loc.longitude);
} else { // <<< necessary to handle case where loc was not derived.
throw new Error('Geolocation enabled, but failed to derive current location');
}
})
.catch(function(e) {
console.error(e);
throw e; // Rethrow the error otherwise it is considered caught and the promise chain will continue down its success path.
// Alternatively, return a manually-coded default `loc` object.
});
// Now race `p` against a timeout in case enableLocationRequest() hangs.
return Promise.race(p, new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error('viewModel.getCurrentPosition() timed out'));
}, settings.timeout);
}));
}
return viewModel;
备注:
使用已解析的本机 Promise 启动链与包装在
new Promise(...)
中的效果大致相同,但更清晰,主要是因为链中的意外抛出保证会传递一个 Error 对象链的错误路径而不需要try/catch/reject()
。此外,在标记为 "return a Promise" 的两行中,我们不需要关心 return 是一个 Promise 还是一个值;两者都会被原生的 Promise 链同化。包含两个
else
子句以应对不会自动抛出的失败情况。Promise.race()
不是必需的,但它是针对报告的问题 here 的保障措施。内置的 'timeout' 机制可能就足够了。这种额外的超时机制是一项 "belt-and-braces" 措施。包含一种机制,通过传递
options
对象来覆盖viewModel.getCurrentPosition
中的硬编码默认值。要使用默认值 运行,只需调用viewModel.getCurrentPosition()
。引入此功能主要是为了允许settings.timeout
在Promise.race()
. 中重复使用
编辑:
感谢@grantwparks 提供 Geolocation.isEnabled()
也 return 承诺的信息。
所以现在我们可以用 p = Geolocation.isEnabled()....
启动 Promise 链并测试异步传递的布尔值。如果 false
则尝试启用。
从那时起,如果地理定位最初已启用或已启用,则将遵循 Promise 链的成功路径。启用地理定位的进一步测试消失了。
这应该有效:
viewModel.getCurrentPosition = function(options) {
var settings = Object.assign({
'desiredAccuracy': 3,
'updateDistance': 10,
'maximumAge': 20000,
'timeout': 20000
}, options || {});
var p = Geolocation.isEnabled() // returned Promise resolves to true|false.
.then(function(isEnabled) {
if (isEnabled) {
// No need to return anything here.
// `undefined` will suffice at next step in the chain.
} else {
return Geolocation.enableLocationRequest(); // returned Promise will cause main chain to follow success path if Geolocation.enableLocationRequest() was successful, or error path if it failed;
}
})
.then(function() {
return Geolocation.getCurrentLocation(settings); // return Promise
})
.then(function(loc) {
if (loc) {
console.log("Current location is: " + loc.latitude + ", " + loc.longitude);
return Gmap.Position.positionFromLatLng(loc.latitude, loc.longitude);
} else { // <<< necessary to handle case where loc was not derived.
throw new Error('Geolocation enabled, but failed to derive current location');
}
})
.catch(function(e) {
console.error(e);
throw e; // Rethrow the error otherwise it is considered caught and the promise chain will continue down its success path.
// Alternatively, return a manually-coded default `loc` object.
});
// Now race `p` against a timeout in case Geolocation.isEnabled() or Geolocation.enableLocationRequest() hangs.
return Promise.race(p, new Promise(function(resolve, reject) {
setTimeout(function() {
reject(new Error('viewModel.getCurrentPosition() timed out'));
}, settings.timeout);
}));
}
return viewModel;