Angular集成agm/core后Google Map报InvalidKeyMapError错误求助
Hey there, let's break down why you're hitting that InvalidKeyMapError when using AGM in your Angular app. This error almost always traces back to issues with your Google Maps API key setup—let's walk through the most common fixes step by step:
Double-check your API key's validity and enabled APIs
Head over to your Google Cloud Console and verify:- Your API key exists and hasn't been deleted or disabled.
- The Maps JavaScript API is enabled for this key (AGM depends on this core API to render maps).
- Since you're including the
placeslibrary in your config, make sure the Places API is also enabled for your key.
Eliminate typos or whitespace in your API key
It's easy to accidentally copy extra spaces or miss a character when pasting your key. Ensure yourAgmCoreModuleconfiguration uses the exact, unmodified key with no extra whitespace:AgmCoreModule.forRoot({ apiKey: 'YOUR_REAL_API_KEY', // No extra spaces, no typos libraries: ['places'] })Also, make sure you're using straight single quotes (
') not curly quotes, which can cause parsing issues.Verify API key restrictions are properly configured
If you've set up restrictions on your API key (a smart security practice), make sure your app's origin is allowed:- For local Angular development, add
http://localhost:4200(or your custom dev port) to the HTTP referrer allowlist. - For production, add your app's full domain (e.g.,
https://your-app-domain.com).
Avoid overly broad or overly restrictive rules that might block your app from accessing the API.
- For local Angular development, add
Clear cache and restart your dev server
Sometimes your browser caches an old, invalid key, or your Angular dev server hasn't picked up the latest config changes. Try:- Stopping and restarting your
ng servecommand. - Testing in a private/incognito browser window to bypass cached data.
- Stopping and restarting your
Confirm AGM and Angular version compatibility
Ensure the version of@agm/coreyou installed is compatible with your Angular version. For example, newer AGM versions require Angular 14+, so if you're on an older Angular release, you might need to install a matching AGM version. You can check the AGM package's README for version compatibility details.
If you've tried all these steps and still see the error, check the Google Cloud Console's API error logs—they'll often provide more specific details about why the key is being rejected (like a missing enabled API or incorrect restriction).
内容的提问来源于stack exchange,提问作者Fahad Subzwari

