Is the Google Maps Javascript API compatible with Ionic 2?

Hi everyone, I hope you're all doing well :)

In my development of a basic application using Ionic Framework with Google Maps (Map + Places SearchBox), everything is working smoothly until I encounter an issue when trying to search for an address (e.g. Morena Blvd #1, San Diego, CA). The input displays the suggested addresses, but when I select one, it doesn't populate completely in my <ion-input> element...

The functionality works perfectly fine in my browser when running the app with ionic serve, but the problem arises on my iPhone or Android device. Has anyone faced a similar challenge before?

Below is the frontend code snippet:

<ion-content no-padding>
  <ion-searchbar #searchAddress id="searchAddress" [showCancelButton]="false" [(ngModel)]="address">
</ion-searchbar>

Additionally, this is how I'm setting the SearchBox instance for the inner input control of my ion-searchbar...

@ViewChild('searchAddress', {read: ElementRef}) searchElement: ElementRef;
...
...
...
...
let input = this.searchElement.nativeElement.querySelector('.searchbar-input');
let searchBox = new google.maps.places.SearchBox(input);

searchBox.addListener('places_changed', () => {
  let places = searchBox.getPlaces();

  if(!places && places.length === 0) return;

  this.address = places[0].formatted_address;
  this.latitude = places[0].geometry.location.lat();
  this.longitude = places[0].geometry.location.lng();

  if(places[0].address_components.length === 0) {
    this.street = places[0].address_components[1].long_name;
    this.selectedEstate = places[0].address_components[4].long_name;
  }
});

Lastly, this code runs within my ionViewDidEnter() event.

Answer №1

Consider encapsulating your listener code within an NgZone wrapper:

import { NgZone } from '@angular/core';

export class myPage {
  zone: NgZone;

  constructor() {
    this.zone = new NgZone({enableLongStackTrace: false});
  }

  ...

    searchBox.addListener('places_changed', () => {
      this.zone.run(() => {
        let places = searchBox.getPlaces();

        if(!places && places.length === 0) return;

        this.address = places[0].formatted_address;
        this.latitude = places[0].geometry.location.lat();
        this.longitude = places[0].geometry.location.lng();

        if(places[0].address_components.length === 0) {
          this.street = places[0].address_components[1].long_name;
          this.selectedEstate = places[0].address_components[4].long_name;
        }
      });
    });
}

If successful, it indicates that your listener callback is being executed outside the Angular context, leading to a lack of change detection and updates. I encountered a similar issue in the past (specifically on mobile devices), suggesting potential performance or optimization factors affecting battery life.

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

Tips for successfully importing mock data for testing without running into reference problems when reusing the same mocked object or array multiple times

Trying to run tests for Angular has presented a challenge. I have intricate objects, nested within other objects, stored in a separate file along with my mocked data. Each mocked object is linked to an export in the data file specifically created for mock ...

The challenge of injecting services into Jest test cases using Angular 17 Functional Resolver

Overview Greetings, I am currently in the process of updating my Angular application from version 14 to version 17. One of the tasks involved in this update is replacing the deprecated Resolver classes with the new ResolverFn implementation. The challen ...

Unable to retrieve POST parameters using Node.js and Express

I'm currently experimenting with a basic example of a Node.js + Express RESTful API. One action I've set up is to simulate a login request. Below is the code snippet: app.js var express = require('express'); var path = require('p ...

Ways to identify the current configuration of ckeditor in use

I've created a custom CKEditor plugin with a unique dialog box setup. To include the dialog, I use the following code: var customize_dialog = this.path + 'dialogs/customdialog.js' ; CKEDITOR.dialog.add( myPluginName, customize_dialo ...

What is the method for determining the new point coordinates and direction vector after a rotation of degrees in three.js?

How can I determine the coordinates of point A to H after rotating a certain number of degrees and aligning them with direction vector (-42, 51, 11) using three.js? Thank you in advance for your help and please forgive any mistakes in my English. Best reg ...

Issue with Promise.all not waiting for Promise to resolve

After making a request to the server, I receive the data as a promise, which contains the correct information. However, for some reason, the program fails to execute properly. Prior to uploading it on Zeit, this program was functioning correctly. Fetch R ...

Designing a dropdown menu within displaytag

I am currently utilizing displaytag to present tabular data, but I aspire to design a user interface akin to "kayak.com" where clicking on a row reveals additional details without refreshing the page. Here is an example scenario before clicking the Detail ...

Making modifications to the CSS within an embedded iframe webpage

Assigned with the task of implementing a specific method on a SharePoint 2013 site. Let's dive in. Situation: - Within a page on a SharePoint 2013 site, there is a "content editor" web part that displays a page from the same domain/site collection. T ...

Unexplained failure in saving mongoose documents

I am currently encountering an issue with the mongoose save method in my project. The problem lies in the fact that it fails without generating any errors. After investigating, I discovered that the failure is due to the userId field being marked as requi ...

The required element was not discovered

Whenever I attempt to execute npm run serve, it reaches 98% completion and then halts, displaying the following error message: An issue occurred while compiling with a total of 1 error: ...

Assign increasing values within an array

Is there a way to efficiently update multiple values in an array by mapping through them? I want to select and change all of them simultaneously. state.formData.forEach(item => { item.EndDate = nextDayIfSelected; }); ...

What is the best way to combine the elements within an array with the elements outside of the array in order to calculate their sum?

The goal is to create a function that determines the winner using two input integers. The function should return the first input if it is greater than the second input. function determineWinner(a, b) { let result = [] for (let i = 0; i < 3; i++) ...

There is a possibility of encountering an endless update loop in the watcher when utilizing the expression "tabs" error in vue

My code includes a watcher on tabs to prevent them from changing based on the values of the edit. If edit is false, then go to the next tab; otherwise, prevent the change. However, when I try to click on the tab heading to change the tab, I encounter an er ...

Utilizing FlatList in React Native to display a parsed JSON array response

Can anyone help me with parsing the JSON response below into a FlatList? I'm not sure what I'm missing since it doesn't follow the standard key and value pair structure for rendering. {"list":["a","b","c","d"]} Here is my code... impo ...

Issues with the functionality of jQuery append and AngularJS ng-if not functioning

In my application using checkboxes, I control the visibility of charts with the ng-if directive and implement drag-and-drop functionality with angular-Dragula. The use of ng-if is essential for me as it allows me to manipulate visible div IDs and organize ...

javascript: extracting class name from HTML elements

To extract class names from an HTML code using JavaScript, I can utilize the following method: var cPattern = new RegExp(/class[ \t]*=[ \t]*"[^"]+"/g); var cMatches = data.match(cPattern); However, the above code returns an array with values li ...

Error message received from Express middleware: "Unable to modify headers after they have been sent."

I have created middleware for my Node Express app to perform the following tasks: Checking all incoming requests to determine if they are from a bot Allowing requests for raw resources to proceed Serving an HTML snapshot if the request is from a bot How ...

Issue with font selection in Fabric.js

I am currently working with fabric js version 1.7.22 alongside angular 7 to create a text editor. I have encountered an issue when trying to add text to the canvas using a custom font as shown in the code snippet below. var canvas= new fabric.Canvas(&apos ...

Building a PathString Tree

I encountered a similar issue like the one discussed in this post (Get a tree like structure out of path string). I attempted to implement the suggested solution but I am facing difficulties getting it to work within an Angular context. The concept involv ...

I am having trouble getting the minimum value as it keeps displaying 0. However, when using Math.max(), it correctly displays the maximum value. Can anyone explain why this is the case?

Why am I not getting the minimum value when it displays 0, but Math.max() correctly shows the maximum value? function findMin(ar) { var min_val = 0; for(var i = 0; i < ar.length; i++) { min_val = Math.min(min_val,ar[i]); } document.write(m ...