Skip to main content

Command Palette

Search for a command to run...

How to integrate Google Maps in Angular

Published
13 min read

Location-based services are important in enhancing user experiences in this digital age. Integrating dynamic mapping functionalities into web applications has become a standard practice. Google Maps is a cornerstone in mapping technology, offering a wealth of features and services for developers to leverage.

This article serves as a guide for developers who want to integrate Google Maps into their websites built with Angular. From the initial setup of the development environment to handling user interactions, each section will provide practical knowledge and step-by-step instructions to facilitate the integration process.

Setting Up Development Environment

Create a new Angular project by running the command below in the terminal.

ng new <filename>

Move into the created Angular directory.

cd <filename>

Open the directory in VS Code.

code .

Install Google map dependency.

npm i @Angular/google-maps

Generate a component: googlemap.

ng generate component googlemap

Obtaining Google Maps API Key

To use Google Maps in your application, you'll need a Google Maps API Key. Here's how to obtain one:

  • Sign up for a Google Cloud Platform account here.

  • Once you're signed in, click on APIs and Services on the dashboard.

  • Next, click on ENABLE APIS AND SERVICES.

  • Look for Maps Javascript API and click on it.

  • Click on Enable.

  • On the left side of the screen, click on the menu icon.

  • Hover over APIs and Services in the menu, then select Credentials from the options that appear.

  • Click on CREATE CREDENTIALS and choose API key. A new window will pop up showing your API key, Copy it.

Embedding Google Maps in Angular Component

In this section, we'll cover how to set up a basic map, show it on the component's template, and handle user actions like clicking or moving the map. Let's get started!

Firstly, load Maps JavaScript API in your index.html file by adding a script tag as shown below. Replace YOUR_API_KEY with the API key generated earlier.

This script tag tells your web page to load the Google Maps API, allowing you to use its features in your Angular application.

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

Next, specify an empty path for GooglemapComponent in the app.routes.ts file.

export const routes: Routes = [{ path: '', component: GooglemapComponent }];

Finally, delete the template in the app.component.html file leaving only the code below.

<router-outlet />

Setting up basic map configuration

We set up the basic map configuration to control how the map looks and works initially, like where it's centered, how close it zooms, and what type of map it is. This ensures the map fits our app's needs.

To do this, open the googlemap.component.ts file and import GoogleMapsModule

import { GoogleMapsModule } from '@Angular/google-maps';

Import GoogleMapsModule in @component class.

@Component({
  //other metadata
   imports: [GoogleMapsModule],
 })

In the GooglemapComponent class, define the following variables:

  • center of type google.maps.LatLngLiteral initialized with latitude and longitude coordinates {lat: 0, lng: 0} representing the center of the map.

  • zoom: This is initialized with the value 4, representing the initial zoom level of the map.

  • display of type any which would store the latitude and longitude coordinates.

export class GooglemapComponent {
  center: google.maps.LatLngLiteral = { lat: 0, lng: 0 };
  zoom = 4;
  display: any;
}

Next, define two methods moveMap and moveAround. Both methods take an event as input, specifically a google.maps.MapMouseEvent.

moveMap is called when the map is moved. It checks if the event.latLng isn't null. If it's not null, it updates the center variable with the new latitude and longitude coordinates from the event.

moveAround updates display variable with latitude and longitude coordinates as the mouse moves over the map.

export class GooglemapComponent {
  //Center, zoom, and display variables.

  moveMap(event: google.maps.MapMouseEvent) {
    if (event.latLng != null) this.center = event.latLng.toJSON();
  }

  moveAround(event: google.maps.MapMouseEvent) {
    if (event.latLng != null) this.display = event.latLng.toJSON();
  }
}

Rendering the map on the component template

Once you've configured the map basics, show the map on the webpage with these steps:

  • In the googlemap.component.html file, use the <google-map> tag to add the Google Maps component. We'll also use Angular's data binding syntax, [center]="center" and [zoom]="zoom", to connect the center and zoom properties of the map component with variables we've defined in the GooglemapComponent class.

  • Set up (mapClick) and (mapMousemove) event binding to call methods moveMap($event) and moveAround($event) respectively, whenever the user clicks on the map or moves their mouse over it.

  • Create two <div> elements to show the latitude and longitude coordinates of the current map position. We'll achieve this using Angular's interpolation syntax, {{display?.lat}} and {{display?.lng}}.

<google-map
  [center]="center"
  [zoom]="zoom"
  (mapClick)="moveMap($event)"
  (mapMousemove)="moveAround($event)"
></google-map>
<div>Latitude: {{ display?.lat }}</div>
<div>Longitude: {{ display?.lng }}</div>

Preview of the map showing latitude and longitude coordinates as the mouse moves across it.

map main (1)

Implementing markers on Google map

Markers serve as visual indicators, pinpointing specific locations or points of interest on the map. This functionality improves user experience by providing clear reference points and context within the geographic visualization. Adding markers to a map for navigation, data visualization, or interactive applications greatly enhances its utility and effectiveness.

To implement markers in your application, import MapMarker within the @component class in googlemap.component.ts file.

@Component({
  //other metadata
  imports: [GoogleMapsModule, MapMarker],
})

In the GooglemapComponent class, define the following properties:

  • markerPositions: This is an array of objects representing latitude and longitude coordinates (google.maps.LatLngLiteral).

  • markerOptions: This property defines options for markers on the map. We can allow the markers to be draggable by setting draggable: true.

export class GooglemapComponent {
  //Center and zoom variables.

  markerPositions: google.maps.LatLngLiteral[] = [];
  markerOptions: google.maps.MarkerOptions = { draggable: true };
}

Next, create a function addMarker that receives an event as its parameter. This function gets triggered when a user clicks on the map. It places a marker on the map at the exact spot where the user clicked, defined by the latitude and longitude coordinates (event.latLng).

export class GooglemapComponent {
  //Center and zoom variables.

  //markerPositions andmarkerOptions Properties

  addMarker(event: google.maps.MapMouseEvent) {
    if (event.latLng) {
      this.markerPositions.push(event.latLng.toJSON());
    }
  }
}

Displaying the markers

To display the markers on the webpage, listen for the (mapClick) event in the googlemap.component.html file. This event triggers the addMarker($event) method when the map is clicked.

Next, use the @for directive to iterate over each position in the markerPositions array. This loop dynamically creates <map-marker> components for each position. Each <map-marker> represents a marker on the Google Map.

<!-- Specify the center and zoom attributes in the google-map element, just like you did before. -->

<google-map (mapClick)="addMarker($event)">
  @for (position of markerPositions; track position) {
  <map-marker [position]="position" [options]="markerOptions" />
  }
</google-map>

Preview of the map showing markers added dynamically.

marker

Info windows for markers

Info windows, also known as information windows or pop-up windows, display additional information when a user interacts with a marker on the map. This additional information may include details about the location represented by the marker. In this segment, we would add an info window that displays the latitude and longitude information on a specific marker on the map.

To create info windows for markers, add a connection to a child component called MapInfoWindow into the GooglemapComponent class using Angular's ViewChild decorator. This connection helps the component communicate with MapInfoWindow.

Then, create a method called openInfoWindow. This method takes a MapMarker as input. Inside this function, check if both this.infoWindow and marker are defined. If they are, then open the info window linked to that marker.

export class GooglemapComponent {

  @ViewChild(MapInfoWindow) infoWindow: MapInfoWindow | undefined;
  //Center and zoom variables.
  //markerPositions andmarkerOptions Properties
  //addMarker method goes here

  openInfoWindow(marker: MapMarker) {
    if (this.infoWindow && marker) {
      this.infoWindow.open(marker);
    }
  }
}

Displaying info window for markers on the map

In the googlemap.component.html file, assign a variable maker to the marker component for reference. Listen for a mapClick event on the marker and call the openInfoWindow() method with marker as an argument.

Create <map-info-window> component. This represents an info window on the map. Within this component, display the latitude and longitude of the marker associated with the info window, if available.

<!-- Define the center, zoom properties, and mapClick event in the google-map element as we did previously -->

<google-map>
  @for (position of markerPositions; track position) {
  <map-marker
    #marker="mapMarker"
    [position]="position"
    (mapClick)="openInfoWindow(marker)"
  />
  }
  <map-info-window>
    <p>Latitude: {{ infoWindow?.getPosition()?.lat() }}</p>
    <p>Longitude: {{ infoWindow?.getPosition()?.lng() }}</p>
  </map-info-window>
</google-map>

Image of the map displaying the longitude and latitude information of the markers.

info marker (3) (2)

Adding shapes to the map

Adding shapes to a map can enhance its visual appeal and provide valuable context for users. Shapes like polygons, circles, and polylines can represent boundaries, routes, or areas of interest. Let's explore how to integrate these shapes into the map.

Rectangle

To create a rectangle highlighting a specific area of interest on the map, import MapRectangle to the @Component class import array.

@Component({
  //other metadata
  imports: [GoogleMapsModule, MapRectangle],
})

Next, create a property called bounds to represent the boundaries of the rectangle to be drawn on the map. Initialize this property with latitude and longitude boundaries using google.maps.LatLngBoundsLiteral type. Specify the east, west, north, and south boundaries for accurate positioning.

export class GooglemapComponent {
  // center and zoom variables as previously defined

  bounds: google.maps.LatLngBoundsLiteral = {
    east: 5,
    west: -5,
    north: 5,
    south: -5,
  };
}

In the googlemap.component.html file, include <map-rectangle> element to display a rectangle overlay on the Google Map. This element should have a bounds attribute, which connects to the bounds property set in the GooglemapComponent class.

<!-- Define center and zoom attributes in the google-map element as we did previously -->

<google-map>
  <map-rectangle [bounds]="bounds" />
</google-map>

Picture showing a rectangle on the map.

rectangle

Circle

To implement a circle shape in representing an area of interest on the map, import MapCircle within the @Component class in the googlemap.component.ts file.

@Component({
  //other metadata
  imports: [GoogleMapsModule, MapCircle],
})

Within the GooglemapComponent class, create the circleCenter property. This property defines the center of the circle using google.maps.LatLngLiteral object. It specifies the latitude and longitude coordinates for the circle's center.

Next, create a property called radius. This property will determine how big the circle is by indicating the distance from its center to its outer edge.

export class GooglemapComponent {
  // center and zoom variables as previously defined.

  circleCenter: google.maps.LatLngLiteral = { lat: 10, lng: 15 };
  radius = 5;
}

Finally, define the <map-circle> element in the googlemap.component.html file. This element represents a circle overlay on the Google Map. It takes attributes for setting the center and radius of the circle.

<!-- Define center and zoom attributes in the google-map element as we did previously -->

<google-map>
  <map-circle [center]="circleCenter" [radius]="radius"></map-circle>
</google-map>

Snapshot of the map showing a circle on it.

circle

Polyline and Polygon

In the GooglemapComponent class, both polyline and polygon shapes are configured similarly. To set them up, define a property called vertices. This property holds an array containing the positions where markers will be placed on the map. Each position is defined as a google.maps.LatLngLiteral object, which includes latitude and longitude coordinates.

export class GooglemapComponent {
  // center and zoom variables as previously defined

  vertices: google.maps.LatLngLiteral[] = [
    { lat: 14, lng: 14 },
    { lat: -8, lng: 5 },
    { lat: 18, lng: -8 },
  ];
}
  • For Polyline To form polylines on the map, import MapPolyline within the @Component class import array in the googlemap.component.ts file.
@Component({
  //other metadata
  imports: [GoogleMapsModule, MapPolyline],
})

In the googlemap.component.html file, add a <map-polyline> element to show a line on the map. This element needs an attribute called [path] that tells it where to draw the line. You can set this attribute by connecting it to an array of coordinates (vertices).

<!-- Define center and zoom attributes in the google-map element as we did previously -->

<google-map>
  <map-polyline [path]="vertices" />
</google-map>

Preview of the map showing polyline on the map

polyline

  • For Polygon To draw a polygon over a specific area of the map, import MapPolygon in the @Component class import array.
@Component({
  //other metadata
  imports: [GoogleMapsModule, MapPolygon],
})

Then, define <map-polygon> element to show a polygon on the map. It takes the paths property, which is an array of coordinates defining the polygon's shape. Connect this property to the vertices array, which holds the polygon's coordinates.

<!-- Define center and zoom attributes in the google-map element as we did previously -->

<google-map>
  <map-polygon [paths]="vertices"></map-polygon>
</google-map>

An image showing a polygon on the map.

polygon

Implementing Ground Overlay on the Map

Ground Overlay is a feature that allows you to overlay an image onto the map, fixed to a particular geographical area defined by coordinates. We would implement this feature by adding an image to the map.

To use Ground Overlay, include MapGroundOverlay in the @Component class import list.

@Component({
  //other metadata
  imports: [GoogleMapsModule, MapGroundOverlay],
})

In the GooglemapComponent class, define two properties: image and imgBound.

  • image: This property holds the URL of the image you want to use as a custom marker icon on the map.

  • imgBound: This property sets the boundaries of the custom marker image using latitude and longitude coordinates in the form of google.maps.LatLngBoundsLiteral object.

export class GooglemapComponent {
  // center and zoom variables as previously defined

  image =
    'https://bookface-images.s3.amazonaws.com/logos/e46de9ab565d7b10514c61f2f5177850be03635b.png';
  imgBound: google.maps.LatLngBoundsLiteral = {
    east: 8,
    west: -8,
    north: 5,
    south: -5,
  };
}

Displaying the image on the map

Create a <map-ground-overlay> component to add an image overlay on the map. This component requires two attributes: [url], which defines the image URL, and [bounds], which specifies the location on the map where the image should appear based on latitude and longitude coordinates.

<!-- Define center and zoom attributes in the google-map element as we did previously -->

<google-map>
  <map-ground-overlay [url]="image" [bounds]="imgBound" />
</google-map>

Snapshot of an image placed on the map.

overlay

Adding heat map

Heat maps are a type of visual representation that displays the density or intensity of data points across a geographic area using color gradients. Hot colors like red or orange indicate higher density or intensity, whereas cool colors like blue or green represent lower density or intensity. This feature is useful in data analysis. It provides a clear and intuitive visual representation of patterns, trends, and concentrations within the data set.

To add heat maps in our Angular application, import MapHeatmapLayer within the @Component class import array.

@Component({
  //other metadata
  imports: [GoogleMapsModule, MapHeatmapLayer],
})

Next, in the GooglemapComponent class, make two variables: heatmapOptions and heatmapData.

  • heatmapOptions contains a radius that specifies the radius of each data point's influence on the heatmap.

  • heatmapData contains an array of objects, each representing a latitude and longitude coordinate pair. These coordinates are used to generate heatmap data on the map.

export class GooglemapComponent {
  // center and zoom variables as previously defined

  heatmapOptions = { radius: 10 };
  heatmapData = [
    { lat: 40.7128, lng: -74.006 },
    { lat: 40.7128, lng: -74.004 },
    { lat: 40.7128, lng: -74.002 },
    { lat: 40.7128, lng: -74.0 },
    { lat: 40.7128, lng: -73.998 },
    { lat: 40.7128, lng: -73.996 },
    { lat: 40.7128, lng: -73.994 },
    { lat: 40.715, lng: -74.006 },
    { lat: 40.715, lng: -74.004 },
    { lat: 40.715, lng: -74.002 },
    { lat: 40.715, lng: -74.0 },
    { lat: 40.715, lng: -73.998 },
    { lat: 40.715, lng: -73.996 },
    { lat: 40.715, lng: -73.994 },
  ];
}

Displaying the heat map

To display the heat map on the map, create <map-heatmap-layer> element representing a heatmap layer on the Google Map in the googlemap.component.html file. It takes two inputs: [data] and [options].

  • [data]="heatmapData": This binds the heatmapData property from the GooglemapComponent class to the data input of the map-heatmap-layer component. It provides the heatmap data to be displayed on the map.

  • [options]="heatmapOptions": This binds the heatmapOptions property from the component class to the options input of the map-heatmap-layer component. It provides configuration options for rendering the heatmap layer, such as the radius of each data point's influence.

<!-- Define center and zoom attributes in the google-map element as we did previously -->

<google-map>
  <map-heatmap-layer [data]="heatmapData" [options]="heatmapOptions" />
</google-map>

Image of the map with heat map.

heat map 2333

Conclusion

Integrating Google Maps into web applications can greatly improve user experiences and add useful features. With Google Maps API, developers can easily incorporate markers, heatmap layers, and interactive controls, making map-based interfaces intuitive and informative. Whether you're showing business locations, tracking assets, or visualizing data geographically, Google Maps offers a dependable and flexible solution.

Additional Resources