我正在使用带有phonegap的angular.js。为了获得用户的GPS位置,我开发了一个简单的服务:
app.factory('geolocation', function ($rootScope, cordovaReady) {
return {
getCurrentPosition: cordovaReady(function (onSuccess, onError, options) {
navigator.geolocation.getCurrentPosition(function () {
var that = this,
args = arguments;
if (onSuccess) {
$rootScope.$apply(function () {
onSuccess.apply(that, args);
});
}
}, function () {
var that = this,
args = arguments;
if (onError) {
$rootScope.$apply(function () {
onError.apply(that, args);
});
}
}, options);
});
}
});
我将此服务称为
geolocation.getCurrentPosition(function (position) {
console.log(position);
});
现在我想用另一个名为 getCurrentCity 的方法扩展服务。此方法应使用 getCurrentPosition 来确定城市。所以服务看起来像这样:
app.factory('geolocation', function ($rootScope, cordovaReady) {
return {
getCurrentPosition: ....
getCurrentCity: ...
}
});
这可能吗?我应该如何使用getCurrentPosition实现getCurrentCity?
答案 0 :(得分:1)
如果我在这里回答错误的问题,请原谅我,但如果您只是询问如何从服务中回复多种方法,那么这很简单:
angular.module('app', []).factory('geolocation', function ($rootScope, cordovaReady) {
var locationObj = {
getCurrentPosition: cordovaReady(function (onSuccess, onError, options) {
navigator.geolocation.getCurrentPosition(function () {
var that = this,
args = arguments;
if (onSuccess) {
$rootScope.$apply(function () {
onSuccess.apply(that, args);
});
}
}, function () {
var that = this,
args = arguments;
if (onError) {
$rootScope.$apply(function () {
onError.apply(that, args);
});
}
}, options);
}),
getCurrentCity: function() {
this.getCurrentPosition(function(position){
//determine city
var city = ...
//how to apply city to scope?
});
}
}
return locationObj;
});
如果您要询问特定于手机屏幕的问题,请忽略!