Ionic集成Google Maps API遇Autocomplete未定义及脚本&符号问题
Hey there, let's tackle these two common issues you're facing with Google Maps Autocomplete in your Ionic project—we'll get you up and running smoothly.
1. Resolving "Cannot read property 'Autocomplete' of undefined"
This error almost always pops up because the Google Maps Places library either hasn't finished loading before you try to initialize Autocomplete, or it wasn't loaded at all. Here's how to fix it:
Ensure the Places library is included
First, make sure your script URL includes the libraries=places parameter—this is non-negotiable for Autocomplete to work. We'll cover the & symbol issue in the next section, but for now, focus on having that parameter present.
Wait for the script to load before initializing
Don't call new google.maps.places.Autocomplete() immediately when your component loads. Instead, wait until the Google Maps script is fully loaded. Here are two reliable approaches:
Option 1: Use Ionic's lifecycle hooks + load event listener
import { Component } from '@angular/core'; @Component({ selector: 'app-map-autocomplete', templateUrl: './map-autocomplete.component.html', styleUrls: ['./map-autocomplete.component.scss'], }) export class MapAutocompleteComponent { ionViewDidEnter() { // Check if Google Maps is already loaded if (window.google?.maps?.places) { this.initAutocomplete(); } else { // Listen for the window load event to ensure script is ready window.addEventListener('load', () => { this.initAutocomplete(); }); } } private initAutocomplete() { const input = document.getElementById('location-input') as HTMLInputElement; const autocomplete = new window.google.maps.places.Autocomplete(input); // Add listener for place selection autocomplete.addListener('place_changed', () => { const selectedPlace = autocomplete.getPlace(); console.log('Selected place:', selectedPlace); // Add your logic to handle the selected location here }); } }
Option 2: Dynamically load the script with a Promise
This method ensures the script loads completely before you try to use Autocomplete, avoiding race conditions:
async ionViewDidEnter() { await this.loadGoogleMapsScript(); this.initAutocomplete(); } private loadGoogleMapsScript(): Promise<void> { return new Promise((resolve, reject) => { // Check if script is already loaded if (window.google?.maps?.places) { resolve(); return; } // Create script element const script = document.createElement('script'); script.src = `https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places`; script.async = true; script.defer = true; // Resolve when script loads script.onload = () => resolve(); // Reject if there's an error loading the script script.onerror = () => reject(new Error('Failed to load Google Maps script')); // Add script to the DOM document.body.appendChild(script); }); }
Double-check your API key
Make sure your Google Cloud API key is valid, has the Places API enabled, and isn't restricted to domains/IPs that don't include your Ionic app (especially if you're testing locally).
2. Fixing the "&" symbol issue when importing the script
If your environment (like Angular's template compiler) is rejecting the & in the script URL, it's because HTML requires ampersands to be escaped as &. Here's what to do:
In your index.html template
Replace the & with & in the script URL:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
The browser will automatically parse & back to &, so the script will load correctly with the places library included.
If using dynamic script loading (like the Promise method above)
You don't need to escape the & here—since you're building the URL as a JavaScript string, the ampersand will be treated correctly without escaping.
In angular.json (if adding the script to build config)
If you're including the script in your angular.json under scripts, you can use either & or &—most build tools will handle the escaping automatically, but if you run into issues, switch to &.
内容的提问来源于stack exchange,提问作者Jaime Román

