Tuesday, May 17, 2016

Angular 2: Building a Google Map Component

Live Demo
Github Repo
 
In order to force myself dig deeper into Angular 2, I tried to build a component wrapper for Google Map JavaScript API. The end results is a demo component here: google_map.component.ts.

 

Sample Client Code

A sample client code using the component looks like this:

Features

The features including:
  • Drawing through Angular binding
  • Map events published as Angular events 

 

Tips

Here are some code snippets the highlights some of the lessons I have learned.

First, make sure Google Maps library is loaded from here:
    https://maps.googleapis.com/maps/api/js?key={YOUR_API_KEY}&libraries=visualization,place&callback=initMap
Add this line in typings.ts, so that we can have type definitions for Google Maps JavaScript API
    "googlemaps": "github:DefinitelyTyped/DefinitelyTyped/googlemaps/google.maps.d.ts"
Event handlers turns out to be tricky. My naive first implementation was something like this
this.map.addListener('click', function(e: google.maps.MouseEvent) {      
  this.mapClick.emit(e.latLng));
);
Turns out there are two big problems in this implementation:
  1. this inside the event handler does not have member mapClick. Because it is no longer the component class
  2. Once scope of this is fixed, I found data changes in the event handler does not trigger Angular change detection
Solutions for those problems? See the comments in my final implementation:

On the CSS side, it is very important to set height of Google Map component. If not done, it is automatically collapsed to nothing, and you won't see a map.

Demo 

Finally, a functional demo is here: google_map.html. Below is screenshot of the demo in action:

No comments: