Create a Simple Map Using JavaScript

To customize maps with images and shapes, it’s better to use coding in JavaScript instead of simply embedding the maps into web pages. To accomplish this task, we use the Google Maps JavaScript API. The base URL of the JavaScript API looks like this: https://maps.googleapis.com/maps/api/js?key=API_KEY&PARAMETERS.

Maps JavaScript API URL parameters

The Google Maps JavaScript API supports the following URL parameters:

Parameters

Category

Description

key

Required

This parameter specifies the needed API key.

callback

Required

This parameter specifies the name of the global function to call, once the Maps JavaScript API loads completely.

v

Optional

This parameter specifies which version of the Google Maps JavaScript API is used.

libraries

Optional

This parameter specifies the comma-separated list of which additional Maps JavaScript API libraries are used.

language

Optional

This parameter specifies a supported language for the map using a language code.

region

Optional

This parameter specifies the two-letter region code used for the map. It modifies the map's behavior based on the given territory. For example, the region code for Great Britain is GB.

solution_channel

Optional

This query parameter is meant for Google's own quality control. There is no need to provide a value for this parameter.

auth_referrer_policy

Optional

This parameter allows configuring HTTP Referrer Restrictions in the Cloud console to control which URLs are allowed to use a particular API Key.

Note: The complete updated list of supported region codes and language codes can be found on the Google Maps Developer Platform.

Create a simple map

To display the map on the web page, begin by reserving a spot for it. This can be done by creating a named div element in the HTML file.

In our code examples, div elements are named map. Here’s how that looks:

<div id="map"></div>

A reference to this element in the browser’s DOMDocument Object Model is also needed in order to control and customize the map.

Obtain a reference to the div element by using the document.getElementById() method in the JavaScript file. Since the div element is named map, get the DOM reference by adding map as a parameter of the document.getElementById() method, as shown below:

document.getElementById("map")

The Map object

A map is represented using the google.maps.Map JS class. Objects of this class define a single map on a page. To create a new instance of this class, use JavaScript’s new operator.

Note: It’s possible to create more than one instance of this class, in which each instance defines a separate map on the web page.

A div element in the HTML page is defined as a map container whenever a new map instance is created and gets its reference using the document.getElementById() method.

Here’s how to create a new map object and get the reference to the named div element:

map = new google.maps.Map(document.getElementById('map'), {...});

The MapOptions parameter

The Map constructor takes in the MapOptions parameter that defines the location where the map is centered and the style set for altering the map’s visual features.

All MapOptions parameters are optional, and there are no required parameters. Here’s a list of some optional MapOptions parameters that we can pass to the Map constructor:

Parameters

Type

Description

center

LatLng | LatLngLiteral

This parameter specifies the initial location of the map's center using the latitude and longitude coordinates.

zoom

number

This parameter specifies the initial zoom level of the map.

disableDefaultUI

boolean

This parameter enables or disables the default UI controls on the map.

fullscreenControl

boolean

This parameter enables or disables the state of the fullscreen control.

fullscreenControlOptions

FullscreenControlOptions

This parameter specifies the options for the fullscreen control.

gestureHandling

string

This parameter specifies how the API handles gestures on the map. These are possible values that can be passed to it:

  • cooperative: In this mode, scroll events and one-finger touch gestures scroll the page but cannot zoom or pan the map.
  • greedy: Touch gestures and scroll events can pan or zoom the map in this mode.
  • none: In this mode, users cannot pan or zoom the map through user gestures.
  • auto: This is a default mode in which gestureHandling is either cooperative or greedy.


keyboardShortcuts

boolean

This parameter specifies whether a user can use keyboard controls or not. The default value for this parameter is true.

mapId

string

This parameter specifies the Map ID of the map, which can’t be modified once the map object is constructed.

mapTypeControl

boolean

This parameter enables or disables the state of the map type control.

mapTypeControlOptions

MapTypeControlOptions

This parameter specifies the options for the map type control.

mapTypeId

MapTypeId | string

This parameter specifies the initial map type to use on the map. There are four possible map types: roadmap, terrain, satellite, and hybrid. The default value for this parameter is roadmap.

maxZoom

number

This parameter specifies the maximum zoom level of the map that can be displayed.

minZoom

number

This parameter specifies the minimum zoom level of the map that can be displayed.

restriction

MapRestriction

This parameter specifies the bounds that restrict the map sections accessible to the users.

rotateControl

boolean

This parameter enables or disables the state of the rotate control.

rotateControlOptions

RotateControlOptions

This parameter specifies the options for rotation control.

scaleControl

boolean

This parameter enables or disables the state of the scale control.

scaleControlOptions

ScaleControlOptions

This parameter specifies the options for the scale control.

scrollwheel

boolean

This parameter specifies whether a user can use a mouse scroll wheel for zooming on the map.

streetView

StreetViewPanorama

This parameter specifies a panorama of a Street View to be displayed when we drop a Street View Pegman on the map.

streetViewControl

boolean

This parameter enables or disables the state of the Street View control.

streetViewControlOptions

StreetViewControlOptions

This parameter specifies the options for the Street View control.

styles

Array<MapTypeStyle>

This parameter specifies the styles to apply to each default map type. Note that these styles will only apply to labels and geometry for satellite, hybrid, and terrain modes.

tilt

number

The satellite and hybrid map types also feature 45° image support. This is only available on zoom levels greater than 12. This high-resolution imagery provides tilted perspective views towards the four cardinal directions.

zoomControl

boolean

This parameter enables or disables the state of the zoom control.

zoomControlOptions

ZoomControlOptions

This parameter specifies the options for the zoom control.

We can construct a Map object without any parameters because they’re all optional. However, to display a Map object, the zoom and center parameters are required.

These parameters can be provided either during the construction of the map or after construction using the setValues() method. Here’s an example of how to construct a Map object using the center and zoom parameters:

map = new google.maps.Map(document.getElementById('map'), {
    center: { lat: 47.6059, lng: -122.3345 },  // Coordinates of Seattle
    zoom: 8
});

Load the Maps JavaScript API

The script tag is used to load the API. It can be added inline in the HTML file or dynamically using JavaScript. In the example for this lesson, the inline approach is invoked by adding a script tag, as shown below.

<script async
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>

In the script tag, several attributes which are recommended when embedding a map using this API are set. The explanations for each attribute are as follows:

  • The src attribute specifies the URL from which the Maps JS API is loaded. The URL in this example has two parameters:
    • The key parameter is the API key that needs to be provided.
    • The callback is the name of the global function that’s called once the Maps JavaScript API loads completely.
  • The async attribute asks the browser to asynchronously download and execute the script. When the script is executed, the function specified using the callback parameter is called.

Code example

Let’s look at a simple example to get started with learning the Maps JS API. The following map example displays a map centered on Seattle, Washington.

Console
Simple map

Here’s a brief explanation of the HTML and JavaScript files in the above code widget.

In the HTML file, we’re doing the following:

  • Line 1: We declare the application as HTML5 using <!DOCTYPE html>.
  • line 9: To hold the map on the web page, we create a div element with an ID of map.
  • Lines 11–17: To load the Maps JS API, we use the script tag.

In the JavaScript file, we’re doing the following:

  • Line 3: We define a function that creates the map called initMap.
  • Line 4: We obtain a DOM reference for the div element using document.getElementById("map").
  • Lines 5–6: We set the center with the coordinates for Seattle, Washington, and set the zoom to 8.