Skip to content

Google Maps - Getting Started

Google Maps Platform - Getting Started with Maps JavaScript API

Section titled “Google Maps Platform - Getting Started with Maps JavaScript API”

This tutorial guides you through displaying a simple, interactive Google Map on your web page using the Maps JavaScript API.

The Google Maps Platform’s Maps JavaScript API allows you to embed customized Google Maps directly into your own web pages. It’s a powerful tool for:

  • Displaying geographic locations relevant to your content.
  • Visualizing data points on a map (e.g., store locations, user activity).
  • Providing interactive features like panning, zooming, and switching map types.
  • Adding markers, lines, shapes, and information windows to highlight specific areas or routes.
  • Integrating with other Google Maps services like Directions, Geocoding, and Places.

This initial chapter focuses on the fundamental steps to get a basic map up and running.

Follow these steps to embed your first Google Map:

Step 1: Set Up Your Environment & Get an API Key

Section titled “Step 1: Set Up Your Environment & Get an API Key”

Before you start, you need an API key. This key authenticates your requests to Google’s services.

  • Go to the Google Cloud Console.
  • Create a new project or select an existing one.
  • Enable the “Maps JavaScript API” service for your project.
  • Create credentials to get an API key.
  • Important: Secure your API key! Restrict its usage to your specific web domains to prevent unauthorized use. See API Key Best Practices.

Start with a standard HTML5 document structure:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Google Map</title>
<style>
/* Basic styling for the map container */
#map {
height: 400px; /* Or any desired height */
width: 100%; /* Makes the map responsive */
}
/* Optional: Ensure html and body take full height */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<h3>My Google Map</h3>
<!-- The div element that will contain the map -->
<div id="map"></div>
<!-- API Script will go here -->
</body>
</html>

Notice the div with the id="map". This is where the map will be rendered. The CSS ensures this div has a defined height, which is crucial for the map to display.

Include the API script just before the closing </body> tag. Replace YOUR_API_KEY with the key you obtained in Step 1.

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly" async defer></script>
<!--
Key Parameters:
- key=YOUR_API_KEY: Your unique API key (Required).
- callback=initMap: Specifies the global function to call once the API is loaded.
- v=weekly: Specifies the API version (weekly channel is recommended for development).
- async: Allows the script to be downloaded in parallel without blocking HTML parsing.
- defer: Ensures the script executes only after the HTML is fully parsed.
-->

Step 4: Define the initMap Callback Function

Section titled “Step 4: Define the initMap Callback Function”

The callback=initMap parameter tells the API to execute the initMap function once it’s ready. Create this function within a <script> tag (or in a separate JS file). This function will create and configure your map.

<script>
// Initialize and add the map
async function initMap() {
// The location to center the map on (e.g., Visakhapatnam)
const position = { lat: 17.6868, lng: 83.2185 };
// Request needed libraries.
// Import the Map class from the 'maps' library
const { Map } = await google.maps.importLibrary("maps");
// The map, centered at the specified position
const map = new Map(document.getElementById("map"), {
zoom: 12, // Initial zoom level (higher value = more zoomed in)
center: position, // Center the map on the 'position' coordinates
mapId: "DEMO_MAP_ID", // Optional: A Map ID for Cloud-based styling
mapTypeId: 'roadmap' // Initial map type (roadmap, satellite, hybrid, terrain)
});
// Optional: Add a marker at the center position
// const { Marker } = await google.maps.importLibrary("marker");
// const marker = new Marker({
// map: map,
// position: position,
// title: 'Visakhapatnam'
// });
}
// Call initMap - This is handled by the callback parameter in the script URL
// initMap(); // No need to call explicitly when using the callback parameter
</script>
  • async function initMap(): Declares an asynchronous function. Using async allows us to use await inside.
  • const position = { lat: ..., lng: ... };: Defines the geographical coordinates (Latitude, Longitude) using a modern object literal.
  • await google.maps.importLibrary("maps"): Asynchronously loads the necessary maps library components, including the Map class. This is the modern way to load specific API features.
  • new Map(document.getElementById("map"), {...}): Creates a new Google Map instance. It takes two arguments:
  • - The HTML element (our `<div id="map">`) where the map should be displayed.
  • - A `MapOptions` object literal containing configuration settings:
  • - `zoom`: Controls the initial magnification level. Higher numbers zoom in closer.
  • - `center`: Sets the initial map center using the `position` object.
  • - `mapId`: (Optional but recommended for customization) Links to a Map ID configured in Google Cloud Console for cloud-based map styling. Using a `mapId` is the modern way to style maps.
  • - `mapTypeId`: Specifies the initial map type. Common values are `'roadmap'`, `'satellite'`, `'hybrid'`, `'terrain'`.

Save your HTML file and open it in a web browser. You should see an interactive Google Map centered on the specified location (Visakhapatnam in the example).

  • Blank Page/Map Not Loading: Check the browser’s developer console (usually F12) for errors. Common issues include:
  • - Missing or incorrect API key.
  • - API key restrictions preventing your domain (e.g., `localhost` or `file://`) from using it.
  • - The Maps JavaScript API not being enabled in the Cloud Console.
  • - JavaScript errors in your `initMap` function.
  • - The map `div` not having a defined `height`.
  • ‘initMap is not a function’ error: Ensure your initMap function is defined in the global scope (not inside another function unless properly exposed) and that the callback=initMap parameter in the API script URL exactly matches your function name.
  • API Key Security: Remember to restrict your API key in the Cloud Console for production environments.

Here is the complete code combining all the steps:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Google Map</title>
<style>
#map {
height: 400px;
width: 100%;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<h3>My Google Map</h3>
<div id="map"></div>
<script>
// Initialize and add the map
async function initMap() {
const position = { lat: 17.6868, lng: 83.2185 }; // Visakhapatnam
// Request needed libraries.
const { Map } = await google.maps.importLibrary("maps");
// Optional: Import marker library if you want to add a marker
// const { Marker } = await google.maps.importLibrary("marker");
const map = new Map(document.getElementById("map"), {
zoom: 12,
center: position,
mapId: "DEMO_MAP_ID", // Optional: Replace with your own Map ID
mapTypeId: 'roadmap'
});
// Optional: Add a marker
// const marker = new Marker({
// map: map,
// position: position,
// title: 'Visakhapatnam'
// });
}
</script>
<!-- Load the Google Maps API -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap&v=weekly" async defer></script>
</body>
</html>

Remember to replace YOUR_API_KEY with your actual key.

Opening this HTML file in your browser will display an interactive map covering the Visakhapatnam area, using the standard road map style, zoomed in to show city details.