GoogleMaps v3 domListener not triggering in Angularjs directive when using Phonegap

I have a directive in one of my templates and here is the code for that directive:

appDirectives.directive('map', function() {
  return {
    restrict: 'E',
    scope: {
      onCreate: '&'
    },
    link: function ($scope, $element, $attr) {

      alert("This alert works fine.");

      function initialize() {

        alert("This alert doesn't appear 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
        });

        // Prevent sidebar drag when clicking on the map
        google.maps.event.addDomListener($element[0], 'mousedown', function (e) {
          e.preventDefault();
          return false;
        });

        }, function (error) {
          alert('Error getting location.');
        });
      }

      google.maps.event.addDomListener(window, 'load', initialize());

    }
  }

When I run the app on the browser, everything functions as expected. However, when running on the iOS Simulator, the initialize() function fails to execute.

I attempted this fix (as mentioned here):

google.maps.event.addDomListener(window, 'load', initialize);

But unfortunately, this did not work in either the browser or the simulator.

Any insights into why this might be happening?

Answer №1

Ensuring that cordova is ready before obtaining the current location is crucial. Here is an explanation from the phonegap documentation:

Updated Information:

Here is a way to incorporate deviceReady in an angular manner.

In your api.js file where you store services:

//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 the geoLocation service into your controller:

geolocation.getCurrentPosition(function (position) {

$scope.position = {
coords: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
}
};
});

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

Unexpected Error: Null value prevents accessing 'getElementsByClassName' property in HTML, along with Troubleshooting Inactive Button Behavior in HTML

Can someone identify the error in my HTML code? I keep getting an "Uncaught TypeError: Cannot read property 'getElementsByClassName' of null" error on the second line of the script tag. Additionally, my implemented active header code is not funct ...

Dealing with automatic indentation in the Node.js REPL while pasting content

I'm in search of a general idea on how to tackle the issue at hand. I currently have two REPLs - one for my Scheme based LISP written in JavaScript called LIPS, and another one using node.js with readline. The final problem that requires solving is ad ...

Angular 4 animations are triggering every element on the page

I'm currently working on incorporating an animation trigger for components that are dynamically generated by an *ngFor loop. The goal is to have a button that, when clicked, triggers a method to change the animation state and flip the specific compone ...

how to use AngularJS filter and ng-options to format specific options as bold in a select dropdown

I am currently utilizing AngularJS ng-options to populate specific select elements. I am interested in bolding and disabling certain options. Despite trying to achieve this using the filter along with ng-options, I have been unsuccessful so far. While I ca ...

The integration of cypress-cucumber-preprocessor with multiple testing frameworks appears to be experiencing compatibility issues

I am trying to set up a connection between Cypress and Cucumber, and I came across this plugin: https://www.npmjs.com/package/cypress-cucumber-preprocessor However, I am having trouble with my implementation as it seems to be missing. I have also added th ...

Would you suggest using angularjs for authentication in large-scale applications?

As I continue to learn and utilize the AngularJS framework, I have noticed that while some of its features are impressive, some key aspects make it challenging for authentication-based applications. For example, let's consider a scenario where a webs ...

creating a spherical image mapping with three.js

I am currently facing a challenge in UV mapping a cube-map texture onto a sphere. The process of mapping a cube-map onto a cube was straightforward for me. I successfully mapped an image onto a cube using the following steps: Click here to open the image ...

What is the best way to retrieve a value from within the callback function while working in the global scope

While working with express Js, I encountered a situation where I needed to export the port on which the server is running for testing purposes. However, I found that the port value is only accessible within the callback function of app.listen. Is there a ...

Issue with displaying checkboxes in the dataTable table

I am currently working with dataTables and encountering difficulties displaying checkboxes on my tables. Below is the code that I have: <table id="employeeList" class="table table-sm table-bordered table-hover" cellspacing="0" width="200%"> &l ...

Using Bootstrap datepicker to show dates in Month YYYY format and then sending the data to server as MMYYYY for processing

Utilizing the bootstrap datepicker to select a date has been smooth sailing so far. However, due to certain server limitations, we now need to submit the data in the format "022021" rather than "Feb 2021". How can we achieve this post-formatting and submis ...

Dealing with the challenge of duplicate posts in JqWidgets context menu within a nested grid scenario

I have encountered a double posting issue in the JqWidgets context menu for a nested grid. The event is triggering multiple times (where "n" is the number of times I clicked the context menu). In addition, if I place the event handler method outside the c ...

Dealing with Android Woes: Troubleshooting POST Requests using $.ajax with PhoneGap 2.6 and Zepto.js

Currently, I am working on a PhoneGap application that needs to send a POST request to a Django server. Unfortunately, instead of receiving the expected JSON object with a 401 (unauthorized) response, we are getting a 200 message with no data. Here is a s ...

What is the specific functionality of $find in the Microsoft Ajax library?

I'm feeling a bit puzzled about the functionality of $find from Microsoft Ajax. Does it simply retrieve a control like the $ operator in jQuery or JavaScript's getElementById? For example: $find('someControlId') Would this return th ...

Exploring the ins and outs of troubleshooting Nodewebkit using Webstorm

Attempting to open a NW in Webstorm for debugging purposes, but encountering an issue. When there is an error in the app, the NW window simply closes without providing any indication of what went wrong. Stumbled upon this helpful article on the Webstorm w ...

Performing numerous AJAX calls to a PHP server from a single client

I am facing a challenge with my app that sends multiple requests to PHP via jQuery.post, each with different parameters. These requests are for data from the eBay API and take 1-3 seconds to complete. The issue arises when these requests are sent out in qu ...

Leveraging .intersect/.intersectsBox to handle object collisions in threeJS

Currently, I am developing a simple breakout/arkanoid game using threeJS. The game features a paddle and a bouncing ball on the screen. My main focus right now is to make the collision detection work correctly so that when the ball hits the paddle, it boun ...

I'm having trouble figuring out why my Vue method isn't successfully deleting a Firebase object. Can anyone offer some guidance

What I am trying to achieve: I have been struggling to use the remove method from Firebase. I have read the documentation, but for some reason, it is not working as expected. Retrieving data using snapshot works fine, but when I try to delete using the re ...

What is the procedure to obtain a session object on the server side in next.js version 14?

I am currently utilizing version 14 of next.js with its app routing feature and NextAuth. My goal is to secure the API, however, I encounter a null object when using the getServerSession( authOptions ) method while attempting to access a protected endpoin ...

Fetching database entries upon page load instead of using the keyup function in JavaScript

Here is an HTML form input provided: <input type="text" id="username" value=""> In this scenario, when a username like "John" is entered and the enter button is pressed, the script below retrieves database records: $(function(){ //var socket = ...

Instead of sending a post request, sending an options request after the ajax request is made

Currently, I am initiating a post ajax request: var responsehttpreq = {} function createAndSendXmlHttpReq(){ requestBody = { hostname: "prova", pathname: "prova", query: "prova", method: "prova" } console.log("F ...