πŸ”‘ Obtaining Your Maps API Key(s)

Spatialized founder Jozef Sorocin
Book a consultation β†—
12 min read  β€’  Updated 09/15/2025

What You'll Master in This Chapter
Skip the API key setup headaches that kill 90% of mapping projects β†’

  • Battle-Tested GCP Setup: Exact hierarchy and configuration that works from day one
  • Programmatic Key Creation: gcloud CLI automation for scalable key management
  • Enterprise Security: Bulletproof restrictions, Secret Manager integration, and key rotation strategies
  • Team Management: Multi-environment keys, quota monitoring, and access control
  • Complete Troubleshooting: Resolution strategies for every common API key error you might encounter

The Maps Platform runs on the Google Cloud Platform (GCP).

Roughly speaking, GCP is Google's answer to Amazon's AWS and Microsoft's Azure. But in terms of geospatial tooling, nothing comes close to Google's extensive offering.

Now, even if you only intend to use GCP's map-related features, you'll still need:

  • a GCP account
  • a GCP billing account
  • a GCP project
  • and a GCP Maps Key.

That's a bunch of new terms so let's visualize a typical, moderately complex scenario which will help us understand the moving parts.

I have a web application consisting of a frontend and a backend. I need two separate API keys – one to display a map on the frontend and another to run geospatial workloads from the backend.

From GCP's point of view, the hierarchical architecture for the above scenario looks as follows:

↳ (user) account
	↳ billing account
    ↳ project A
      ↳ Frontend API key
      ↳ Backend API key
      ↳ Development/testing key (optional)

Each of these keys should have its own restrictions as discussed below .
Also note that the whole project is associated with at most one billing account.

Assuming you already have a google account (e.g. a @gmail.com email or a company email running on Google Workspace):

  1. Visit console.cloud.google.com
  2. Click on the "Select a Project" dropdown in the top navbar and then click on "New Project".
  3. Give your project a name and click "Create".
  4. Wait for the project to be created. This may take a few minutes.
  5. If you don't have a billing account, you'll be prompted to create one. FYI, almost every new billing account gets $200 USD of monthly credit towards Maps usage.

2025 Pricing Update: Google has adjusted their free tier. New accounts now receive $200/month in free credits (down from $300), but this still covers substantial usage for most applications.

  1. In the Google Cloud Platform console, select your project from the dropdown in the top navigation bar.
  2. Click on the hamburger menu in the top-left corner and select "APIs & Services" > "Dashboard".
  3. Click on "Enable APIs and Services".
  4. Search for "Maps Javascript API" and click on it.
  5. Click the "Enable" button.
  6. Click on the "Credentials" tab in the left sidebar.
  7. Click the "Create Credentials" dropdown and select "API Key".

After that's done, a fresh new API key will have been autogenerated.

As of Nov 2023, you can programmatically create API keys with Google Cloud's CLI (gcloud) .

You can use gcloud locally or as part of your CI/CD pipelines, e.g. in Github Actions .

Once you've got gcloud installed, authenticate and set the corresponding account + project:

gcloud config set account my@email.com
gcloud config set project my-project-name

After that, look into the services api-keys create command, now available in stable release:

gcloud services api-keys create \
  --display-name="Frontend API key - Prod" \
  --allowed-referrers="https://*.example.com/*" \
  --api-target=service=places.googleapis.com,service=maps.googleapis.com

2025 Update: The gcloud services api-keys commands are now GA (generally available) and no longer require the beta prefix.

To retrieve the list of available services (Maps and other GCP APIs) to pass to --api-target, run:

gcloud services list --available --filter="name:googleapis.com"

Note: I've originally answered this question on Stack Overflow .

Your project will likely have certain map-related APIs (e.g. the Maps Javascript API) already enabled by default.

After creating your very first key, you may be prompted to restrict it:

A prompt to protect the newly created key
A prompt to protect the newly created key
A prompt to protect the newly created key

Key restriction is a security best practice that limits the API scopes in which the key may be used. Choosing not to restrict your keys may lead to unexpected charges or even key hijacking.

It's recommended to use both the application restrictions (as shown above) and the API restrictions.

We will select API restrictions and HTTP referrers.

Go to the corresponding Console page, open the β€œCredentials” panel and choose a key to edit:

Editing an API key
Editing an API key
Editing an API key

Only select those APIs which you intend to use. If you don't see a particular API in the dropdown, you'll need to enable it through the Library .

API restrictions
API restrictions
API restrictions

This restriction is even more important than the API restrictions. You can input regex -like entries targeting:

  • the whole domain ( wildcard )
  • selected or all subdomains (wildcard)
  • or just specific pages and subpages (prefixed wildcard)

HTTP referrer restrictions
HTTP referrer restrictions
HTTP referrer restrictions

Finally, click β€œSave” on the bottom of the page. Once the changes have propagated across Google's network, only visits from the explicitly allowed (sub)domains will be let through.

You may also need to add your local development URL (e.g. localhost:3000) to the referrer list. Otherwise, your may encounter a β›” RefererNotAllowedMapError .

Repeat the same process for the backend key and you'll end up with production-ready API keys:

Production-ready, restricted API keys
Production-ready, restricted API keys
Production-ready, restricted API keys

If your frontend API key is properly restricted, you can use it freely in your frontend code. But when it comes to the backend key, you should take appropriate measures to secure it, e.g. using Google's Secret Manager , and never expose it in your frontend code.

2025 Best Practices: For larger teams and production applications, implement these advanced key management strategies.

Most development teams work across multiple environments - you develop locally, test on staging, and deploy to production. Using the same API key everywhere is a security risk and makes debugging harder when something goes wrong.

The smart approach is to create separate API keys for each environment, each with its own restrictions. This way, your production key can't accidentally be used in development, and if a development key gets compromised, it can't access your production data.

# Create keys for different environments
gcloud services api-keys create \
  --display-name="Maps API - Development" \
  --allowed-referrers="http://localhost:*/*,https://*.dev.example.com/*"

gcloud services api-keys create \
  --display-name="Maps API - Staging" \
  --allowed-referrers="https://*.staging.example.com/*"

gcloud services api-keys create \
  --display-name="Maps API - Production" \
  --allowed-referrers="https://example.com/*,https://www.example.com/*"

Notice how the development key includes localhost:* for local development, while production keys are strictly limited to your live domains.

Nothing ruins your day quite like waking up to a surprise $500 Google Cloud bill because someone misconfigured a loop that hammered your Maps API. The good news? You can set up monitoring that catches runaway usage before it hits your wallet.

Google Cloud's monitoring system can watch your API usage in real-time and alert you when things look suspicious. Here's how to set up a safety net:

First, enable monitoring on your project:

gcloud services enable monitoring.googleapis.com

Next, set up usage alerts through the Google Cloud Console:

  • Navigate to "Monitoring" > "Alerting" in Google Cloud Console
  • Create alert policy for "Maps API" usage
  • Set threshold at 80% of your monthly budget
  • Configure email/SMS notifications

This gives you early warning when usage spikes unexpectedly, usually before you hit expensive billing tiers.

Finally, set hard quota limits to prevent runaway costs:

gcloud services quota update \
  --service=maps.googleapis.com \
  --consumer=projects/YOUR_PROJECT_ID \
  --metric=maps.googleapis.com/quota/requests \
  --value=10000

The quota limit acts like a circuit breaker - once you hit 10,000 requests in this example, the API stops responding rather than racking up charges.

API keys are like passwords - they should be changed regularly. If an API key gets compromised (leaked in a GitHub repo, exposed in browser dev tools, or stolen by malware), you want to limit how long an attacker can use it.

Most security teams rotate API keys quarterly or semi-annually. Here's a script that automates the process of creating new keys while keeping the old ones active during the transition:

# Script for quarterly key rotation
#!/bin/bash
DATE=$(date +"%Y%m%d")
PROJECT_ID="your-project-id"

# Create new key
NEW_KEY=$(gcloud services api-keys create \
  --display-name="Maps API - Prod - $DATE" \
  --allowed-referrers="https://example.com/*" \
  --format="value(name)")

# Get the actual key value
KEY_VALUE=$(gcloud services api-keys get-key-string $NEW_KEY --format="value(keyString)")

echo "New API key created: $KEY_VALUE"
echo "Update your application configuration and test thoroughly"
echo "Delete old key after successful deployment"

The key insight is to create the new key first, then update your application configuration, test everything works, and only then delete the old key. This prevents any service interruption during the rotation process.

When you see "API key not valid", it's usually not because the key itself is wrong - it's because the key can't access what you're trying to use it for. This error typically means either your key restrictions are too tight or you haven't enabled the right APIs.

First, check what restrictions are applied to your key:

gcloud services api-keys describe projects/PROJECT_ID/locations/global/keys/KEY_ID

This shows you exactly which domains and APIs the key is restricted to. Make sure your current domain is in the allowed referrers list.

Next, verify that the APIs you're trying to use are actually enabled:

gcloud services list --enabled --filter="name:maps"

You might be surprised how often this catches issues - you created a key for the "Maps JavaScript API" but you're actually trying to use the "Places API" which wasn't enabled yet.

Getting "Quota Exceeded" errors? This usually means you've hit either your daily request limit or your spending cap. The frustrating part is that these errors often happen right when you're in the middle of debugging something important.

To see what's actually using your quota, check your API request logs:

# Check current quota usage
gcloud logging read 'resource.type="consumed_api" AND protoPayload.serviceName="maps.googleapis.com"' \
  --limit=50 \
  --format='table(timestamp,protoPayload.authenticationInfo.principalEmail,protoPayload.requestMetadata.callerIp)'

This shows you exactly who's making requests and when, which helps you identify if it's legitimate traffic or a runaway script.

For longer-term protection, set up budget alerts that warn you before you hit limits:

# Set up budget alerts
gcloud alpha billing budgets create \
  --billing-account=BILLING_ACCOUNT_ID \
  --display-name="Maps API Budget Alert" \
  --budget-amount=100USD \
  --threshold-rule=percent=0.8

The alert triggers when you hit 80% of your $100 budget, giving you time to investigate before hitting the hard limit.

API key security isn't just about restricting domains - it's about defense in depth. Here are the techniques that separate professional applications from hobby projects:

Never store backend API keys in plain text. Frontend keys are meant to be public, but backend keys should be treated like database passwords. Use Google's Secret Manager to store them securely:

# Store backend API key securely
echo -n "YOUR_BACKEND_API_KEY" | gcloud secrets create maps-api-backend-key --data-file=-

Your application can then retrieve the key at runtime without ever storing it in your codebase or environment files.

Add an extra layer of validation in your backend. Even with Google's restrictions, you can add your own middleware that double-checks requests are coming from expected sources:

// Express.js middleware example
const validateMapsKey = (req, res, next) => {
  const referer = req.get('Referer');
  const allowedDomains = ['yourdomain.com', 'www.yourdomain.com'];
  
  if (!referer || !allowedDomains.some(domain => referer.includes(domain))) {
    return res.status(403).json({ error: 'Invalid referrer' });
  }
  next();
};

This catches attempts to use your keys from unexpected domains, even if someone manages to bypass Google's restrictions.

Set up monitoring that alerts you to suspicious usage patterns. Legitimate usage tends to be predictable - sudden spikes or requests from unusual locations often indicate abuse:

# Set up log-based metrics
gcloud logging metrics create maps_api_usage \
  --description="Track Maps API usage patterns" \
  --log-filter='resource.type="consumed_api" AND protoPayload.serviceName="maps.googleapis.com"'

This creates custom metrics you can use to build dashboards and alerts around your specific usage patterns.

Once you have the keys properly configured and secured, we're onto 🌐 Creating a New Google Map .