问题
I've got a directive in one of my templates, the following is the code of that directive:
appDirectives.directive('map', function() {
return {
restrict: 'E',
scope: {
onCreate: '&'
},
link: function ($scope, $element, $attr) {
alert("This fires just fine.");
function initialize() {
alert("This doesnt fire on Phonegap.");
navigator.geolocation.getCurrentPosition(function (pos) {
$scope.currentLocation = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
var mapOptions = {
center: $scope.currentLocation,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
};
var map = new google.maps.Map($element[0], mapOptions);
var currentLocation = $scope.currentLocation;
$scope.onCreate({
map: map,
currentLocation: currentLocation
});
// Stop the side bar from dragging when mousedown/tapdown on the map
google.maps.event.addDomListener($element[0], 'mousedown', function (e) {
e.preventDefault();
return false;
});
}, function (error) {
alert('Erro ao obter localização.');
});
}
google.maps.event.addDomListener(window, 'load', initialize());
}
}
When running the app on the browser, everything works as expected. But when running on the iOS Simulator, it just doesnt fire the function initialize().
I've tried this (as described here):
google.maps.event.addDomListener(window, 'load', initialize);
Bu then it just fails to work both in the browser and in the simualtor.
Any idea why?
回答1:
You have to make sure that cordova is ready before getting the current location. here is an explanation from phonegap docs
http://docs.phonegap.com/en/1.7.0/cordova_events_events.md.html#deviceready
edited:
here is how you can use deviceReady in angular way
in your api.js where you keep service
//cordova service
apiServices.factory('cordovaReady', function() {
return function (fn) {
var queue = [];
var impl = function () {
queue.push(Array.prototype.slice.call(arguments));
};
document.addEventListener('deviceready', function () {
queue.forEach(function (args) {
fn.apply(this, args);
});
impl = fn;
}, false);
return function () {
return impl.apply(this, arguments);
};
};
});
//map service
apiServices.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);
})
};
});
Then inject geoLocation service in your controller
geolocation.getCurrentPosition(function (position) {
$scope.position = {
coords: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
};
});
来源:https://stackoverflow.com/questions/24071203/phonegap-not-firing-googlemaps-v3-domlistener-function-inside-angularjs-directiv