Angular and Google Maps: A Tutorial

Reading Time: 9 minutesIn this article you will learn how to create interactive Google Maps powered by Angular.

We will see how to:

  • instantiate the map
  • perform geocoding by address and location
  • work with markers and geocode by the marker's position
  • work with circles and programmaticaly adjust their radiuses.

The source code for this article can be found at GitHub.

Google Map

If you'd like to become an Angular expert in a few hours, then checkout ng-book: The Complete Guide to Angular. Find out why hundreds of other developers love ng-book.

Preparing the App

First things first: let's create a new Angular application by running:

I am assuming that you are using Angular 6, but most of the described concepts should apply to earlier versions as well.

Next, let's add some libraries:

  • ng-bootstrap allows us to employ Bootstrap
  • agm is the main star today — it provides all the necessary component to work with the Google Maps API

Of course, we require a separate component before starting to implement the map functionality, so generate it now:

After that make sure that everything is imported properly in the app.module.ts file:

Note that I've also imported the FormsModule because we'll rely heavily on it.

Next, perform some tweaks to the @NgModule in the same file:

Obtaining a Google API Key

Before proceeding, you will require a special Google API key that can be obtained at the Google API Dashboard. Perform the following steps:

  • Log in or register if you don't have a Google account yet
  • At the top-left corner select an already existing project or press "New Project"
  • When creating a new project, give it some name
  • Press "Enable APIs and Services" button
  • Search for the "Maps" and select the item that says "Maps for your website"
  • Then press "Manage" and switch to the "Credentials" section
  • Here you should find an API key. Note that by default this key is unrestricted, so you may want to manage it and choose what websites can utilize it

After you are done, paste the obtained key to the app.module.ts on this line:

Geocoding

Working With Component

So far so good. What I would like to do next is add an ability for the users to search for addresses and reflect them on the map. When the address is found, it should be pinpointed with a marker. Also, when the marker is moved to some location, the address of this location should be displayed.

Start by importing all the necessary modules inside the map.component.ts file, then define two interfaces and a variable:

These interfaces will allow us to easily work with the location and the marker.

Now let's define some default values for the location, and also create a view object for the AmgMap:

Then the constructor. We should wait for the mapsApiLoader to load and only after that assign geocoder with a new Geocoder object:

Also, when the component is initialized let's make our marker draggable:

Great! Let's stop here for a moment and proceed to the view in order to take care of some initial user interface.

Displaying the Map and the Form

The map itself and the marker can be displayed with special tags in the following way:

The map has the following main attributes: latitude, longtitude, and zoom. We have already defined their defaults in the map.component.ts in the previous section.

Our marker also has latitude and longtitude with the default values, as well as the markerDraggable attribute (which we set to true as you remember). On top of that, marker has a special dragEnd event that we'll flesh out in the next section.

Now let's create the form. It is going to contain a handful of fields to enter the following information about the location to search for:

  • Address line 1 and 2
  • State, province or region
  • Country
  • ZIP code

Here is the corresponding markup:

Nothing special here. Each field corresponds to one of the location attributes. When the "Search" button is clicked, the updateOnMap() method is called.

Also let's define a very simple style for our map so that it has a static height:

Before we return to the component and code the necessary methods, don't forget to render the map in the app.component.html:

Finding Location by Address

So, the method to perform the actual geocoding is called updateOnMap() and it should be called when the "Search" button is clicked. Unfortunately, things start to become a bit messy here because our geocoder object requires a full address to be provided, therefore we must properly construct it:

Next code the findLocation() method:

We are geocoding by a full address and then if the response is successfull, decompose the result. The result itself, however, might contain different data, so we must do all the heavily lifting and process them properly. Here is the final version of the findLocation() method:

We are checking for various parts of the address and store them accordingly. Then also trying to update the location and the marker position. Last but not the least is the this.map.triggerResize() line of code that resizes the map as needed. Phew!

Finding Location by Marker

The next step is to process the markerDragEnd event and search for the selected location. The method itself is quite simple:

We are reading the coordinates of the marker and then call the findAddressByCoordinates(). This method should geocode by latitude and longtitude, and then decompose the result:

Result decomposition resembles the one that we have performed in the previous section:

The address may consist of various elements, namely "street_number", "route", "locality", "administrative_area_level_1", "country", and "postal_code". We are picking all of these values and assign them to the corresponding attributes of our location.

This is it! You may now boot the application by running

Try to enter various addresses and make sure they are displayed properly. Also, try to move the marker over the map and check that the address is updated.

Drawing a Circle on the Map

Shape on Map

Before wrapping up, let's also see how we can draw a circle with a given radius on the map. To do that, we'll need to update the view in the following way:

This is going to be a blue draggable circle with a predefined radius and location (which equals to the location's latitude and longtitude). We don't have a value for the radius yet, so define it now:

Why don't we also allow this circle's radius to be customized via the form? This is quite easy to do:

The entered value is in miles, so we need to format it properly:

We are done! You may now adjust the circle's radius as needed with the help of the text field.

If you'd like to become an Angular expert in a few hours, then checkout ng-book: The Complete Guide to Angular. Find out why hundreds of other developers love ng-book.

Conclusion

In this article we have seen how to create interactive Google Map powered by Angular's magic. You have learned how to geocode by address and coordinates, how to adjust the map's locations, and also how to work with the circles on the map. Of course, there is more to the Google Maps API so I recommend checking the official docs to learn more.

That's it for today, folks! Thanks for staying with me and happy coding.

About the Author

Ilya Bodrov is personal IT tutor, author, and lecturer at Moscow Aviations Institute. His primary programming languages are Ruby, Elixir, and JavaScript. He enjoys coding, teaching people and learning new things. In his free time he tweets, participates in OpenSource projects, and plays music. You can read more of his writings on his website here