Unable to obtain return value in AngularJS controller or view

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!

Answer №1

As I noted in my previous comment, the issue lies with the promise created within the getLocation function not being resolved, resulting in the value not being stored. The solution to this problem is to replace the if statement in the getLocation function with the following code:

[...]
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function (position) {
        showPosition(position).then(function(formattedAddress) {
            deferred.resolve(formattedAddress);
        }
    }, error);
} else {
[...]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues arise with routing when specific route parameters are implemented

After setting a route parameter in my browser URL, I encountered errors with the routing of the public folder (which contains my CSS, JS, etc.). The app's structure is as follows: app | |-- public | └-- css | └-- profile.css | |-- ...

Icon: When clicked, initiate a search action

I am looking to make the icon clickable so that it can be used as an alternative to pressing the "return key" for searching. Check out this bootply example at . You simply need to click on the magnifying glass icon and it will initiate the search. ...

Find the mean of two values entered by the user using JavaScript

I'm sorry for asking such a basic question, but I've been struggling to get this code to work for quite some time now. I'm ashamed to admit how long I've spent trying to figure it out and how many related StackOverflow questions I ...

Jest is having trouble recognizing a custom global function during testing, even though it functions properly outside of testing

In my Express app, I have a custom function called foo that is globally scoped. However, when running Jest test scripts, the function is being recognized as undefined, causing any tests that rely on it to fail. This is declared in index.d.ts: declare glob ...

Adding key/value pairs to an array of objects in RxJS Observables can be easily

I currently have an Angular app with state management that retrieves data from a database in observables. Here is an example of the interfaces I am working with: interface Service { id: number, name: string, category_id: number, } interface Category ...

What is the best way to ensure all asynchronous tasks are completed in Node.js before proceeding?

My program is in need of running numerous asynchronous tasks. Additionally, there needs to be a task that will only run once all the other asynchronous tasks have completed. Is there a way I can create a function that waits for all async functions to fin ...

When using angular's ngHide directive on a button, it will still occupy space in the

At the bottom of this HTML file, there are 3 buttons displayed. The first image illustrates the layout of the 3 buttons. The second image demonstrates what happens when the middle button in the footer is commented out. The third image shows the situat ...

Sorting Object Values with Alternate Order

Is there a way to sort a JSON response object array in a specific order, especially when dealing with non-English characters like Umlauts? object { item: 1, users: [ {name: "A", age: "23"}, {name: "B", age: "24"}, {name: "Ä", age: "27"} ] ...

Convert h264 video to GIF using Node.js

Currently, I'm utilizing the "pi-camera" library to successfully record video in a raw h264 format on my Raspberry Pi. However, I am encountering an issue with the node.js library "gifify" which keeps throwing the error "RangeError: Maximum call stack ...

How can I add divs to an HTML page with a Javascript animated background?

I am currently facing an issue with my JavaScript animated background, consisting of just 3 pictures. I am trying to display some Div elements on it with content inside. Here is the code snippet I have right now: In my CSS file, I have defined styles for ...

A guide to placing tooltips dynamically in highcharts column charts

I am encountering an issue with tooltips in Highcharts column charts. The problem arises when the series fill up my chart, causing the tooltip to be hidden below the series and cut off by the end of the div. You can see an example here: https://i.stack.i ...

Integrate a PHP variable into an HTML/JavaScript statement that was previously transformed from PHP

Incorporated within this PHP variable is a mix of HTML and JavaScript code. My task is to enhance it by adding another PHP variable. Specifically, I have a PHP variable denoted as $user->user_email. How can I seamlessly integrate this variable into th ...

Submitting an HTTP POST REQUEST with both an image and text

Is there a way to send an image with text from VueJs to an ExpressJs backend? I've currently implemented two HTTP POST requests for this process. Please note: "this.albumName" and "this.albumDesc" contain text, while the formData variable holds the ...

The modal appears on the screen prior to the content being shown

While attempting to render a bootstrap modal with content from a REST call, I am encountering an issue where the modal appears before the content has finished populating. The modal is triggered by a button click event. If I click the button again after wa ...

Can hash routes be defined in next.js?

Previously, I created a modal component using <HashRouter> in react-router where the modal would become active or inactive based on the hash url. For example, the modal is inactive when the url is /route, but becomes active when the url is /route#m ...

The echo statement is failing to show any value following the ajax request

I am in need of assistance. I would like to output the value from a PHP echo statement using an AJAX call. Currently, the code is functioning without any errors. When I select options from a dropdown menu, the value is displayed on the console by using con ...

What is the best way to instruct the protractor to pause until the webpage has completely loaded

My application is taking some time to load the login page, causing Protractor to attempt entering the username before the page fully loads. To resolve this issue, I need to instruct Protractor to wait until the login page is completely loaded. Can you ass ...

Searching in the Kendo Dropdown List using text and value

$(document).ready(function() { $("#selection").kendoDropDownList({ filter: "startswith", dataTextField: "SelectionName", dataValueField: "SelectionID", dataSour ...

What is the proper method for setting the queryString in react-router-dom?

After using angularJS in my application, I decided to migrate to React. As part of the migration process, I am navigating to a specific route: /index using $urlServiceProvider.rules.otherwise('/index'). It's important to note that I am utili ...

Ajax fails to transfer the complete data

I am currently facing an issue with my request. Here is the code snippet that I need help with: logInWithFacebook = function() { FB.login(function(response) { if (response.authResponse) { FB.api('/me', {fields: 'name,email,location,p ...