I have been working on a geolocation and reverse geocoding application. I have a function that is triggered by a button click to call a function in my controller which then calls my service. While the service is able to retrieve values, I am unable to get it to return the value back to my controller.
Previously, I faced some challenges with promises and returns, and although I managed to solve some of them, not all have been resolved. Any help or guidance would be greatly appreciated.
This is the code for my 'geoService':
(function() {
'use strict';
angular.module('JourneyApp').factory('geoService',
[
'$q',
function($q) {
var geoServiceFactory = {};
function getLocation(location) {
var deferred = $q.defer();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, error);
} else {
console.log("No support for Geolocation");
deferred.reject(false);
}
return deferred.promise;
}
function error(error) {
console.log(error);
}
function showPosition(position) {
var deferred = $q.defer();
var geocoder = new google.maps.Geocoder();
var coords = position.coords;
var latlng = { lat: parseFloat(coords.latitude), lng: parseFloat(coords.longitude) };
geocoder.geocode({ 'location': latlng },
function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
console.log(results);
if (results[0]) {
var formattedAddress = results[0].formatted_address;
console.log(formattedAddress);
deferred.resolve(formattedAddress);
} else {
console.log("No match, sorry");
deferred.reject("Error");
}
} else {
console.log("Error, sorry");
deferred.reject("Error");
}
});
return deferred.promise;
}
geoServiceFactory.getLocation = getLocation;
geoServiceFactory.showPosition = showPosition;
return geoServiceFactory;
}
]);
})();
Now moving on to the controller:
(function() {
'use strict';
angular.module('JourneyApp').controller('tripsController',
[
'tripsService', 'vehicleService', 'geoService', function(tripsService, vehicleService, geoService) {
var vm = this;
// Function to retrieve start location
vm.getStartLocation = function() {
geoService.getLocation().then(function (location) {
vm.trip.startAdress = location;
});
}
// Function to retrieve stop location
vm.getStopLocation = function() {
geoService.getLocation().then(function(location) {
vm.trip.stopAdress = location;
});
}
}
]);
}());
Last but not least, a snippet from my view:
<div class="col-md-2">
<input ng-model="vm.trip.startAdress"/>
</div>
<div class="col-md-2">
<button ng-click="vm.getStartLocation()">Get location</button>
</div>
If you notice any mistakes or have suggestions for improvement, please let me know!