Graphics Maps JavaScript API Basics
Building an interactive map with the Maps JavaScript API means registering an API key, loading the library, then creating a map centered on a coordinate with a marker on it.
Why You Need an API Key
Unlike a simple iframe embed, the Maps JavaScript API hands your own code direct control over the map object — you can add custom markers, draw shapes, respond to clicks, and restyle the map to match your site. That level of access means Google needs to know who is asking, so every project must be registered under a billing-enabled Google Cloud account and identified with an API key on every request.
- Create or select a project in the Google Cloud Console.
- Enable the "Maps JavaScript API" for that project.
- Enable billing on the project (Google provides a recurring free usage credit).
- Generate an API key under Credentials.
- Restrict the key to your site's domain(s) so it can't be used elsewhere.
Loading the API Script
The library is loaded with a single script tag that includes your key as a query parameter. The async and defer attributes let the rest of the page keep loading while the script downloads, and the callback parameter names a global function that Google will call automatically the moment the library finishes loading.
Example
<!DOCTYPE html>
<html>
<head>
<script
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async
defer>
</script>
</head>
<body>
</body>
</html>Initializing the Map
Because the script calls initMap for you, that's where you create the map. The google.maps.Map constructor takes two arguments: the DOM element the map should render into, and an options object. At minimum, the options need a center — a {lat, lng} coordinate — and a zoom level to decide how far into that coordinate the initial view is.
Example
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function initMap() {
const officeLocation = { lat: 12.9716, lng: 77.5946 };
const map = new google.maps.Map(document.getElementById("map"), {
center: officeLocation,
zoom: 15,
});
const marker = new google.maps.Marker({
position: officeLocation,
map: map,
title: "Our Office",
});
}
</script>
</body>
</html>- position — the {lat, lng} coordinate the marker sits at.
- map — which map instance the marker belongs to; set it to null to remove the marker.
- title — text shown as a small tooltip when the pin is hovered.
- icon — a custom image URL to use instead of the default red pin.
- Attach an InfoWindow to a marker's click listener to pop open a richer content box, like a photo and address.
Exercise: Graphics Maps on the Web
How do most interactive web maps display large geographic areas efficiently?