Skip to content

feat(google-maps): add input options for google Map component #16759

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/dev-app/google-map/google-map-demo.html
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
<google-map *ngIf="isReady"></google-map>
<google-map *ngIf="isReady"
height="400px"
width="750px"
[center]="center"
[zoom]="zoom"></google-map>
3 changes: 3 additions & 0 deletions src/dev-app/google-map/google-map-demo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ import {HttpClient} from '@angular/common/http';
export class GoogleMapDemo {
isReady = false;

center = {lat: 24, lng: 12};
zoom = 4;

constructor(httpClient: HttpClient) {
httpClient.jsonp('https://maps.googleapis.com/maps/api/js?', 'callback')
.subscribe(() => {
Expand Down
128 changes: 116 additions & 12 deletions src/google-maps/google-map/google-map.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,18 @@ import {Component} from '@angular/core';
import {async, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';

import {createMapConstructorSpy, createMapSpy} from './testing/fake-google-map-utils';
import {GoogleMapModule} from './index';

const DEFAULT_OPTIONS: google.maps.MapOptions = {
center: {lat: 37.421995, lng: -122.084092},
zoom: 17,
};
import {DEFAULT_HEIGHT, DEFAULT_OPTIONS, DEFAULT_WIDTH, GoogleMapModule} from './index';
import {
createMapConstructorSpy,
createMapSpy,
TestingWindow
} from './testing/fake-google-map-utils';

describe('GoogleMap', () => {
let mapConstructorSpy: jasmine.Spy;
let mapSpy: jasmine.SpyObj<google.maps.Map>;

beforeEach(async(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
mapConstructorSpy = createMapConstructorSpy(mapSpy);

TestBed.configureTestingModule({
imports: [GoogleMapModule],
declarations: [TestApp],
Expand All @@ -28,17 +24,125 @@ describe('GoogleMap', () => {
TestBed.compileComponents();
});

afterEach(() => {
const testingWindow: TestingWindow = window;
delete testingWindow.google;
});

it('throws an error is the Google Maps JavaScript API was not loaded', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
mapConstructorSpy = createMapConstructorSpy(mapSpy, false);

expect(() => TestBed.createComponent(TestApp))
.toThrow(new Error(
'Namespace google not found, cannot construct embedded google ' +
'map. Please install the Google Maps JavaScript API: ' +
'https://developers.google.com/maps/documentation/javascript/' +
'tutorial#Loading_the_Maps_API'));
});

it('initializes a Google map', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
mapConstructorSpy = createMapConstructorSpy(mapSpy);

const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();

const container = fixture.debugElement.query(By.css('div'));
expect(container.nativeElement.style.height).toBe(DEFAULT_HEIGHT);
expect(container.nativeElement.style.width).toBe(DEFAULT_WIDTH);
expect(mapConstructorSpy).toHaveBeenCalledWith(container.nativeElement, DEFAULT_OPTIONS);
});

it('sets height and width of the map', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
mapConstructorSpy = createMapConstructorSpy(mapSpy);

const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.height = '750px';
fixture.componentInstance.width = '400px';
fixture.detectChanges();

const container = fixture.debugElement.query(By.css('div'));
expect(container.nativeElement.style.height).toBe('750px');
expect(container.nativeElement.style.width).toBe('400px');
expect(mapConstructorSpy).toHaveBeenCalledWith(container.nativeElement, DEFAULT_OPTIONS);

fixture.componentInstance.height = '650px';
fixture.componentInstance.width = '350px';
fixture.detectChanges();

expect(container.nativeElement.style.height).toBe('650px');
expect(container.nativeElement.style.width).toBe('350px');
});

it('sets center and zoom of the map', () => {
const options = {center: {lat: 3, lng: 5}, zoom: 7};
mapSpy = createMapSpy(options);
mapConstructorSpy = createMapConstructorSpy(mapSpy).and.callThrough();

const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.center = options.center;
fixture.componentInstance.zoom = options.zoom;
fixture.detectChanges();

const container = fixture.debugElement.query(By.css('div'));
expect(mapConstructorSpy).toHaveBeenCalledWith(container.nativeElement, options);

fixture.componentInstance.center = {lat: 8, lng: 9};
fixture.componentInstance.zoom = 12;
fixture.detectChanges();

expect(mapSpy.setOptions).toHaveBeenCalledWith({center: {lat: 8, lng: 9}, zoom: 12});
});

it('sets map options', () => {
const options = {center: {lat: 3, lng: 5}, zoom: 7, draggable: false};
mapSpy = createMapSpy(options);
mapConstructorSpy = createMapConstructorSpy(mapSpy).and.callThrough();

const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = options;
fixture.detectChanges();

const container = fixture.debugElement.query(By.css('div'));
expect(mapConstructorSpy).toHaveBeenCalledWith(container.nativeElement, options);

fixture.componentInstance.options = {...options, heading: 170};
fixture.detectChanges();

expect(mapSpy.setOptions).toHaveBeenCalledWith({...options, heading: 170});
});

it('gives precedence to center and zoom over options', () => {
const inputOptions = {center: {lat: 3, lng: 5}, zoom: 7, heading: 170};
const correctedOptions = {center: {lat: 12, lng: 15}, zoom: 5, heading: 170};
mapSpy = createMapSpy(correctedOptions);
mapConstructorSpy = createMapConstructorSpy(mapSpy);

const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.center = correctedOptions.center;
fixture.componentInstance.zoom = correctedOptions.zoom;
fixture.componentInstance.options = inputOptions;
fixture.detectChanges();

const container = fixture.debugElement.query(By.css('div'));
expect(mapConstructorSpy).toHaveBeenCalledWith(container.nativeElement, correctedOptions);
});
});

@Component({
selector: 'test-app',
template: `<google-map></google-map>`,
template: `<google-map [height]="height"
[width]="width"
[center]="center"
[zoom]="zoom"
[options]="options"></google-map>`,
})
class TestApp {}
class TestApp {
height?: string;
width?: string;
center?: google.maps.LatLngLiteral;
zoom?: number;
options?: google.maps.MapOptions;
}
126 changes: 107 additions & 19 deletions src/google-maps/google-map/google-map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,27 @@ import {
Component,
ElementRef,
Input,
OnChanges,
OnDestroy,
OnInit,
} from '@angular/core';
import {ReplaySubject} from 'rxjs';
import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs';
import {map, take, takeUntil} from 'rxjs/operators';

interface GoogleMapsWindow extends Window {
google?: typeof google;
}

/** default options set to the Googleplex */
export const DEFAULT_OPTIONS: google.maps.MapOptions = {
center: {lat: 37.421995, lng: -122.084092},
zoom: 17,
};

/** Arbitrary default height for the map element */
export const DEFAULT_HEIGHT = '500px';
/** Arbitrary default width for the map element */
export const DEFAULT_WIDTH = '500px';

/**
* Angular component that renders a Google Map via the Google Maps JavaScript
Expand All @@ -17,28 +35,98 @@ import {ReplaySubject} from 'rxjs';
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<div class="map-container"></div>',
})
export class GoogleMap implements OnInit {
// Arbitrarily chosen default size
@Input() height = '500px';
@Input() width = '500px';
export class GoogleMap implements OnChanges, OnInit, OnDestroy {
@Input() height = DEFAULT_HEIGHT;

@Input() width = DEFAULT_WIDTH;

@Input()
set center(center: google.maps.LatLngLiteral) {
this._center.next(center);
}
@Input()
set zoom(zoom: number) {
this._zoom.next(zoom);
}
@Input()
set options(options: google.maps.MapOptions) {
this._options.next(options || DEFAULT_OPTIONS);
}

// TODO(mbehrlich): Add event handlers, properties, and methods.

private _mapEl?: HTMLElement;

// TODO(mbehrlich): add options, handlers, properties, and methods.
private readonly _options = new BehaviorSubject<google.maps.MapOptions>(DEFAULT_OPTIONS);
private readonly _center = new BehaviorSubject<google.maps.LatLngLiteral|undefined>(undefined);
private readonly _zoom = new BehaviorSubject<number|undefined>(undefined);

private readonly _map$ = new ReplaySubject<google.maps.Map>(1);
private readonly _destroy = new Subject<void>();

constructor(private readonly _elementRef: ElementRef) {}
constructor(private readonly _elementRef: ElementRef) {
const googleMapsWindow: GoogleMapsWindow = window;
if (!googleMapsWindow.google) {
throw Error(
'Namespace google not found, cannot construct embedded google ' +
'map. Please install the Google Maps JavaScript API: ' +
'https://developers.google.com/maps/documentation/javascript/' +
'tutorial#Loading_the_Maps_API');
}
}

ngOnChanges() {
this._setSize();
}

ngOnInit() {
// default options set to the Googleplex
const options: google.maps.MapOptions = {
center: {lat: 37.421995, lng: -122.084092},
zoom: 17,
};

const mapEl = this._elementRef.nativeElement.querySelector('.map-container');
mapEl.style.height = this.height;
mapEl.style.width = this.width;
const map = new google.maps.Map(mapEl, options);
this._map$.next(map);
this._mapEl = this._elementRef.nativeElement.querySelector('.map-container')!;
this._setSize();

const combinedOptionsChanges = this._combineOptions();

const googleMapChanges = this._initializeMap(combinedOptionsChanges);
googleMapChanges.subscribe();

this._watchForOptionsChanges(googleMapChanges, combinedOptionsChanges);
}

private _setSize() {
if (this._mapEl) {
this._mapEl.style.height = this.height || DEFAULT_HEIGHT;
this._mapEl.style.width = this.width || DEFAULT_WIDTH;
}
}

/** Combines the center and zoom and the other map options into a single object */
private _combineOptions(): Observable<google.maps.MapOptions> {
return combineLatest(this._options, this._center, this._zoom)
.pipe(map(([options, center, zoom]) => {
const combinedOptions: google.maps.MapOptions = {
...options,
center: center || options.center,
zoom: zoom !== undefined ? zoom : options.zoom,
};
return combinedOptions;
}));
}

private _initializeMap(optionsChanges: Observable<google.maps.MapOptions>):
Observable<google.maps.Map> {
return optionsChanges.pipe(take(1), map(options => new google.maps.Map(this._mapEl!, options)));
}

private _watchForOptionsChanges(
googleMapChanges: Observable<google.maps.Map>,
optionsChanges: Observable<google.maps.MapOptions>) {
combineLatest(googleMapChanges, optionsChanges)
.pipe(takeUntil(this._destroy))
.subscribe(([googleMap, options]) => {
googleMap.setOptions(options);
});
}

ngOnDestroy() {
this._destroy.next();
this._destroy.complete();
}
}
31 changes: 17 additions & 14 deletions src/google-maps/google-map/testing/fake-google-map-utils.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,31 @@
declare global {
interface Window {
google?: {
maps: {
Map: jasmine.Spy;
};
/** Window interface for testing */
export interface TestingWindow extends Window {
google?: {
maps: {
Map: jasmine.Spy;
};
}
};
}

/** Creates a jasmine.SpyObj for a google.maps.Map. */
export function createMapSpy(options: google.maps.MapOptions): jasmine.SpyObj<google.maps.Map> {
return jasmine.createSpyObj('Map', ['getDiv']);
return jasmine.createSpyObj('google.maps.Map', ['setOptions']);
}

/** Creates a jasmine.Spy to watch for the constructor of a google.maps.Map. */
export function createMapConstructorSpy(mapSpy: jasmine.SpyObj<google.maps.Map>): jasmine.Spy {
export function createMapConstructorSpy(
mapSpy: jasmine.SpyObj<google.maps.Map>, apiLoaded = true): jasmine.Spy {
const mapConstructorSpy =
jasmine.createSpy('Map constructor', (_el: Element, _options: google.maps.MapOptions) => {
return mapSpy;
});
window.google = {
maps: {
'Map': mapConstructorSpy,
}
};
const testingWindow: TestingWindow = window;
if (apiLoaded) {
testingWindow.google = {
maps: {
'Map': mapConstructorSpy,
}
};
}
return mapConstructorSpy;
}
Loading