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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<google-map | |
[center]='center' | |
[zoom]='zoom' | |
(mapClick)='onMapClick($event)' | |
[markers]='markers' | |
[heatmapData]='heatmapData'> | |
</google-map> |
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=initMapAdd 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:
this
inside the event handler does not have membermapClick
. Because it is no longer the component class- Once scope of
this
is fixed, I found data changes in the event handler does not trigger Angular change detection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
this.map.addListener('click', | |
// Lambdas to the rescue, it will automatically capture this | |
(e: google.maps.MouseEvent) => { | |
// Run event handler in Angular Zone, so that change detection will work | |
this._ngZone.run(() => | |
this.mapClick.emit(e.latLng)); | |
}); |