What is the best way to establish the order of execution in an AngularJS controller?

I have successfully displayed a Google map with markers. However, I am encountering an issue when trying to dynamically set the center of the map's latitude and longitude using a method called coords(). The error message indicates that the center is undefined because the map is being drawn before the function returns or sets the centered latitude and longitude values. As a result, we are getting an undefined error. How can I ensure that the coords() function is executed completely before the map is drawn? On the other hand, I tested by hard coding the latitude value and found that the map was drawn correctly. I also attempted using callbacks but did not achieve the desired results.

Below is my controller code (js) and view (html).

var appa = angular.module('appa',['firebase','uiGmapgoogle-maps']);
appa.controller('mainCtrl', function($firebaseObject,$scope) {

              $scope.coords = function(){
                var ref =  firebase.database().ref();
                var latArray = [];
                var lngArray = [];
                var cenlat;
                var cenlng;
                  var marker = [];
                ref.once("value")
                .then(function(snapshot)
                {
                snapshot.forEach(function(child)
                {

                  latArray.push(child.child("Lat").val());
                  console.log(child.child("Lat").val());
                  lngArray.push(child.child("Long").val());
                  var mark = {
                  id: child.child("Id").val(),
                  coords: {
                  latitude: child.child("Lat").val(),
                  longitude: child.child("Long").val()
                  },
                  options: { title: child.child("Alt").val() }
                  };
                  marker.push(mark);
                });

                   cenlat = (Math.max.apply(Math,latArray)+Math.min.apply(Math,latArray)/2);
                   cenlng = (Math.max.apply(Math,lngArray)+Math.min.apply(Math,lngArray)/2);

                });
                $scope.map.center.latitude = cenlat;
                $scope.map.center.longitude = cenlng;
                };

              $scope.map = {
                center:
                {
                  latitude: 51,
                  longitude: 4
                         },
                 zoom: 2
                      };

                $scope.coords();

   });
<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org/" >

<head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <link rel="stylesheet" href="style.css" />
    <script src="https://code.angularjs.org/1.3.14/angular.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDF-sQ_g7FJ46HeYo8e4dpVukyDkdE5UXw"></script>
    <script src="https://www.gstatic.com/firebasejs/3.6.0/firebase.js"></script>
    <script src="https://cdn.firebase.com/libs/angularfire/2.1.0/angularfire.min.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.js"></script>
    <script src="http://rawgit.com/angular-ui/angular-google-maps/2.0.X/dist/angular-google-maps.js"></script>
    <script type='text/javascript' src='app.js'></script>
    <style type="text/css">
        html, body, #map_canvas {
            height: 100%;
            width: 100%;
            margin: 0px;
        }

        #map_canvas {
            position: relative;
        }

        .angular-google-map-container {
            position: absolute;
            top: 0;
            bottom: 0;
            right: 0;
            left: 0;
        }
    </style>
</head>

<body ng-app="appa">
    <div id="map_canvas" ng-controller="mainCtrl">
    <ui-gmap-google-map center="map.center" zoom="map.zoom">
      <ui-gmap-marker ng-repeat="m in marker" coords="m.coords" options="m.options" idkey="m.id">
           </ui-gmap-marker>
                    </ui-gmap-google-map>
</div>
<!--example-->
</body>

</html>

Answer №1

To simplify the process, one can eliminate the firmly established $scope.map.center by generating it within the $scope.coords function and incorporating ng-if into the HTML:

<ui-gmap-google-map center="map.center" zoom="map.zoom" ng-if="map.center">

As a result, the directive will only be displayed once $scope.map.center is present, typically after the asynchronous completion of $scope.coords.

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

Resetting the randomness in a function within a sudoku generator implemented in JavaScript

I'm in the process of creating a unique Sudoku generator that incorporates randomness into its design. Within my code, there's a particular function responsible for generating the Sudoku puzzles. The issue I'm encountering is the inability t ...

What's the deal with THREE.ImageUtils these days?

Currently in the process of updating outdated JavaScript code using three.js for textures. Specifically looking to improve the second line of code below. var groundColor = new THREE.Color(0xd2ddef); var groundTexture = new THREE.ImageUtils().generateData ...

Having trouble with less.modifyVars not functioning properly in Visual Studio?

I attempted to dynamically change the LESS variable using HTML within an AngularJS function. The code worked fine on XAMPP with simple HTML and CSS, but when I transferred it to an enterprise app in Visual Studio, it stopped functioning properly. While the ...

What is the best way to pass information between Express middleware and endpoints?

Many middleware packages come with factories that accept an options object, which often includes a function to provide necessary information to the middleware. One example of this is express-preconditions: app.use(preconditions({ stateAsync: async (re ...

Choose specific GeoJSON elements using a mouse click - OpenLayers 3

I'm working with GeoJSON features that consist of multiple smaller features. When I hover over one of them, I'm hoping to have the entire layer selected, rather than just a portion of it. I'm not sure where to begin in order to make this ha ...

Default page featuring an AngularJS modal dialog displayed

I am attempting to display a modal popup dialog using an HTML template. However, instead of appearing as a popup dialog, the HTML code is being inserted into the default HTML page. I have included the controller used below. app.controller('sortFiles&a ...

Generating HTML tables with charts using FireFox

I am encountering an issue: My table contains charts and tables that are displayed correctly in browsers. However, when I attempt to print it (as a PDF) in Mozilla Firefox, the third speedometer gets cut off, showing only 2.5 speedometers. Using the "s ...

Working with Vue/Nuxt to loop through a collection of documents in Firestore using v-for

This is my first project using Vue and Firebase. I am working with NuxtJS (Vue v2.x) along with Vuetify and Firestore. My goal is to iterate through a collection of documents and display Vuetify Card components with the relevant data. Currently, all the ...

Managing multiple checkboxes in a Vue component

I have a checkbox component in Vue: <template> <div class="checkbox"> <input class="checkbox-input" name="input" type="checkbox" v-model="checkbox"> </div> </templ ...

What is the method to determine the duration of a video using the FileReader function to access the video file?

My current challenge involves uploading a video to a server and reading it on the client end using `readAsBinaryString()` from FileReader. However, I am facing an issue when trying to determine the duration of this video file. If I attempt to read the fi ...

How does a browser automatically fill in email and password fields?

When using a text input and a password input in my single page app, Chrome often prompts to remember the information for autofill. However, I am encountering an issue where it doesn't actually autofill the information. Does anyone know how to trouble ...

"Utilizing the power of Node.js to perform SQL queries with

I'm having trouble with this SQL query that uses INNER JOIN. The query is returning an error. connection.query("SELECT caracavis.caracname FROM caracavis WHERE firstcaturl ='" + req.body[0].firstcatname + "' AND secondcaturl = '" + r ...

Looping through an array in Angular with ng-repeat

In my controller, I have managed to loop through the primary xml-based data successfully. However, I am facing challenges in passing the secondary child data (in the second level tr tag where I want all "list" categories to repeat) within the loop. angula ...

"Bringing in a Nunjucks Macro - How to Easily Use It

I've been working on a script that renders a nunjucks contact.html template with the following code: let fs = require('fs'); let nj = require('nunjucks'); var contact = fs.readFileSync('./src/contact.html',&a ...

Tips for transmitting binary information to an API using AngularJS

I am attempting to send binary image data to an API endpoint. The API currently accepts a URL as input, and that works perfectly fine. Now, I want to send binary image data from an HTML canvas. You can refer to the API documentation for more details on th ...

How to use jQuery to dynamically add a variable to a request in Laravel 5.2

Is it feasible to append a variable to the Laravel cookie in the client using jQuery? Understandably, the Cookie is linked to the request during GET? Can you include a variable in the $request container in Laravel 5.2 using jQuery before initiating a GET ...

Incorporating a variety of functions into an external javascript file

I am currently working on enhancing the functionality of a basic HTML page by incorporating JavaScript with multiple buttons. The problem arises when I attempt to introduce another function in my external JS file, as it causes the existing code to stop wor ...

`There seems to be an issue with multiple markers not appearing on Google Maps when using AngularJS.`

.controller('homeCtrl', function($scope, Markers) { var username = window.localStorage.getItem('username'); var id_user = window.localStorage.getItem('id_user'); console.log(username); console.log(id_user); document.getElement ...

Can a constructor function be utilized as a parameter type in another function within TypeScript?

Recently, I came across TypeScript and after watching some video reviews, I see great potential in it. It seems to offer better code completion, implicit code documentation, and enhanced type safety for JavaScript. I'm currently in the process of con ...

Animation of disappearing blocks covering the entire screen

I am currently working on creating a slider with fading blocks animation similar to the one shown here. The challenge I am facing is making it fullscreen, where the height and width will be variable. This makes using the background-position trick ineffecti ...