You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular 6能否通过angular.json引入远程第三方JS(如Google Maps API)?

How to Include Google Maps API in Angular 6 with Webpack Integration

Great question! The Angular CLI's scripts and assets configurations don't support external HTTP URLs directly—they're designed for local files or resources within your project structure. But there are two solid approaches to include the Google Maps API in a way that works with webpack and fits better into your Angular workflow:

This is the most Angular-friendly solution, as it wraps the Google Maps API into reusable components and handles script loading automatically, integrating smoothly with webpack. Here's how to set it up:

  • Install the library via npm:

    npm install @agm/core --save
    
  • Import and configure the module in your app.module.ts:

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AgmCoreModule } from '@agm/core';
    import { AppComponent } from './app.component';
    
    @NgModule({
      declarations: [AppComponent],
      imports: [
        BrowserModule,
        AgmCoreModule.forRoot({
          apiKey: 'YOUR_GOOGLE_MAPS_API_KEY',
          // Optional: Add additional libraries like places, geometry, etc.
          libraries: ['places']
        })
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    
  • Use the component in your template (e.g., app.component.html):

    <agm-map [latitude]="51.678418" [longitude]="7.809007" [zoom]="12">
      <agm-marker [latitude]="51.678418" [longitude]="7.809007"></agm-marker>
    </agm-map>
    

AGM takes care of loading the Google Maps script dynamically when needed, and it will be part of your build process without cluttering your index.html.

2. Dynamically Load the Script Manually

If you prefer not to use a third-party library, you can create a service or component method to load the Google Maps script dynamically. This gives you full control over when the script loads:

  • Create a service (e.g., google-maps-loader.service.ts) with a method to load the script:

    import { Injectable } from '@angular/core';
    
    @Injectable({ providedIn: 'root' })
    export class GoogleMapsLoaderService {
      private scriptLoaded = false;
    
      loadGoogleMaps(): Promise<void> {
        return new Promise((resolve, reject) => {
          if (this.scriptLoaded) {
            resolve();
            return;
          }
    
          const script = document.createElement('script');
          script.src = 'https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY&callback=initMap';
          script.async = true;
          script.defer = true;
    
          // Handle script load success
          script.onload = () => {
            this.scriptLoaded = true;
            resolve();
          };
    
          // Handle script load error
          script.onerror = () => {
            reject(new Error('Failed to load Google Maps API'));
          };
    
          document.head.appendChild(script);
        });
      }
    }
    
  • Then, in your component, call this service in ngOnInit (or whenever you need the map):

    import { Component, OnInit } from '@angular/core';
    import { GoogleMapsLoaderService } from './google-maps-loader.service';
    
    @Component({
      selector: 'app-map',
      templateUrl: './map.component.html'
    })
    export class MapComponent implements OnInit {
      constructor(private mapsLoader: GoogleMapsLoaderService) {}
    
      ngOnInit(): void {
        this.mapsLoader.loadGoogleMaps().then(() => {
          // Initialize your map here (your existing initMap function)
          this.initMap();
        }).catch(error => {
          console.error(error);
        });
      }
    
      initMap(): void {
        // Your map initialization code goes here
        const map = new google.maps.Map(document.getElementById('map'), {
          center: { lat: -34.397, lng: 150.644 },
          zoom: 8
        });
      }
    }
    

Why Angular CLI's scripts/assets Don't Work for External URLs

To clarify why your initial attempts failed:

  • The scripts array in angular.json expects local file paths (relative to your project root) or paths to scripts in node_modules. Webpack tries to resolve these paths locally, so external HTTP URLs will throw errors.
  • The assets configuration is for copying local static files (like images, JSON) to the build output directory—it doesn't handle loading external scripts.

内容的提问来源于stack exchange,提问作者Mehdi Benmoha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:00:30