Make sure your API keys are safe and secure before starting your projects!
Go to the Google Cloud Console, create a new project, and enable the Maps JavaScript API.
In the Cloud Console under Credentials, add HTTP referrer restrictions (e.g., websitename.com) and enable only the required APIs for your project.
Create a .env file in your backend project root and add:
GOOGLE_MAPS_API_KEY = YOUR_API_KEY_HERE
Make sure to add .env to your .gitignore to avoid committing secrets.
Create a backend API endpoint that returns the API key securely (example using Node.js & Express):
require('dotenv').config();
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname)));
app.get('/api-key', (req, res) => {
res.json({ key: process.env.GOOGLE_MAPS_API_KEY});
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});
Fetch the API key from your backend and add it to the bottom of your script:
async function loadGoogleMaps() {
try {
const response = await fetch('/api-key');
if (!response.ok) {
throw new Error('Failed to fetch API key');
}
const data = await response.json();
const script = document.createElement('script');
script.src = `https://maps.googleapis.com/maps/api/js?key=${data.key}&callback=initMap&libraries=places`;
script.async = true;
script.defer = true;
document.head.appendChild(script);
} catch (error) {
console.error("Error loading Google Maps API: ", error);
}
}
loadGoogleMaps();