Troubles with displaying Google Maps on Ionic Modal

Having trouble displaying the google map in an ionic modal - it shows up fine on the page but not in the modal. Any help would be greatly appreciated, as this is quite frustrating. Below is my controller js and code for the ionic modal.

$ionicModal.fromTemplateUrl('templates/mapmodal.html', {
          scope: $scope,
          animation: 'slide-in-up'
        }).then(function(modal) {
          $scope.modal4 = modal;
        });

      $scope.openmapModal = function()
      {
          
         $scope.modal4.show();
      };

      $scope.closemapModal = function() { 
        $scope.modal4.hide();
      };     

 var posOptions = {
            enableHighAccuracy: true,
            timeout: 20000,
            maximumAge: 0
        };
        
$cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
            var lat  = position.coords.latitude;
            var long = position.coords.longitude;
            console.log(lat); 
            console.log(long); 
            $ionicLoading.hide();
            $scope.openmapModal();    
            //var jus = document.getElementById('map');
//            var map;
            $scope.initMap = function() {
                var myLatlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                console.log('entered map');
                var myOptions = {
                    zoom: 16,
                    center: myLatlng,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                $scope.map = new google.maps.Map(document.getElementById("map"), myOptions);

                var marker = new google.maps.Marker({
                    draggable: true,
                    position: myLatlng,
                    map: $scope.map,
                    title: "Your location"
                });

                google.maps.event.addListener(marker, 'dragend', function (event) {

                    document.getElementById("lat").value = event.latLng.lat();
                    document.getElementById("long").value = event.latLng.lng();
                });
            }
            google.maps.event.addDomListener(window, "load", $scope.initMap());
            
            });
<ion-modal-view >
  <ion-header-bar align-title="center" class="common-header">
    <h1 class="title">Add address</h1>
     <button class="button button-icon icon ion-close" ng-click="modal4.hide();"></button>    
  </ion-header-bar>
  <ion-content>
    <div id="map" data-tap-disabled="true"></div>
  </ion-content>
  <ion-footer-bar class="bar-dark">
      <a ng-click="centerOnMe()" class="button button-icon icon ion-navigate">Find Me</a>
  </ion-footer-bar>
</ion-modal-view>

Answer №1

One potential issue could be that the function

$cordovaGeolocation.getCurrentPosition(posOptions).then
is being executed before the HTML template templates/mapmodal.html has finished loading. This may result in the elements not being found when trying to retrieve them using document.getElementById. To resolve this, try calling the code after the HTML has fully loaded. Additionally, consider adding a timeout to ensure that the modal is displayed before initializing the map (you could also listen for the modal.shown event).

$ionicModal.fromTemplateUrl('templates/mapmodal.html', {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.modal4 = modal;
      $scope.openmapModal();
      setTimeout(function(){//here!
          getPositionAndShowOnMap(); 
      }, 500);
    });

  $scope.openmapModal = function()
  {
     $scope.modal4.show();
  };

  $scope.closemapModal = function() { 
    $scope.modal4.hide();
  };     

function getPositionAndShowOnMap(){
    var posOptions = {
        enableHighAccuracy: true,
        timeout: 20000,
        maximumAge: 0
    };

    $cordovaGeolocation.getCurrentPosition(posOptions).then(function (position) {
        var lat  = position.coords.latitude;
        var long = position.coords.longitude;
        console.log(lat);
        console.log(long);
        $ionicLoading.hide();
        $scope.initMap = function() {
            var myLatlng = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
            console.log('entered map');
            var myOptions = {
                zoom: 16,
                center: myLatlng,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };
            $scope.map = new google.maps.Map(document.getElementById("map"), myOptions);

            var marker = new google.maps.Marker({
                draggable: true,
                position: myLatlng,
                map: $scope.map,
                title: "Your location"
            });

            google.maps.event.addListener(marker, 'dragend', function (event) {


                document.getElementById("lat").value = event.latLng.lat();
                document.getElementById("long").value = event.latLng.lng();
            });
        };
        $scope.initMap();
    });
}

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

The jade files are not being detected by gulp.watch()

Out of the blue, my gulpfile.js's watch statement for all of my jade files decided to stop functioning. Any idea why this might be? The Jade task is set up as follows: gulp.task('jade', function() { gulp.src('app/*.jade') . ...

Updating Vue.js Component Data

I have set up a basic Example Component which is bound to a Vue Instance as shown below: <template> <div class="container-fluid"> <div class="row"> <div class="col-md-8 col-md-offset-2"> < ...

Obtain environment variables within a Strapi plugin

I am currently working on developing a Strapi local plugin, but I am facing an issue with retrieving variables defined in my .env file located at the root of my project. Specifically, I am trying to access this value within my React component (plugins/myPl ...

The Angular router seems to be refusing to show my component

My Angular 2 App includes a Module called InformationPagesModule that contains two lazy load components (Info1 Component and Info2 Component). I would like these components to load when accessing the following routes in the browser: http://localhost:4200/ ...

What is the optimal strategy for managing multilingual text in a React website?

As I develop a react website with multiple localizations, I am faced with the question of how to best store UI texts for different languages. Currently, I am contemplating two approaches: One option is to store text directly in the UI code, using an objec ...

Employing distinct techniques for a union-typed variable in TypeScript

I'm currently in the process of converting a JavaScript library to TypeScript. One issue I've encountered is with a variable that can be either a boolean or an array. This variable cannot be separated into two different variables because it&apos ...

Synk: the presence of a self-signed certificate within the certificate chain

Recently, I've been encountering the error message Synk Protect is showing "self-signed certificate in certificate chain" when I try to run npm install on a project of mine. Would appreciate any help or tips on how to identify which out of the 984 pac ...

npm's protocol for handling callback errors

While exploring the coding style guidelines by npm, I stumbled upon a rather enigmatic suggestion: Be very careful never to ever ever throw anything. It’s worse than useless. Just send the error message back as the first argument to the callback. Thi ...

What is the process for transmitting information via a Link in Next.js?

In my upcoming 13.1.5 version, I am faced with a challenge of sending the value of contact.name through a Link in my component. I am looking for the most effective approach to achieve this. The initial code block for the Link represents my original code. ...

Vuetify: Utilizing Time Range Inputs for Start and End Time

I am encountering some difficulty in identifying what I may have missed. I am dealing with 2 inputs: time, startTime, and endTime startTime <v-col cols="12" sm="6" md="2"> <v-menu ref="menu" ...

Tallying the Number of Accordion Toggle Clicks

Let me present a scenario where I have some accordions and would like to keep track of how many times the user expands each one. Could you guide me on how to implement this particular feature? Appreciate your support, Kevin ...

Explain the contrast between specifying a function name in the onclick react event versus invoking it using a callback

Can someone explain the distinction between these two React statements? <Button onClick={this.Callme}></Button> <Button onClick={()=>this.Callme()}></Button> Is it merely a syntax difference or is there an impact on functional ...

The perfect combination: Symfony2 and AngularJS working together

Currently, I have been working on a web app that utilizes Symfony2 and recently integrated AngularJS. Within this app, there is an input field where users can filter products by name. The issue arises when it comes to querying the database in PHP and passi ...

The EJS view fails to render when called using the fetch API

Within my client-side JavaScript, I have implemented the following function which is executed upon an onclick event: function submitForm(event) { const data = { name, image_url }; console.log(data); fetch('/', { method: &apo ...

encountering an issue while working with Selenium on Google Colab

I'm attempting to perform web scraping with selenium in Google Colab and running into some errors https://i.sstatic.net/egDf7.png The webpage is prompting me to enable JavaScript and disable any ad blockers. I tried enabling JavaScript by adding the ...

Need to import Vue from a JavaScript file

I am relatively new to modern frontend development tools. After installing Nodejs and NPM, I successfully downloaded packages such as "jquery" and everything was working fine. However, when I installed Webpack (version 2) and created a demo configuration f ...

How can I show only the final four digits of an input field using Angular Material and AngularJS?

As a newcomer to Angular Material and Angular JS, I am striving to create an md-input field that displays only the last 4 digits in a masked format, such as "********1234". While my experience is currently limited to using md-input password fields where ...

"Trouble with JavaScript boolean values in if-else conditions - not functioning as expected

While utilizing true/false values and checking if at least one of them is true, I am encountering an issue with the if/else statement not functioning as expected. Here is the code snippet: $scope.checkValues = function (qId) { var airport = $scope.air ...

Exploring the Power of BufferGeometry and Textures in Three.js

I am experiencing an issue where the texture does not show up when I try to load textures on a THREE.BufferGeometry. However, the texture displays correctly when using normal geometry. Could it be that textures are unsupported with BufferGeometry, or am I ...

Strip newline characters from information in AngularJS

What is the recommended approach for detecting and formatting the "\n\n" line breaks within text received from the server before displaying it? Check out this Fiddle: http://jsfiddle.net/nicktest2222/2vYBn/ $scope.data = [{ terms: 'You ...