_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
components/src/cdk/clipboard/pending-copy.ts_0_2785
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* A pending copy-to-clipboard operation.
*
* The implementation of copying text to the clipboard modifies the DOM and
* forces a re-layout. This re-layout can take too long if the string is large,
* causing the execCommand('copy') to happen too long after the user clicked.
* This results in the browser refusing to copy. This object lets the
* re-layout happen in a separate tick from copying by providing a copy function
* that can be called later.
*
* Destroy must be called when no longer in use, regardless of whether `copy` is
* called.
*/
export class PendingCopy {
private _textarea: HTMLTextAreaElement | undefined;
constructor(
text: string,
private readonly _document: Document,
) {
const textarea = (this._textarea = this._document.createElement('textarea'));
const styles = textarea.style;
// Hide the element for display and accessibility. Set a fixed position so the page layout
// isn't affected. We use `fixed` with `top: 0`, because focus is moved into the textarea
// for a split second and if it's off-screen, some browsers will attempt to scroll it into view.
styles.position = 'fixed';
styles.top = styles.opacity = '0';
styles.left = '-999em';
textarea.setAttribute('aria-hidden', 'true');
textarea.value = text;
// Making the textarea `readonly` prevents the screen from jumping on iOS Safari (see #25169).
textarea.readOnly = true;
// The element needs to be inserted into the fullscreen container, if the page
// is in fullscreen mode, otherwise the browser won't execute the copy command.
(this._document.fullscreenElement || this._document.body).appendChild(textarea);
}
/** Finishes copying the text. */
copy(): boolean {
const textarea = this._textarea;
let successful = false;
try {
// Older browsers could throw if copy is not supported.
if (textarea) {
const currentFocus = this._document.activeElement as HTMLOrSVGElement | null;
textarea.select();
textarea.setSelectionRange(0, textarea.value.length);
successful = this._document.execCommand('copy');
if (currentFocus) {
currentFocus.focus();
}
}
} catch {
// Discard error.
// Initial setting of {@code successful} will represent failure here.
}
return successful;
}
/** Cleans up DOM changes used to perform the copy operation. */
destroy() {
const textarea = this._textarea;
if (textarea) {
textarea.remove();
this._textarea = undefined;
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2785,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk/clipboard/pending-copy.ts"
}
|
components/src/cdk/clipboard/clipboard.ts_0_1322
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DOCUMENT} from '@angular/common';
import {Injectable, inject} from '@angular/core';
import {PendingCopy} from './pending-copy';
/**
* A service for copying text to the clipboard.
*/
@Injectable({providedIn: 'root'})
export class Clipboard {
private readonly _document = inject(DOCUMENT);
constructor(...args: unknown[]);
constructor() {}
/**
* Copies the provided text into the user's clipboard.
*
* @param text The string to copy.
* @returns Whether the operation was successful.
*/
copy(text: string): boolean {
const pendingCopy = this.beginCopy(text);
const successful = pendingCopy.copy();
pendingCopy.destroy();
return successful;
}
/**
* Prepares a string to be copied later. This is useful for large strings
* which take too long to successfully render and be copied in the same tick.
*
* The caller must call `destroy` on the returned `PendingCopy`.
*
* @param text The string to copy.
* @returns the pending copy operation.
*/
beginCopy(text: string): PendingCopy {
return new PendingCopy(text, this._document);
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1322,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk/clipboard/clipboard.ts"
}
|
components/src/cdk/clipboard/copy-to-clipboard.spec.ts_0_4267
|
import {Component} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, tick} from '@angular/core/testing';
import {Clipboard} from './clipboard';
import {ClipboardModule} from './clipboard-module';
import {PendingCopy} from './pending-copy';
const COPY_CONTENT = 'copy content';
@Component({
selector: 'copy-to-clipboard-host',
template: `
<button
[cdkCopyToClipboard]="content"
[cdkCopyToClipboardAttempts]="attempts"
(cdkCopyToClipboardCopied)="copied($event)"></button>`,
standalone: true,
imports: [ClipboardModule],
})
class CopyToClipboardHost {
content = '';
attempts = 1;
copied = jasmine.createSpy('copied spy');
}
describe('CdkCopyToClipboard', () => {
let fixture: ComponentFixture<CopyToClipboardHost>;
let clipboard: Clipboard;
beforeEach(fakeAsync(() => {
TestBed.configureTestingModule({
imports: [ClipboardModule, CopyToClipboardHost],
});
}));
beforeEach(() => {
fixture = TestBed.createComponent(CopyToClipboardHost);
const host = fixture.componentInstance;
host.content = COPY_CONTENT;
clipboard = TestBed.inject(Clipboard);
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
});
it('copies content to clipboard upon click', () => {
spyOn(clipboard, 'copy');
fixture.nativeElement.querySelector('button')!.click();
expect(clipboard.copy).toHaveBeenCalledWith(COPY_CONTENT);
});
it('emits copied event true when copy succeeds', fakeAsync(() => {
spyOn(clipboard, 'copy').and.returnValue(true);
fixture.nativeElement.querySelector('button')!.click();
expect(fixture.componentInstance.copied).toHaveBeenCalledWith(true);
}));
it('emits copied event false when copy fails', fakeAsync(() => {
spyOn(clipboard, 'copy').and.returnValue(false);
fixture.nativeElement.querySelector('button')!.click();
tick(1);
expect(fixture.componentInstance.copied).toHaveBeenCalledWith(false);
}));
it('should be able to attempt multiple times before succeeding', fakeAsync(() => {
const maxAttempts = 3;
let attempts = 0;
spyOn(clipboard, 'beginCopy').and.returnValue({
copy: () => ++attempts >= maxAttempts,
destroy: () => {},
} as PendingCopy);
fixture.componentInstance.attempts = maxAttempts;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.nativeElement.querySelector('button')!.click();
fixture.detectChanges();
tick(3);
expect(attempts).toBe(maxAttempts);
expect(fixture.componentInstance.copied).toHaveBeenCalledTimes(1);
expect(fixture.componentInstance.copied).toHaveBeenCalledWith(true);
}));
it('should be able to attempt multiple times before failing', fakeAsync(() => {
const maxAttempts = 3;
let attempts = 0;
spyOn(clipboard, 'beginCopy').and.returnValue({
copy: () => {
attempts++;
return false;
},
destroy: () => {},
} as PendingCopy);
fixture.componentInstance.attempts = maxAttempts;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
fixture.nativeElement.querySelector('button')!.click();
fixture.detectChanges();
tick(3);
expect(attempts).toBe(maxAttempts);
expect(fixture.componentInstance.copied).toHaveBeenCalledTimes(1);
expect(fixture.componentInstance.copied).toHaveBeenCalledWith(false);
}));
it('should destroy any pending copies when the directive is destroyed', fakeAsync(() => {
const fakeCopy = {
copy: jasmine.createSpy('copy spy').and.returnValue(false) as () => boolean,
destroy: jasmine.createSpy('destroy spy') as () => void,
} as PendingCopy;
fixture.componentInstance.attempts = 10;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
spyOn(clipboard, 'beginCopy').and.returnValue(fakeCopy);
fixture.detectChanges();
fixture.nativeElement.querySelector('button')!.click();
fixture.detectChanges();
tick(1);
expect(fakeCopy.copy).toHaveBeenCalledTimes(2);
expect(fakeCopy.destroy).toHaveBeenCalledTimes(0);
fixture.destroy();
tick(1);
expect(fakeCopy.copy).toHaveBeenCalledTimes(2);
expect(fakeCopy.destroy).toHaveBeenCalledTimes(1);
}));
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 4267,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk/clipboard/copy-to-clipboard.spec.ts"
}
|
components/src/cdk/clipboard/copy-to-clipboard.ts_0_3341
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Directive,
EventEmitter,
Input,
Output,
NgZone,
InjectionToken,
OnDestroy,
inject,
} from '@angular/core';
import {Clipboard} from './clipboard';
import {PendingCopy} from './pending-copy';
/** Object that can be used to configure the default options for `CdkCopyToClipboard`. */
export interface CdkCopyToClipboardConfig {
/** Default number of attempts to make when copying text to the clipboard. */
attempts?: number;
}
/** Injection token that can be used to provide the default options to `CdkCopyToClipboard`. */
export const CDK_COPY_TO_CLIPBOARD_CONFIG = new InjectionToken<CdkCopyToClipboardConfig>(
'CDK_COPY_TO_CLIPBOARD_CONFIG',
);
/**
* Provides behavior for a button that when clicked copies content into user's
* clipboard.
*/
@Directive({
selector: '[cdkCopyToClipboard]',
host: {
'(click)': 'copy()',
},
})
export class CdkCopyToClipboard implements OnDestroy {
private _clipboard = inject(Clipboard);
private _ngZone = inject(NgZone);
/** Content to be copied. */
@Input('cdkCopyToClipboard') text: string = '';
/**
* How many times to attempt to copy the text. This may be necessary for longer text, because
* the browser needs time to fill an intermediate textarea element and copy the content.
*/
@Input('cdkCopyToClipboardAttempts') attempts: number = 1;
/**
* Emits when some text is copied to the clipboard. The
* emitted value indicates whether copying was successful.
*/
@Output('cdkCopyToClipboardCopied') readonly copied = new EventEmitter<boolean>();
/** Copies that are currently being attempted. */
private _pending = new Set<PendingCopy>();
/** Whether the directive has been destroyed. */
private _destroyed: boolean;
/** Timeout for the current copy attempt. */
private _currentTimeout: any;
constructor(...args: unknown[]);
constructor() {
const config = inject(CDK_COPY_TO_CLIPBOARD_CONFIG, {optional: true});
if (config && config.attempts != null) {
this.attempts = config.attempts;
}
}
/** Copies the current text to the clipboard. */
copy(attempts: number = this.attempts): void {
if (attempts > 1) {
let remainingAttempts = attempts;
const pending = this._clipboard.beginCopy(this.text);
this._pending.add(pending);
const attempt = () => {
const successful = pending.copy();
if (!successful && --remainingAttempts && !this._destroyed) {
// We use 1 for the timeout since it's more predictable when flushing in unit tests.
this._currentTimeout = this._ngZone.runOutsideAngular(() => setTimeout(attempt, 1));
} else {
this._currentTimeout = null;
this._pending.delete(pending);
pending.destroy();
this.copied.emit(successful);
}
};
attempt();
} else {
this.copied.emit(this._clipboard.copy(this.text));
}
}
ngOnDestroy() {
if (this._currentTimeout) {
clearTimeout(this._currentTimeout);
}
this._pending.forEach(copy => copy.destroy());
this._pending.clear();
this._destroyed = true;
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 3341,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk/clipboard/copy-to-clipboard.ts"
}
|
components/src/cdk/clipboard/public-api.ts_0_338
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './clipboard';
export * from './clipboard-module';
export * from './copy-to-clipboard';
export * from './pending-copy';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 338,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk/clipboard/public-api.ts"
}
|
components/src/cdk/clipboard/clipboard.spec.ts_0_2701
|
import {DOCUMENT} from '@angular/common';
import {TestBed} from '@angular/core/testing';
import {Clipboard} from './clipboard';
import {PendingCopy} from './pending-copy';
const COPY_CONTENT = 'copy content';
describe('Clipboard', () => {
let clipboard: Clipboard;
let execCommand: jasmine.Spy;
let document: Document;
let body: HTMLElement;
let focusedInput: HTMLElement;
beforeEach(() => {
TestBed.configureTestingModule({});
clipboard = TestBed.inject(Clipboard);
document = TestBed.inject(DOCUMENT);
execCommand = spyOn(document, 'execCommand').and.returnValue(true);
body = document.body;
focusedInput = document.createElement('input');
body.appendChild(focusedInput);
focusedInput.focus();
});
afterEach(() => {
focusedInput.remove();
});
describe('#beginCopy', () => {
let pendingCopy: PendingCopy;
beforeEach(() => {
pendingCopy = clipboard.beginCopy(COPY_CONTENT);
});
afterEach(() => {
pendingCopy.destroy();
});
it('loads the copy content in textarea', () => {
expect(body.querySelector('textarea')!.value).toBe(COPY_CONTENT);
});
it('removes the textarea after destroy()', () => {
pendingCopy.destroy();
expect(body.querySelector('textarea')).toBeNull();
});
});
describe('#copy', () => {
it('returns true when execCommand succeeds', () => {
expect(clipboard.copy(COPY_CONTENT)).toBe(true);
expect(body.querySelector('textarea')).toBeNull();
});
it('does not move focus away from focused element', () => {
expect(clipboard.copy(COPY_CONTENT)).toBe(true);
expect(document.activeElement).toBe(focusedInput);
});
it('does not move focus away from focused SVG element', () => {
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svg.setAttribute('focusable', 'true');
svg.setAttribute('tabindex', '0');
document.body.appendChild(svg);
svg.focus();
expect(document.activeElement).toBe(svg);
clipboard.copy(COPY_CONTENT);
expect(document.activeElement).toBe(svg);
svg.remove();
});
describe('when execCommand fails', () => {
beforeEach(() => {
execCommand.and.throwError('could not copy');
});
it('returns false', () => {
expect(clipboard.copy(COPY_CONTENT)).toBe(false);
});
it('removes the text area', () => {
expect(body.querySelector('textarea')).toBeNull();
});
});
it('returns false when execCommand returns false', () => {
execCommand.and.returnValue(false);
expect(clipboard.copy(COPY_CONTENT)).toBe(false);
});
});
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2701,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk/clipboard/clipboard.spec.ts"
}
|
components/src/cdk/clipboard/clipboard.md_0_2191
|
The clipboard package provides helpers for working with the system clipboard.
### Click an element to copy
The `cdkCopyToClipboard` directive can be used to easily add copy-on-click functionality to an
existing element. The directive selector doubles as an `@Input()` for the text to be copied.
```html
<img src="avatar.jpg" alt="Hero avatar" [cdkCopyToClipboard]="getShortBio()">
```
<!-- example(cdk-clipboard-overview) -->
### Programmatically copy a string
The `Clipboard` service copies text to the user's clipboard. It has two methods: `copy` and
`beginCopy`. For cases where you are copying a relatively small amount of text, you can call `copy`
directly to place it on the clipboard.
```typescript
import {Clipboard} from '@angular/cdk/clipboard';
class HeroProfile {
constructor(private clipboard: Clipboard) {}
copyHeroName() {
this.clipboard.copy('Alphonso');
}
}
```
However, for longer text the browser needs time to fill an intermediate textarea element and copy
the content. Directly calling `copy` may fail in this case, so you can pre-load the text by calling
`beginCopy`. This method returns a `PendingCopy` object that has a `copy` method to finish copying
the text that was buffered. Please note, if you call `beginCopy`, you must clean up the
`PendingCopy` object by calling `destroy` on it after you are finished.
```typescript
import {Clipboard} from '@angular/cdk/clipboard';
class HeroProfile {
lifetimeAchievements: string;
constructor(private clipboard: Clipboard) {}
copyAchievements() {
const pending = this.clipboard.beginCopy(this.lifetimeAchievements);
let remainingAttempts = 3;
const attempt = () => {
const result = pending.copy();
if (!result && --remainingAttempts) {
setTimeout(attempt);
} else {
// Remember to destroy when you're done!
pending.destroy();
}
};
attempt();
}
}
```
If you're using the `cdkCopyToClipboard` you can pass in the `cdkCopyToClipboardAttempts` input
to automatically attempt to copy some text a certain number of times.
```html
<button [cdkCopyToClipboard]="longText" [cdkCopyToClipboardAttempts]="5">Copy text</button>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2191,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk/clipboard/clipboard.md"
}
|
components/src/cdk/clipboard/BUILD.bazel_0_932
|
load("//tools:defaults.bzl", "markdown_to_html", "ng_module", "ng_test_library", "ng_web_test_suite")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "clipboard",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
assets = glob(["**/*.html"]),
deps = [
"@npm//@angular/common",
"@npm//@angular/core",
"@npm//rxjs",
],
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":clipboard",
"//src/cdk/testing",
"@npm//@angular/common",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
markdown_to_html(
name = "overview",
srcs = [":clipboard.md"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 932,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk/clipboard/BUILD.bazel"
}
|
components/src/cdk/clipboard/clipboard-module.ts_0_415
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {CdkCopyToClipboard} from './copy-to-clipboard';
@NgModule({
imports: [CdkCopyToClipboard],
exports: [CdkCopyToClipboard],
})
export class ClipboardModule {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 415,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk/clipboard/clipboard-module.ts"
}
|
components/src/cdk/clipboard/index.ts_0_234
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/cdk/clipboard/index.ts"
}
|
components/src/google-maps/map-anchor-point.ts_0_450
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
export interface MapAnchorPoint {
getAnchor(): google.maps.MVCObject | google.maps.marker.AdvancedMarkerElement;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 450,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-anchor-point.ts"
}
|
components/src/google-maps/google-maps-module.ts_0_1912
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgModule} from '@angular/core';
import {GoogleMap} from './google-map/google-map';
import {MapBaseLayer} from './map-base-layer';
import {MapBicyclingLayer} from './map-bicycling-layer/map-bicycling-layer';
import {MapCircle} from './map-circle/map-circle';
import {MapDirectionsRenderer} from './map-directions-renderer/map-directions-renderer';
import {MapGroundOverlay} from './map-ground-overlay/map-ground-overlay';
import {MapInfoWindow} from './map-info-window/map-info-window';
import {MapKmlLayer} from './map-kml-layer/map-kml-layer';
import {MapMarker} from './map-marker/map-marker';
import {DeprecatedMapMarkerClusterer} from './deprecated-map-marker-clusterer/deprecated-map-marker-clusterer';
import {MapPolygon} from './map-polygon/map-polygon';
import {MapPolyline} from './map-polyline/map-polyline';
import {MapRectangle} from './map-rectangle/map-rectangle';
import {MapTrafficLayer} from './map-traffic-layer/map-traffic-layer';
import {MapTransitLayer} from './map-transit-layer/map-transit-layer';
import {MapHeatmapLayer} from './map-heatmap-layer/map-heatmap-layer';
import {MapAdvancedMarker} from './map-advanced-marker/map-advanced-marker';
import {MapMarkerClusterer} from './map-marker-clusterer/map-marker-clusterer';
const COMPONENTS = [
GoogleMap,
MapBaseLayer,
MapBicyclingLayer,
MapCircle,
MapDirectionsRenderer,
MapGroundOverlay,
MapHeatmapLayer,
MapInfoWindow,
MapKmlLayer,
MapMarker,
MapAdvancedMarker,
DeprecatedMapMarkerClusterer,
MapPolygon,
MapPolyline,
MapRectangle,
MapTrafficLayer,
MapTransitLayer,
MapMarkerClusterer,
];
@NgModule({
imports: COMPONENTS,
exports: COMPONENTS,
})
export class GoogleMapsModule {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1912,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/google-maps-module.ts"
}
|
components/src/google-maps/map-event-manager.ts_0_3067
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NgZone} from '@angular/core';
import {BehaviorSubject, Observable, Subscriber} from 'rxjs';
import {switchMap} from 'rxjs/operators';
type MapEventManagerTarget =
| {
addListener: (
name: string,
callback: (...args: any[]) => void,
) => google.maps.MapsEventListener | undefined;
}
| undefined;
/** Manages event on a Google Maps object, ensuring that events are added only when necessary. */
export class MapEventManager {
/** Pending listeners that were added before the target was set. */
private _pending: {observable: Observable<any>; observer: Subscriber<any>}[] = [];
private _listeners: google.maps.MapsEventListener[] = [];
private _targetStream = new BehaviorSubject<MapEventManagerTarget>(undefined);
/** Clears all currently-registered event listeners. */
private _clearListeners() {
for (const listener of this._listeners) {
listener.remove();
}
this._listeners = [];
}
constructor(private _ngZone: NgZone) {}
/** Gets an observable that adds an event listener to the map when a consumer subscribes to it. */
getLazyEmitter<T>(name: string): Observable<T> {
return this._targetStream.pipe(
switchMap(target => {
const observable = new Observable<T>(observer => {
// If the target hasn't been initialized yet, cache the observer so it can be added later.
if (!target) {
this._pending.push({observable, observer});
return undefined;
}
const listener = target.addListener(name, (event: T) => {
this._ngZone.run(() => observer.next(event));
});
// If there's an error when initializing the Maps API (e.g. a wrong API key), it will
// return a dummy object that returns `undefined` from `addListener` (see #26514).
if (!listener) {
observer.complete();
return undefined;
}
this._listeners.push(listener);
return () => listener.remove();
});
return observable;
}),
);
}
/** Sets the current target that the manager should bind events to. */
setTarget(target: MapEventManagerTarget) {
const currentTarget = this._targetStream.value;
if (target === currentTarget) {
return;
}
// Clear the listeners from the pre-existing target.
if (currentTarget) {
this._clearListeners();
this._pending = [];
}
this._targetStream.next(target);
// Add the listeners that were bound before the map was initialized.
this._pending.forEach(subscriber => subscriber.observable.subscribe(subscriber.observer));
this._pending = [];
}
/** Destroys the manager and clears the event listeners. */
destroy() {
this._clearListeners();
this._pending = [];
this._targetStream.complete();
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 3067,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-event-manager.ts"
}
|
components/src/google-maps/public-api.ts_0_2017
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export {GoogleMap} from './google-map/google-map';
export {GoogleMapsModule} from './google-maps-module';
export {MapAnchorPoint} from './map-anchor-point';
export {MapBaseLayer} from './map-base-layer';
export {MapBicyclingLayer} from './map-bicycling-layer/map-bicycling-layer';
export {MapCircle} from './map-circle/map-circle';
export {MapDirectionsRenderer} from './map-directions-renderer/map-directions-renderer';
export {
MapDirectionsService,
MapDirectionsResponse,
} from './map-directions-renderer/map-directions-service';
export {MapGroundOverlay} from './map-ground-overlay/map-ground-overlay';
export {MapInfoWindow} from './map-info-window/map-info-window';
export {MapKmlLayer} from './map-kml-layer/map-kml-layer';
export {MapMarker} from './map-marker/map-marker';
export {MapAdvancedMarker} from './map-advanced-marker/map-advanced-marker';
export {DeprecatedMapMarkerClusterer} from './deprecated-map-marker-clusterer/deprecated-map-marker-clusterer';
export {MapMarkerClusterer} from './map-marker-clusterer/map-marker-clusterer';
export * from './map-marker-clusterer/map-marker-clusterer-types';
export {MapPolygon} from './map-polygon/map-polygon';
export {MapPolyline} from './map-polyline/map-polyline';
export {MapRectangle} from './map-rectangle/map-rectangle';
export {MapTrafficLayer} from './map-traffic-layer/map-traffic-layer';
export {MapTransitLayer} from './map-transit-layer/map-transit-layer';
export {MapHeatmapLayer, HeatmapData} from './map-heatmap-layer/map-heatmap-layer';
export {MapGeocoder, MapGeocoderResponse} from './map-geocoder/map-geocoder';
export {
MarkerClustererOptions,
ClusterIconStyle,
AriaLabelFn,
Calculator,
} from './deprecated-map-marker-clusterer/deprecated-marker-clusterer-types';
export {MapEventManager} from './map-event-manager';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2017,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/public-api.ts"
}
|
components/src/google-maps/map-event-manager.spec.ts_0_5960
|
import {type NgZone} from '@angular/core';
import {MapEventManager} from './map-event-manager';
describe('MapEventManager', () => {
let dummyZone: NgZone;
let manager: MapEventManager;
let target: TestEventTarget;
beforeEach(() => {
dummyZone = {
run: jasmine.createSpy('NgZone.run').and.callFake((callback: () => void) => callback()),
} as unknown as NgZone;
target = new TestEventTarget();
manager = new MapEventManager(dummyZone);
});
afterEach(() => {
manager.destroy();
});
it('should register a listener when subscribing to an event', () => {
expect(target.addListener).not.toHaveBeenCalled();
manager.setTarget(target);
const stream = manager.getLazyEmitter('click');
expect(target.addListener).not.toHaveBeenCalled();
expect(target.events.get('click')).toBeFalsy();
const subscription = stream.subscribe();
expect(target.addListener).toHaveBeenCalledTimes(1);
expect(target.events.get('click')?.size).toBe(1);
subscription.unsubscribe();
});
it('should register a listener if the subscription happened before there was a target', () => {
const stream = manager.getLazyEmitter('click');
const subscription = stream.subscribe();
expect(target.addListener).not.toHaveBeenCalled();
expect(target.events.get('click')).toBeFalsy();
manager.setTarget(target);
expect(target.addListener).toHaveBeenCalledTimes(1);
expect(target.events.get('click')?.size).toBe(1);
subscription.unsubscribe();
});
it('should remove the listener when unsubscribing', () => {
const stream = manager.getLazyEmitter('click');
const subscription = stream.subscribe();
manager.setTarget(target);
expect(target.events.get('click')?.size).toBe(1);
subscription.unsubscribe();
expect(target.events.get('click')?.size).toBe(0);
});
it('should remove the listener when the manager is destroyed', () => {
const stream = manager.getLazyEmitter('click');
stream.subscribe();
manager.setTarget(target);
expect(target.events.get('click')?.size).toBe(1);
manager.destroy();
expect(target.events.get('click')?.size).toBe(0);
});
it('should remove the listener when the target is changed', () => {
const stream = manager.getLazyEmitter('click');
stream.subscribe();
manager.setTarget(target);
expect(target.events.get('click')?.size).toBe(1);
manager.setTarget(undefined);
expect(target.events.get('click')?.size).toBe(0);
});
it('should trigger the subscription to an event', () => {
const spy = jasmine.createSpy('subscription');
const stream = manager.getLazyEmitter('click');
stream.subscribe(spy);
manager.setTarget(target);
expect(spy).not.toHaveBeenCalled();
target.triggerListeners('click');
expect(spy).toHaveBeenCalledTimes(1);
});
it('should be able to register multiple listeners to the same event', () => {
const firstSpy = jasmine.createSpy('subscription one');
const secondSpy = jasmine.createSpy('subscription two');
const stream = manager.getLazyEmitter('click');
manager.setTarget(target);
stream.subscribe(firstSpy);
stream.subscribe(secondSpy);
expect(firstSpy).not.toHaveBeenCalled();
expect(secondSpy).not.toHaveBeenCalled();
expect(target.events.get('click')?.size).toBe(2);
target.triggerListeners('click');
expect(firstSpy).toHaveBeenCalledTimes(1);
expect(secondSpy).toHaveBeenCalledTimes(1);
});
it('should run listeners inside the NgZone', () => {
const spy = jasmine.createSpy('subscription');
const stream = manager.getLazyEmitter('click');
stream.subscribe(spy);
manager.setTarget(target);
expect(dummyZone.run).not.toHaveBeenCalled();
target.triggerListeners('click');
expect(dummyZone.run).toHaveBeenCalledTimes(1);
});
it('should maintain subscriptions when swapping out targets', () => {
const spy = jasmine.createSpy('subscription');
const stream = manager.getLazyEmitter('click');
stream.subscribe(spy);
manager.setTarget(target);
expect(spy).not.toHaveBeenCalled();
target.triggerListeners('click');
expect(spy).toHaveBeenCalledTimes(1);
const alternateTarget = new TestEventTarget();
manager.setTarget(alternateTarget);
expect(spy).toHaveBeenCalledTimes(1);
expect(target.events.get('click')?.size).toBe(0);
expect(alternateTarget.events.get('click')?.size).toBe(1);
alternateTarget.triggerListeners('click');
expect(spy).toHaveBeenCalledTimes(2);
manager.setTarget(undefined);
expect(alternateTarget.events.get('click')?.size).toBe(0);
alternateTarget.triggerListeners('click');
expect(spy).toHaveBeenCalledTimes(2);
});
it('should not throw with an invalid target', () => {
manager.setTarget({
addListener: () => undefined,
});
const stream = manager.getLazyEmitter('click');
const completeSpy = jasmine.createSpy('completeSpy');
const errorSpy = jasmine.createSpy('errorSpy');
stream.subscribe({complete: completeSpy, error: errorSpy});
expect(() => manager.destroy()).not.toThrow();
expect(completeSpy).toHaveBeenCalled();
expect(errorSpy).not.toHaveBeenCalled();
});
});
/** Imitates a Google Maps event target and keeps track of the registered events. */
class TestEventTarget {
events = new Map<string, Set<() => void>>();
addListener = jasmine
.createSpy('addListener')
.and.callFake((name: string, listener: () => void) => {
if (!this.events.has(name)) {
this.events.set(name, new Set());
}
this.events.get(name)!.add(listener);
return {remove: () => this.events.get(name)!.delete(listener)};
});
triggerListeners(name: string) {
const listeners = this.events.get(name);
if (!listeners) {
throw Error(`No listeners registered for "${name}" event.`);
}
listeners.forEach(listener => listener());
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 5960,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-event-manager.spec.ts"
}
|
components/src/google-maps/README.md_0_3632
|
# Angular Google Maps component
This component provides a Google Maps Angular component that implements the
[Google Maps JavaScript API](https://developers.google.com/maps/documentation/javascript/tutorial).
File any bugs against the [angular/components repo](https://github.com/angular/components/issues).
## Installation
To install, run `ng add @angular/google-maps`.
## Getting the API Key
Follow [these steps](https://developers.google.com/maps/gmp-get-started) to get an API key that can be used to load Google Maps.
## Loading the API
Include the [Dynamic Library Import script](https://developers.google.com/maps/documentation/javascript/load-maps-js-api#dynamic-library-import) in the `index.html` of your app. When a Google Map is being rendered, it'll use the Dynamic Import API to load the necessary JavaScript automatically.
```html
<!-- index.html -->
<!DOCTYPE html>
<body>
...
<script>
(g=>{var h,a,k,p="The Google Maps JavaScript API",c="google",l="importLibrary",q="__ib__",m=document,b=window;b=b[c]||(b[c]={});var d=b.maps||(b.maps={}),r=new Set,e=new URLSearchParams,u=()=>h||(h=new Promise(async(f,n)=>{await (a=m.createElement("script"));e.set("libraries",[...r]+"");for(k in g)e.set(k.replace(/[A-Z]/g,t=>"_"+t[0].toLowerCase()),g[k]);e.set("callback",c+".maps."+q);a.src=`https://maps.${c}apis.com/maps/api/js?`+e;d[q]=f;a.onerror=()=>h=n(Error(p+" could not load."));a.nonce=m.querySelector("script[nonce]")?.nonce||"";m.head.append(a)}));d[l]?console.warn(p+" only loads once. Ignoring:",g):d[l]=(f,...n)=>r.add(f)&&u().then(()=>d[l](f,...n))})({
v: "weekly",
key: YOUR_API_KEY_GOES_HERE
});
</script>
</body>
</html>
```
**Note:** the component also supports loading the API using the [legacy script tag](https://developers.google.com/maps/documentation/javascript/load-maps-js-api#use-legacy-tag), however it isn't recommended because it requires all of the Google Maps JavaScript to be loaded up-front, even if it isn't used.
## Components
- [`GoogleMap`](./google-map/README.md)
- [`MapMarker`](./map-marker/README.md)
- [`MapInfoWindow`](./map-info-window/README.md)
- [`MapPolyline`](./map-polyline/README.md)
- [`MapPolygon`](./map-polygon/README.md)
- [`MapRectangle`](./map-rectangle/README.md)
- [`MapCircle`](./map-circle/README.md)
- [`MapGroundOverlay`](./map-ground-overlay/README.md)
- [`MapKmlLayer`](./map-kml-layer/README.md)
- [`MapTrafficLayer`](./map-traffic-layer/README.md)
- [`MapTransitLayer`](./map-transit-layer/README.md)
- [`MapBicyclingLayer`](./map-bicycling-layer/README.md)
- [`MapDirectionsRenderer`](./map-directions-renderer/README.md)
- [`MapHeatmapLayer`](./map-heatmap-layer/README.md)
## Services
- [`MapGeocoder`](./map-geocoder/README.md)
## The Options Input
The Google Maps components implement all of the options for their respective objects from the
Google Maps JavaScript API through an `options` input, but they also have specific inputs for some
of the most common options. For example, the Google Maps component could have its options set either
in with a google.maps.MapOptions object:
```html
<google-map [options]="options" />
```
```typescript
options: google.maps.MapOptions = {
center: {lat: 40, lng: -20},
zoom: 4
};
```
It can also have individual options set for some of the most common options:
```html
<google-map [center]="center" [zoom]="zoom" />
```
```typescript
center: google.maps.LatLngLiteral = {lat: 40, lng: -20};
zoom = 4;
```
Not every option has its own input. See the API for each component to see if the option has a
dedicated input or if it should be set in the options input.
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 3632,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/README.md"
}
|
components/src/google-maps/marker-utilities.ts_0_698
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {InjectionToken} from '@angular/core';
/** Marker types from the Google Maps API. */
export type Marker = google.maps.Marker | google.maps.marker.AdvancedMarkerElement;
/** Interface that should be implemented by directives that wrap marker APIs. */
export interface MarkerDirective {
_resolveMarker(): Promise<Marker>;
}
/** Token that marker directives can use to expose themselves to the clusterer. */
export const MAP_MARKER = new InjectionToken<MarkerDirective>('MAP_MARKER');
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 698,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/marker-utilities.ts"
}
|
components/src/google-maps/BUILD.bazel_0_1147
|
load("//tools:defaults.bzl", "ng_module", "ng_package", "ng_test_library", "ng_web_test_suite")
package(default_visibility = ["//visibility:public"])
ng_module(
name = "google-maps",
srcs = glob(
["**/*.ts"],
exclude = [
"**/*.spec.ts",
],
),
deps = [
"//src:dev_mode_types",
"@npm//@angular/common",
"@npm//@angular/core",
"@npm//@types/google.maps",
"@npm//rxjs",
],
)
# Creates the @angular/google-maps package published to npm
ng_package(
name = "npm_package",
srcs = ["package.json"],
nested_packages = ["//src/google-maps/schematics:npm_package"],
tags = ["release-package"],
deps = [":google-maps"],
)
filegroup(
name = "source-files",
srcs = glob(["**/*.ts"]),
)
ng_test_library(
name = "unit_test_sources",
srcs = glob(
["**/*.spec.ts"],
exclude = ["**/*.e2e.spec.ts"],
),
deps = [
":google-maps",
"//src/google-maps/testing",
"@npm//@angular/platform-browser",
],
)
ng_web_test_suite(
name = "unit_tests",
deps = [":unit_test_sources"],
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1147,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/BUILD.bazel"
}
|
components/src/google-maps/index.ts_0_234
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './public-api';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 234,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/index.ts"
}
|
components/src/google-maps/map-base-layer.ts_0_1350
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {Directive, NgZone, OnDestroy, OnInit, inject} from '@angular/core';
import {GoogleMap} from './google-map/google-map';
@Directive({
selector: 'map-base-layer',
exportAs: 'mapBaseLayer',
})
export class MapBaseLayer implements OnInit, OnDestroy {
protected readonly _map = inject(GoogleMap);
protected readonly _ngZone = inject(NgZone);
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (this._map._isBrowser) {
this._ngZone.runOutsideAngular(() => {
this._initializeObject();
});
this._assertInitialized();
this._setMap();
}
}
ngOnDestroy() {
this._unsetMap();
}
private _assertInitialized() {
if (!this._map.googleMap) {
throw Error(
'Cannot access Google Map information before the API has been initialized. ' +
'Please wait for the API to load before trying to interact with it.',
);
}
}
protected _initializeObject() {}
protected _setMap() {}
protected _unsetMap() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1350,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-base-layer.ts"
}
|
components/src/google-maps/map-rectangle/README.md_0_898
|
# MapRectangle
The `MapRectangle` component wraps the [`google.maps.Rectangle` class](https://developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle) from the Google Maps JavaScript API.
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapRectangle} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapRectangle],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
bounds: google.maps.LatLngBoundsLiteral = {
east: 10,
north: 10,
south: -10,
west: -10,
};
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map height="400px" width="750px" [center]="center" [zoom]="zoom">
<map-rectangle [bounds]="bounds" />
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 898,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-rectangle/README.md"
}
|
components/src/google-maps/map-rectangle/map-rectangle.spec.ts_0_6113
|
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createMapConstructorSpy,
createMapSpy,
createRectangleConstructorSpy,
createRectangleSpy,
} from '../testing/fake-google-map-utils';
import {MapRectangle} from './map-rectangle';
describe('MapRectangle', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
let rectangleBounds: google.maps.LatLngBoundsLiteral;
let rectangleOptions: google.maps.RectangleOptions;
beforeEach(() => {
rectangleBounds = {east: 30, north: 15, west: 10, south: -5};
rectangleOptions = {bounds: rectangleBounds, strokeColor: 'grey', strokeOpacity: 0.8};
});
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map Rectangle', fakeAsync(() => {
const rectangleSpy = createRectangleSpy({});
const rectangleConstructorSpy = createRectangleConstructorSpy(rectangleSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(rectangleConstructorSpy).toHaveBeenCalledWith({bounds: undefined});
expect(rectangleSpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
it('sets bounds from input', fakeAsync(() => {
const bounds: google.maps.LatLngBoundsLiteral = {east: 3, north: 5, west: -3, south: -5};
const options: google.maps.RectangleOptions = {bounds};
const rectangleSpy = createRectangleSpy(options);
const rectangleConstructorSpy = createRectangleConstructorSpy(rectangleSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.bounds = bounds;
fixture.detectChanges();
flush();
expect(rectangleConstructorSpy).toHaveBeenCalledWith(options);
}));
it('gives precedence to bounds input over options', fakeAsync(() => {
const bounds: google.maps.LatLngBoundsLiteral = {east: 3, north: 5, west: -3, south: -5};
const expectedOptions: google.maps.RectangleOptions = {...rectangleOptions, bounds};
const rectangleSpy = createRectangleSpy(expectedOptions);
const rectangleConstructorSpy = createRectangleConstructorSpy(rectangleSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = rectangleOptions;
fixture.componentInstance.bounds = bounds;
fixture.detectChanges();
flush();
expect(rectangleConstructorSpy).toHaveBeenCalledWith(expectedOptions);
}));
it('exposes methods that provide information about the Rectangle', fakeAsync(() => {
const rectangleSpy = createRectangleSpy(rectangleOptions);
createRectangleConstructorSpy(rectangleSpy);
const fixture = TestBed.createComponent(TestApp);
const rectangleComponent = fixture.debugElement
.query(By.directive(MapRectangle))!
.injector.get<MapRectangle>(MapRectangle);
fixture.detectChanges();
flush();
rectangleComponent.getBounds();
expect(rectangleSpy.getBounds).toHaveBeenCalled();
rectangleSpy.getDraggable.and.returnValue(true);
expect(rectangleComponent.getDraggable()).toBe(true);
rectangleSpy.getEditable.and.returnValue(true);
expect(rectangleComponent.getEditable()).toBe(true);
rectangleSpy.getVisible.and.returnValue(true);
expect(rectangleComponent.getVisible()).toBe(true);
}));
it('initializes Rectangle event handlers', fakeAsync(() => {
const rectangleSpy = createRectangleSpy(rectangleOptions);
createRectangleConstructorSpy(rectangleSpy);
const addSpy = rectangleSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).toHaveBeenCalledWith('bounds_changed', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('click', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dblclick', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('drag', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragend', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragstart', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mousedown', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mousemove', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseout', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseover', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseup', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('rightclick', jasmine.any(Function));
}));
it('should be able to add an event listener after init', fakeAsync(() => {
const rectangleSpy = createRectangleSpy(rectangleOptions);
createRectangleConstructorSpy(rectangleSpy);
const addSpy = rectangleSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).not.toHaveBeenCalledWith('dragend', jasmine.any(Function));
// Pick an event that isn't bound in the template.
const subscription = fixture.componentInstance.rectangle.rectangleDragend.subscribe();
fixture.detectChanges();
expect(addSpy).toHaveBeenCalledWith('dragend', jasmine.any(Function));
subscription.unsubscribe();
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-rectangle
[options]="options"
[bounds]="bounds"
(boundsChanged)="handleBoundsChange()"
(rectangleClick)="handleClick()"
(rectangleRightclick)="handleRightclick()" />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapRectangle],
})
class TestApp {
@ViewChild(MapRectangle) rectangle: MapRectangle;
options?: google.maps.RectangleOptions;
bounds?: google.maps.LatLngBoundsLiteral;
handleBoundsChange() {}
handleClick() {}
handleRightclick() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 6113,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-rectangle/map-rectangle.spec.ts"
}
|
components/src/google-maps/map-rectangle/map-rectangle.ts_0_8994
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Directive,
Input,
OnDestroy,
OnInit,
Output,
NgZone,
inject,
EventEmitter,
} from '@angular/core';
import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs';
import {map, take, takeUntil} from 'rxjs/operators';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
/**
* Angular component that renders a Google Maps Rectangle via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle
*/
@Directive({
selector: 'map-rectangle',
exportAs: 'mapRectangle',
})
export class MapRectangle implements OnInit, OnDestroy {
private readonly _map = inject(GoogleMap);
private readonly _ngZone = inject(NgZone);
private _eventManager = new MapEventManager(inject(NgZone));
private readonly _options = new BehaviorSubject<google.maps.RectangleOptions>({});
private readonly _bounds = new BehaviorSubject<
google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral | undefined
>(undefined);
private readonly _destroyed = new Subject<void>();
/**
* The underlying google.maps.Rectangle object.
*
* See developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle
*/
rectangle?: google.maps.Rectangle;
@Input()
set options(options: google.maps.RectangleOptions) {
this._options.next(options || {});
}
@Input()
set bounds(bounds: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral) {
this._bounds.next(bounds);
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.boundsChanged
*/ @Output() readonly boundsChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('bounds_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.click
*/
@Output() readonly rectangleClick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('click');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.dblclick
*/
@Output() readonly rectangleDblclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dblclick');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.drag
*/
@Output() readonly rectangleDrag: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('drag');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.dragend
*/
@Output() readonly rectangleDragend: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragend');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.dragstart
*/
@Output() readonly rectangleDragstart: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragstart');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.mousedown
*/
@Output() readonly rectangleMousedown: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mousedown');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.mousemove
*/
@Output() readonly rectangleMousemove: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mousemove');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.mouseout
*/
@Output() readonly rectangleMouseout: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseout');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.mouseover
*/
@Output() readonly rectangleMouseover: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseover');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.mouseup
*/
@Output() readonly rectangleMouseup: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseup');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.rightclick
*/
@Output() readonly rectangleRightclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('rightclick');
/** Event emitted when the rectangle is initialized. */
@Output() readonly rectangleInitialized: EventEmitter<google.maps.Rectangle> =
new EventEmitter<google.maps.Rectangle>();
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (this._map._isBrowser) {
this._combineOptions()
.pipe(take(1))
.subscribe(options => {
if (google.maps.Rectangle && this._map.googleMap) {
this._initialize(this._map.googleMap, google.maps.Rectangle, options);
} else {
this._ngZone.runOutsideAngular(() => {
Promise.all([this._map._resolveMap(), google.maps.importLibrary('maps')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.MapsLibrary).Rectangle, options);
},
);
});
}
});
}
}
private _initialize(
map: google.maps.Map,
rectangleConstructor: typeof google.maps.Rectangle,
options: google.maps.RectangleOptions,
) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.rectangle = new rectangleConstructor(options);
this._assertInitialized();
this.rectangle.setMap(map);
this._eventManager.setTarget(this.rectangle);
this.rectangleInitialized.emit(this.rectangle);
this._watchForOptionsChanges();
this._watchForBoundsChanges();
});
}
ngOnDestroy() {
this._eventManager.destroy();
this._destroyed.next();
this._destroyed.complete();
this.rectangle?.setMap(null);
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.getBounds
*/
getBounds(): google.maps.LatLngBounds | null {
this._assertInitialized();
return this.rectangle.getBounds();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.getDraggable
*/
getDraggable(): boolean {
this._assertInitialized();
return this.rectangle.getDraggable();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.getEditable
*/
getEditable(): boolean {
this._assertInitialized();
return this.rectangle.getEditable();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Rectangle.getVisible
*/
getVisible(): boolean {
this._assertInitialized();
return this.rectangle.getVisible();
}
private _combineOptions(): Observable<google.maps.RectangleOptions> {
return combineLatest([this._options, this._bounds]).pipe(
map(([options, bounds]) => {
const combinedOptions: google.maps.RectangleOptions = {
...options,
bounds: bounds || options.bounds,
};
return combinedOptions;
}),
);
}
private _watchForOptionsChanges() {
this._options.pipe(takeUntil(this._destroyed)).subscribe(options => {
this._assertInitialized();
this.rectangle.setOptions(options);
});
}
private _watchForBoundsChanges() {
this._bounds.pipe(takeUntil(this._destroyed)).subscribe(bounds => {
if (bounds) {
this._assertInitialized();
this.rectangle.setBounds(bounds);
}
});
}
private _assertInitialized(): asserts this is {rectangle: google.maps.Rectangle} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.rectangle) {
throw Error(
'Cannot interact with a Google Map Rectangle before it has been initialized. ' +
'Please wait for the Rectangle to load before trying to interact with it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 8994,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-rectangle/map-rectangle.ts"
}
|
components/src/google-maps/map-heatmap-layer/map-heatmap-layer.ts_0_6600
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Input,
OnDestroy,
OnInit,
NgZone,
Directive,
OnChanges,
SimpleChanges,
Output,
EventEmitter,
inject,
} from '@angular/core';
import {GoogleMap} from '../google-map/google-map';
/** Possible data that can be shown on a heatmap layer. */
export type HeatmapData =
| google.maps.MVCArray<
google.maps.LatLng | google.maps.visualization.WeightedLocation | google.maps.LatLngLiteral
>
| (google.maps.LatLng | google.maps.visualization.WeightedLocation | google.maps.LatLngLiteral)[];
/**
* Angular directive that renders a Google Maps heatmap via the Google Maps JavaScript API.
*
* See: https://developers.google.com/maps/documentation/javascript/reference/visualization
*/
@Directive({
selector: 'map-heatmap-layer',
exportAs: 'mapHeatmapLayer',
})
export class MapHeatmapLayer implements OnInit, OnChanges, OnDestroy {
private readonly _googleMap = inject(GoogleMap);
private _ngZone = inject(NgZone);
/**
* Data shown on the heatmap.
* See: https://developers.google.com/maps/documentation/javascript/reference/visualization
*/
@Input()
set data(data: HeatmapData) {
this._data = data;
}
private _data: HeatmapData;
/**
* Options used to configure the heatmap. See:
* developers.google.com/maps/documentation/javascript/reference/visualization#HeatmapLayerOptions
*/
@Input()
set options(options: Partial<google.maps.visualization.HeatmapLayerOptions>) {
this._options = options;
}
private _options: Partial<google.maps.visualization.HeatmapLayerOptions>;
/**
* The underlying google.maps.visualization.HeatmapLayer object.
*
* See: https://developers.google.com/maps/documentation/javascript/reference/visualization
*/
heatmap?: google.maps.visualization.HeatmapLayer;
/** Event emitted when the heatmap is initialized. */
@Output() readonly heatmapInitialized: EventEmitter<google.maps.visualization.HeatmapLayer> =
new EventEmitter<google.maps.visualization.HeatmapLayer>();
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (this._googleMap._isBrowser) {
if (
!window.google?.maps?.visualization &&
!window.google?.maps.importLibrary &&
(typeof ngDevMode === 'undefined' || ngDevMode)
) {
throw Error(
'Namespace `google.maps.visualization` not found, cannot construct heatmap. ' +
'Please install the Google Maps JavaScript API with the "visualization" library: ' +
'https://developers.google.com/maps/documentation/javascript/visualization',
);
}
if (google.maps.visualization?.HeatmapLayer && this._googleMap.googleMap) {
this._initialize(this._googleMap.googleMap, google.maps.visualization.HeatmapLayer);
} else {
this._ngZone.runOutsideAngular(() => {
Promise.all([
this._googleMap._resolveMap(),
google.maps.importLibrary('visualization'),
]).then(([map, lib]) => {
this._initialize(map, (lib as google.maps.VisualizationLibrary).HeatmapLayer);
});
});
}
}
}
private _initialize(
map: google.maps.Map,
heatmapConstructor: typeof google.maps.visualization.HeatmapLayer,
) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.heatmap = new heatmapConstructor(this._combineOptions());
this._assertInitialized();
this.heatmap.setMap(map);
this.heatmapInitialized.emit(this.heatmap);
});
}
ngOnChanges(changes: SimpleChanges) {
const {_data, heatmap} = this;
if (heatmap) {
if (changes['options']) {
heatmap.setOptions(this._combineOptions());
}
if (changes['data'] && _data !== undefined) {
heatmap.setData(this._normalizeData(_data));
}
}
}
ngOnDestroy() {
this.heatmap?.setMap(null);
}
/**
* Gets the data that is currently shown on the heatmap.
* See: developers.google.com/maps/documentation/javascript/reference/visualization#HeatmapLayer
*/
getData(): HeatmapData {
this._assertInitialized();
return this.heatmap.getData();
}
/** Creates a combined options object using the passed-in options and the individual inputs. */
private _combineOptions(): google.maps.visualization.HeatmapLayerOptions {
const options = this._options || {};
return {
...options,
data: this._normalizeData(this._data || options.data || []),
map: this._googleMap.googleMap,
};
}
/**
* Most Google Maps APIs support both `LatLng` objects and `LatLngLiteral`. The latter is more
* convenient to write out, because the Google Maps API doesn't have to have been loaded in order
* to construct them. The `HeatmapLayer` appears to be an exception that only allows a `LatLng`
* object, or it throws a runtime error. Since it's more convenient and we expect that Angular
* users will load the API asynchronously, we allow them to pass in a `LatLngLiteral` and we
* convert it to a `LatLng` object before passing it off to Google Maps.
*/
private _normalizeData(data: HeatmapData) {
const result: (google.maps.LatLng | google.maps.visualization.WeightedLocation)[] = [];
data.forEach(item => {
result.push(isLatLngLiteral(item) ? new google.maps.LatLng(item.lat, item.lng) : item);
});
return result;
}
/** Asserts that the heatmap object has been initialized. */
private _assertInitialized(): asserts this is {heatmap: google.maps.visualization.HeatmapLayer} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.heatmap) {
throw Error(
'Cannot interact with a Google Map HeatmapLayer before it has been ' +
'initialized. Please wait for the heatmap to load before trying to interact with it.',
);
}
}
}
}
/** Asserts that an object is a `LatLngLiteral`. */
function isLatLngLiteral(value: any): value is google.maps.LatLngLiteral {
return value && typeof value.lat === 'number' && typeof value.lng === 'number';
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 6600,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-heatmap-layer/map-heatmap-layer.ts"
}
|
components/src/google-maps/map-heatmap-layer/README.md_0_1630
|
# MapHeatmapLayer
The `MapHeatmapLayer` directive wraps the [`google.maps.visualization.HeatmapLayer` class](https://developers.google.com/maps/documentation/javascript/reference/visualization#HeatmapLayer) from the Google Maps Visualization JavaScript API. It displays
a heatmap layer on the map when it is a content child of a `GoogleMap` component. Like `GoogleMap`,
this directive offers an `options` input as well as a convenience input for passing in the `data`
that is shown on the heatmap.
## Example
```typescript
// google-map-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapHeatmapLayer} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapHeatmapLayer],
})
export class GoogleMapDemo {
center = {lat: 37.774546, lng: -122.433523};
zoom = 12;
heatmapOptions = {radius: 5};
heatmapData = [
{lat: 37.782, lng: -122.447},
{lat: 37.782, lng: -122.445},
{lat: 37.782, lng: -122.443},
{lat: 37.782, lng: -122.441},
{lat: 37.782, lng: -122.439},
{lat: 37.782, lng: -122.437},
{lat: 37.782, lng: -122.435},
{lat: 37.785, lng: -122.447},
{lat: 37.785, lng: -122.445},
{lat: 37.785, lng: -122.443},
{lat: 37.785, lng: -122.441},
{lat: 37.785, lng: -122.439},
{lat: 37.785, lng: -122.437},
{lat: 37.785, lng: -122.435}
];
}
```
```html
<!-- google-map-demo.component.html -->
<google-map height="400px" width="750px" [center]="center" [zoom]="zoom">
<map-heatmap-layer [data]="heatmapData" [options]="heatmapOptions" />
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1630,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-heatmap-layer/README.md"
}
|
components/src/google-maps/map-heatmap-layer/map-heatmap-layer.spec.ts_0_5615
|
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createHeatmapLayerConstructorSpy,
createHeatmapLayerSpy,
createLatLngConstructorSpy,
createLatLngSpy,
createMapConstructorSpy,
createMapSpy,
} from '../testing/fake-google-map-utils';
import {HeatmapData, MapHeatmapLayer} from './map-heatmap-layer';
describe('MapHeatmapLayer', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
let latLngSpy: jasmine.SpyObj<google.maps.LatLng>;
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
latLngSpy = createLatLngSpy();
createMapConstructorSpy(mapSpy);
createLatLngConstructorSpy(latLngSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map heatmap layer', fakeAsync(() => {
const heatmapSpy = createHeatmapLayerSpy();
const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(heatmapConstructorSpy).toHaveBeenCalledWith({
data: [],
map: mapSpy,
});
}));
it('should throw if the `visualization` library has not been loaded', fakeAsync(() => {
createHeatmapLayerConstructorSpy(createHeatmapLayerSpy());
delete (window.google.maps as any).visualization;
expect(() => {
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
}).toThrowError(/Namespace `google.maps.visualization` not found, cannot construct heatmap/);
}));
it('sets heatmap inputs', fakeAsync(() => {
const options: google.maps.visualization.HeatmapLayerOptions = {
map: mapSpy,
data: [
new google.maps.LatLng(37.782, -122.447),
new google.maps.LatLng(37.782, -122.445),
new google.maps.LatLng(37.782, -122.443),
],
};
const heatmapSpy = createHeatmapLayerSpy();
const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.data = options.data;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(heatmapConstructorSpy).toHaveBeenCalledWith(options);
}));
it('sets heatmap options, ignoring map', fakeAsync(() => {
const options: Partial<google.maps.visualization.HeatmapLayerOptions> = {
radius: 5,
dissipating: true,
};
const data = [
new google.maps.LatLng(37.782, -122.447),
new google.maps.LatLng(37.782, -122.445),
new google.maps.LatLng(37.782, -122.443),
];
const heatmapSpy = createHeatmapLayerSpy();
const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.data = data;
fixture.componentInstance.options = options;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(heatmapConstructorSpy).toHaveBeenCalledWith({...options, map: mapSpy, data});
}));
it('exposes methods that provide information about the heatmap', fakeAsync(() => {
const heatmapSpy = createHeatmapLayerSpy();
createHeatmapLayerConstructorSpy(heatmapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
const heatmap = fixture.componentInstance.heatmap;
heatmapSpy.getData.and.returnValue([] as any);
expect(heatmap.getData()).toEqual([]);
}));
it('should update the heatmap data when the input changes', fakeAsync(() => {
const heatmapSpy = createHeatmapLayerSpy();
const heatmapConstructorSpy = createHeatmapLayerConstructorSpy(heatmapSpy);
let data = [
new google.maps.LatLng(1, 2),
new google.maps.LatLng(3, 4),
new google.maps.LatLng(5, 6),
];
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.data = data;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(heatmapConstructorSpy).toHaveBeenCalledWith(jasmine.objectContaining({data}));
data = [
new google.maps.LatLng(7, 8),
new google.maps.LatLng(9, 10),
new google.maps.LatLng(11, 12),
];
fixture.componentInstance.data = data;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(heatmapSpy.setData).toHaveBeenCalledWith(data);
}));
it('should create a LatLng object if a LatLngLiteral is passed in', fakeAsync(() => {
const latLngConstructor = createLatLngConstructorSpy(latLngSpy);
createHeatmapLayerConstructorSpy(createHeatmapLayerSpy());
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.data = [
{lat: 1, lng: 2},
{lat: 3, lng: 4},
];
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(latLngConstructor).toHaveBeenCalledWith(1, 2);
expect(latLngConstructor).toHaveBeenCalledWith(3, 4);
expect(latLngConstructor).toHaveBeenCalledTimes(2);
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-heatmap-layer [data]="data" [options]="options" />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapHeatmapLayer],
})
class TestApp {
@ViewChild(MapHeatmapLayer) heatmap: MapHeatmapLayer;
options?: Partial<google.maps.visualization.HeatmapLayerOptions>;
data?: HeatmapData | null;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 5615,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-heatmap-layer/map-heatmap-layer.spec.ts"
}
|
components/src/google-maps/map-advanced-marker/map-advanced-marker.ts_0_1345
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Input,
OnDestroy,
OnInit,
Output,
NgZone,
Directive,
OnChanges,
SimpleChanges,
inject,
EventEmitter,
} from '@angular/core';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
import {MapAnchorPoint} from '../map-anchor-point';
import {MAP_MARKER, MarkerDirective} from '../marker-utilities';
import {Observable} from 'rxjs';
import {take} from 'rxjs/operators';
/**
* Default options for the Google Maps marker component. Displays a marker
* at the Googleplex.
*/
export const DEFAULT_MARKER_OPTIONS = {
position: {lat: 37.221995, lng: -122.184092},
};
/**
* Angular component that renders a Google Maps marker via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/marker
*/
@Directive({
selector: 'map-advanced-marker',
exportAs: 'mapAdvancedMarker',
providers: [
{
provide: MAP_MARKER,
useExisting: MapAdvancedMarker,
},
],
})
export
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1345,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-advanced-marker/map-advanced-marker.ts"
}
|
components/src/google-maps/map-advanced-marker/map-advanced-marker.ts_1346_10338
|
class MapAdvancedMarker
implements OnInit, OnChanges, OnDestroy, MapAnchorPoint, MarkerDirective
{
private readonly _googleMap = inject(GoogleMap);
private _ngZone = inject(NgZone);
private _eventManager = new MapEventManager(inject(NgZone));
/**
* Rollover text. If provided, an accessibility text (e.g. for use with screen readers) will be added to the AdvancedMarkerElement with the provided value.
* See: https://developers.google.com/maps/documentation/javascript/reference/advanced-markers#AdvancedMarkerElementOptions.title
*/
@Input()
set title(title: string) {
this._title = title;
}
private _title: string;
/**
* Sets the AdvancedMarkerElement's position. An AdvancedMarkerElement may be constructed without a position, but will not be displayed until its position is provided - for example, by a user's actions or choices. An AdvancedMarkerElement's position can be provided by setting AdvancedMarkerElement.position if not provided at the construction.
* Note: AdvancedMarkerElement with altitude is only supported on vector maps.
* https://developers.google.com/maps/documentation/javascript/reference/advanced-markers#AdvancedMarkerElementOptions.position
*/
@Input()
set position(
position:
| google.maps.LatLngLiteral
| google.maps.LatLng
| google.maps.LatLngAltitude
| google.maps.LatLngAltitudeLiteral,
) {
this._position = position;
}
private _position: google.maps.LatLngLiteral | google.maps.LatLng;
/**
* The DOM Element backing the visual of an AdvancedMarkerElement.
* Note: AdvancedMarkerElement does not clone the passed-in DOM element. Once the DOM element is passed to an AdvancedMarkerElement, passing the same DOM element to another AdvancedMarkerElement will move the DOM element and cause the previous AdvancedMarkerElement to look empty.
* See: https://developers.google.com/maps/documentation/javascript/reference/advanced-markers#AdvancedMarkerElementOptions.content
*/
@Input()
set content(content: Node | google.maps.marker.PinElement | null) {
this._content = content;
}
private _content: Node | null;
/**
* If true, the AdvancedMarkerElement can be dragged.
* Note: AdvancedMarkerElement with altitude is not draggable.
* https://developers.google.com/maps/documentation/javascript/reference/advanced-markers#AdvancedMarkerElementOptions.gmpDraggable
*/
@Input()
set gmpDraggable(draggable: boolean) {
this._draggable = draggable;
}
private _draggable: boolean;
/**
* Options for constructing an AdvancedMarkerElement.
* https://developers.google.com/maps/documentation/javascript/reference/advanced-markers#AdvancedMarkerElementOptions
*/
@Input()
set options(options: google.maps.marker.AdvancedMarkerElementOptions) {
this._options = options;
}
private _options: google.maps.marker.AdvancedMarkerElementOptions;
/**
* AdvancedMarkerElements on the map are prioritized by zIndex, with higher values indicating higher display.
* https://developers.google.com/maps/documentation/javascript/reference/advanced-markers#AdvancedMarkerElementOptions.zIndex
*/
@Input()
set zIndex(zIndex: number) {
this._zIndex = zIndex;
}
private _zIndex: number;
/**
* This event is fired when the AdvancedMarkerElement element is clicked.
* https://developers.google.com/maps/documentation/javascript/reference/advanced-markers#AdvancedMarkerElement.click
*/
@Output() readonly mapClick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('click');
/**
* This event is fired when the AdvancedMarkerElement is double-clicked.
*/
@Output() readonly mapDblclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dblclick');
/**
* This event is fired when the mouse moves out of the AdvancedMarkerElement.
*/
@Output() readonly mapMouseout: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseout');
/**
* This event is fired when the mouse moves over the AdvancedMarkerElement.
*/
@Output() readonly mapMouseover: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseover');
/**
* This event is fired when the mouse button is released over the AdvancedMarkerElement.
*/
@Output() readonly mapMouseup: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseup');
/**
* This event is fired when the AdvancedMarkerElement is right-clicked.
*/
@Output() readonly mapRightclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('rightclick');
/**
* This event is repeatedly fired while the user drags the AdvancedMarkerElement.
* https://developers.google.com/maps/documentation/javascript/reference/advanced-markers#AdvancedMarkerElement.drag
*/
@Output() readonly mapDrag: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('drag');
/**
* This event is fired when the user stops dragging the AdvancedMarkerElement.
* https://developers.google.com/maps/documentation/javascript/reference/advanced-markers#AdvancedMarkerElement.dragend
*/
@Output() readonly mapDragend: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragend');
/**
* This event is fired when the user starts dragging the AdvancedMarkerElement.
* https://developers.google.com/maps/documentation/javascript/reference/advanced-markers#AdvancedMarkerElement.dragstart
*/
@Output() readonly mapDragstart: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragstart');
/** Event emitted when the marker is initialized. */
@Output() readonly markerInitialized: EventEmitter<google.maps.marker.AdvancedMarkerElement> =
new EventEmitter<google.maps.marker.AdvancedMarkerElement>();
/**
* The underlying google.maps.marker.AdvancedMarkerElement object.
*
* See developers.google.com/maps/documentation/javascript/reference/advanced-markers#AdvancedMarkerElement
*/
advancedMarker: google.maps.marker.AdvancedMarkerElement;
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (!this._googleMap._isBrowser) {
return;
}
if (google.maps.marker?.AdvancedMarkerElement && this._googleMap.googleMap) {
this._initialize(this._googleMap.googleMap, google.maps.marker.AdvancedMarkerElement);
} else {
this._ngZone.runOutsideAngular(() => {
Promise.all([this._googleMap._resolveMap(), google.maps.importLibrary('marker')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.MarkerLibrary).AdvancedMarkerElement);
},
);
});
}
}
private _initialize(
map: google.maps.Map,
advancedMarkerConstructor: typeof google.maps.marker.AdvancedMarkerElement,
) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.advancedMarker = new advancedMarkerConstructor(this._combineOptions());
this._assertInitialized();
this.advancedMarker.map = map;
this._eventManager.setTarget(this.advancedMarker);
this.markerInitialized.next(this.advancedMarker);
});
}
ngOnChanges(changes: SimpleChanges) {
const {advancedMarker, _content, _position, _title, _draggable, _zIndex} = this;
if (advancedMarker) {
if (changes['title']) {
advancedMarker.title = _title;
}
if (changes['gmpDraggable']) {
advancedMarker.gmpDraggable = _draggable;
}
if (changes['content']) {
advancedMarker.content = _content;
}
if (changes['position']) {
advancedMarker.position = _position;
}
if (changes['zIndex']) {
advancedMarker.zIndex = _zIndex;
}
}
}
ngOnDestroy() {
this.markerInitialized.complete();
this._eventManager.destroy();
if (this.advancedMarker) {
this.advancedMarker.map = null;
}
}
getAnchor(): google.maps.marker.AdvancedMarkerElement {
this._assertInitialized();
return this.advancedMarker;
}
/** Returns a promise that resolves when the marker has been initialized. */
_resolveMarker(): Promise<google.maps.marker.AdvancedMarkerElement> {
return this.advancedMarker
? Promise.resolve(this.advancedMarker)
: this.markerInitialized.pipe(take(1)).toPromise();
}
/** Creates a combined options object using the passed-in options and the individual inputs. */
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 10338,
"start_byte": 1346,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-advanced-marker/map-advanced-marker.ts"
}
|
components/src/google-maps/map-advanced-marker/map-advanced-marker.ts_10341_11279
|
private _combineOptions(): google.maps.marker.AdvancedMarkerElementOptions {
const options = this._options || DEFAULT_MARKER_OPTIONS;
return {
...options,
title: this._title || options.title,
position: this._position || options.position,
content: this._content || options.content,
zIndex: this._zIndex ?? options.zIndex,
gmpDraggable: this._draggable ?? options.gmpDraggable,
map: this._googleMap.googleMap,
};
}
/** Asserts that the map has been initialized. */
private _assertInitialized(): asserts this is {marker: google.maps.marker.AdvancedMarkerElement} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.advancedMarker) {
throw Error(
'Cannot interact with a Google Map Marker before it has been ' +
'initialized. Please wait for the Marker to load before trying to interact with it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 11279,
"start_byte": 10341,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-advanced-marker/map-advanced-marker.ts"
}
|
components/src/google-maps/map-advanced-marker/map-advanced-marker.spec.ts_0_6975
|
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createAdvancedMarkerConstructorSpy,
createAdvancedMarkerSpy,
createMapConstructorSpy,
createMapSpy,
} from '../testing/fake-google-map-utils';
import {DEFAULT_MARKER_OPTIONS, MapAdvancedMarker} from './map-advanced-marker';
describe('MapAdvancedMarker', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map advanced marker', fakeAsync(() => {
const advancedMarkerSpy = createAdvancedMarkerSpy(DEFAULT_MARKER_OPTIONS);
const advancedMarkerConstructorSpy = createAdvancedMarkerConstructorSpy(advancedMarkerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(advancedMarkerConstructorSpy).toHaveBeenCalledWith({
...DEFAULT_MARKER_OPTIONS,
title: undefined,
content: undefined,
gmpDraggable: undefined,
zIndex: undefined,
map: mapSpy,
});
}));
it('sets advanced marker inputs', fakeAsync(() => {
const options: google.maps.marker.AdvancedMarkerElementOptions = {
position: {lat: 3, lng: 5},
title: 'marker title',
map: mapSpy,
content: undefined,
gmpDraggable: true,
zIndex: 1,
};
const advancedMarkerSpy = createAdvancedMarkerSpy(options);
const advancedMarkerConstructorSpy = createAdvancedMarkerConstructorSpy(advancedMarkerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.position = options.position;
fixture.componentInstance.title = options.title;
fixture.componentInstance.content = options.content;
fixture.componentInstance.gmpDraggable = options.gmpDraggable;
fixture.componentInstance.zIndex = options.zIndex;
fixture.detectChanges();
flush();
expect(advancedMarkerConstructorSpy).toHaveBeenCalledWith(options);
}));
it('sets marker options, ignoring map', fakeAsync(() => {
const options: google.maps.marker.AdvancedMarkerElementOptions = {
position: {lat: 3, lng: 5},
title: 'marker title',
content: undefined,
gmpDraggable: true,
zIndex: 1,
};
const advancedMarkerSpy = createAdvancedMarkerSpy(options);
const advancedMarkerConstructorSpy = createAdvancedMarkerConstructorSpy(advancedMarkerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = options;
fixture.detectChanges();
flush();
expect(advancedMarkerConstructorSpy).toHaveBeenCalledWith({...options, map: mapSpy});
}));
it('gives precedence to specific inputs over options', fakeAsync(() => {
const options: google.maps.marker.AdvancedMarkerElementOptions = {
position: {lat: 3, lng: 5},
title: 'marker title',
content: undefined,
gmpDraggable: true,
zIndex: 1,
};
const expectedOptions: google.maps.marker.AdvancedMarkerElementOptions = {
position: {lat: 4, lng: 6},
title: 'marker title 2',
content: undefined,
gmpDraggable: false,
zIndex: 999,
map: mapSpy,
};
const advancedMarkerSpy = createAdvancedMarkerSpy(options);
const advancedMarkerConstructorSpy = createAdvancedMarkerConstructorSpy(advancedMarkerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.position = expectedOptions.position;
fixture.componentInstance.title = expectedOptions.title;
fixture.componentInstance.content = expectedOptions.content;
fixture.componentInstance.gmpDraggable = expectedOptions.gmpDraggable;
fixture.componentInstance.zIndex = expectedOptions.zIndex;
fixture.componentInstance.options = options;
fixture.detectChanges();
flush();
expect(advancedMarkerConstructorSpy).toHaveBeenCalledWith(expectedOptions);
}));
it('initializes marker event handlers', fakeAsync(() => {
const advancedMarkerSpy = createAdvancedMarkerSpy(DEFAULT_MARKER_OPTIONS);
createAdvancedMarkerConstructorSpy(advancedMarkerSpy);
const addSpy = advancedMarkerSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).toHaveBeenCalledWith('click', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('dblclick', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('mouseout', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('mouseover', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('mouseup', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('rightclick', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('drag', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragend', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragstart', jasmine.any(Function));
}));
it('should be able to add an event listener after init', fakeAsync(() => {
const advancedMarkerSpy = createAdvancedMarkerSpy(DEFAULT_MARKER_OPTIONS);
createAdvancedMarkerConstructorSpy(advancedMarkerSpy);
const addSpy = advancedMarkerSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).not.toHaveBeenCalledWith('drag', jasmine.any(Function));
// Pick an event that isn't bound in the template.
const subscription = fixture.componentInstance.advancedMarker.mapDrag.subscribe();
fixture.detectChanges();
expect(addSpy).toHaveBeenCalledWith('drag', jasmine.any(Function));
subscription.unsubscribe();
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-advanced-marker
[title]="title"
[position]="position"
[content]="content"
[gmpDraggable]="gmpDraggable"
[zIndex]="zIndex"
(mapClick)="handleClick()"
(mapDblclick)="handleDblclick()"
(mapMouseout)="handleMouseout()"
(mapMouseover)="handleMouseover()"
(mapMouseup)="handleMouseup()"
(mapRightclick)="handleRightclick()"
[options]="options" />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapAdvancedMarker],
})
class TestApp {
@ViewChild(MapAdvancedMarker) advancedMarker: MapAdvancedMarker;
title?: string | null;
position?: google.maps.LatLng | google.maps.LatLngLiteral | null;
content?: Node | google.maps.marker.PinElement | null;
gmpDraggable?: boolean | null;
zIndex?: number | null;
options: google.maps.marker.AdvancedMarkerElementOptions;
handleClick() {}
handleDblclick() {}
handleMouseout() {}
handleMouseover() {}
handleMouseup() {}
handleRightclick() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 6975,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-advanced-marker/map-advanced-marker.spec.ts"
}
|
components/src/google-maps/map-bicycling-layer/map-bicycling-layer.spec.ts_0_1318
|
import {Component} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createBicyclingLayerConstructorSpy,
createBicyclingLayerSpy,
createMapConstructorSpy,
createMapSpy,
} from '../testing/fake-google-map-utils';
import {MapBicyclingLayer} from './map-bicycling-layer';
describe('MapBicyclingLayer', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map Bicycling Layer', fakeAsync(() => {
const bicyclingLayerSpy = createBicyclingLayerSpy();
const bicyclingLayerConstructorSpy = createBicyclingLayerConstructorSpy(bicyclingLayerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(bicyclingLayerConstructorSpy).toHaveBeenCalled();
expect(bicyclingLayerSpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-bicycling-layer />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapBicyclingLayer],
})
class TestApp {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1318,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-bicycling-layer/map-bicycling-layer.spec.ts"
}
|
components/src/google-maps/map-bicycling-layer/map-bicycling-layer.ts_0_2600
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {Directive, EventEmitter, NgZone, OnDestroy, OnInit, Output, inject} from '@angular/core';
import {GoogleMap} from '../google-map/google-map';
/**
* Angular component that renders a Google Maps Bicycling Layer via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/map#BicyclingLayer
*/
@Directive({
selector: 'map-bicycling-layer',
exportAs: 'mapBicyclingLayer',
})
export class MapBicyclingLayer implements OnInit, OnDestroy {
private _map = inject(GoogleMap);
private _zone = inject(NgZone);
/**
* The underlying google.maps.BicyclingLayer object.
*
* See developers.google.com/maps/documentation/javascript/reference/map#BicyclingLayer
*/
bicyclingLayer?: google.maps.BicyclingLayer;
/** Event emitted when the bicycling layer is initialized. */
@Output() readonly bicyclingLayerInitialized: EventEmitter<google.maps.BicyclingLayer> =
new EventEmitter<google.maps.BicyclingLayer>();
ngOnInit(): void {
if (this._map._isBrowser) {
if (google.maps.BicyclingLayer && this._map.googleMap) {
this._initialize(this._map.googleMap, google.maps.BicyclingLayer);
} else {
this._zone.runOutsideAngular(() => {
Promise.all([this._map._resolveMap(), google.maps.importLibrary('maps')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.MapsLibrary).BicyclingLayer);
},
);
});
}
}
}
private _initialize(map: google.maps.Map, layerConstructor: typeof google.maps.BicyclingLayer) {
this._zone.runOutsideAngular(() => {
this.bicyclingLayer = new layerConstructor();
this.bicyclingLayerInitialized.emit(this.bicyclingLayer);
this._assertLayerInitialized();
this.bicyclingLayer.setMap(map);
});
}
ngOnDestroy() {
this.bicyclingLayer?.setMap(null);
}
private _assertLayerInitialized(): asserts this is {bicyclingLayer: google.maps.BicyclingLayer} {
if (!this.bicyclingLayer) {
throw Error(
'Cannot interact with a Google Map Bicycling Layer before it has been initialized. ' +
'Please wait for the Transit Layer to load before trying to interact with it.',
);
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2600,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-bicycling-layer/map-bicycling-layer.ts"
}
|
components/src/google-maps/map-bicycling-layer/README.md_0_800
|
# MapBicyclingLayer
The `MapBicyclingLayer` component wraps the [`google.maps.BicyclingLayer` class](https://developers.google.com/maps/documentation/javascript/reference/map#BicyclingLayer) from the Google Maps JavaScript API.
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapBicyclingLayer} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapBicyclingLayer],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map height="400px" width="750px" [center]="center" [zoom]="zoom">
<map-bicycling-layer />
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 800,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-bicycling-layer/README.md"
}
|
components/src/google-maps/map-directions-renderer/map-directions-service.ts_0_2060
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {Injectable, NgZone, inject} from '@angular/core';
import {Observable} from 'rxjs';
export interface MapDirectionsResponse {
status: google.maps.DirectionsStatus;
result?: google.maps.DirectionsResult;
}
/**
* Angular service that wraps the Google Maps DirectionsService from the Google Maps JavaScript
* API.
*
* See developers.google.com/maps/documentation/javascript/reference/directions#DirectionsService
*/
@Injectable({providedIn: 'root'})
export class MapDirectionsService {
private readonly _ngZone = inject(NgZone);
private _directionsService: google.maps.DirectionsService | undefined;
constructor(...args: unknown[]);
constructor() {}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/directions
* #DirectionsService.route
*/
route(request: google.maps.DirectionsRequest): Observable<MapDirectionsResponse> {
return new Observable(observer => {
this._getService().then(service => {
service.route(request, (result, status) => {
this._ngZone.run(() => {
observer.next({result: result || undefined, status});
observer.complete();
});
});
});
});
}
private _getService(): Promise<google.maps.DirectionsService> {
if (!this._directionsService) {
if (google.maps.DirectionsService) {
this._directionsService = new google.maps.DirectionsService();
} else {
return google.maps.importLibrary('routes').then(lib => {
this._directionsService = new (lib as google.maps.RoutesLibrary).DirectionsService();
return this._directionsService;
});
}
}
return Promise.resolve(this._directionsService);
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2060,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-directions-renderer/map-directions-service.ts"
}
|
components/src/google-maps/map-directions-renderer/map-directions-renderer.ts_0_5576
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Directive,
EventEmitter,
Input,
NgZone,
OnChanges,
OnDestroy,
OnInit,
Output,
SimpleChanges,
inject,
} from '@angular/core';
import {Observable} from 'rxjs';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
/**
* Angular component that renders a Google Maps Directions Renderer via the Google Maps
* JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/directions#DirectionsRenderer
*/
@Directive({
selector: 'map-directions-renderer',
exportAs: 'mapDirectionsRenderer',
})
export class MapDirectionsRenderer implements OnInit, OnChanges, OnDestroy {
private readonly _googleMap = inject(GoogleMap);
private _ngZone = inject(NgZone);
private _eventManager = new MapEventManager(inject(NgZone));
/**
* See developers.google.com/maps/documentation/javascript/reference/directions
* #DirectionsRendererOptions.directions
*/
@Input()
set directions(directions: google.maps.DirectionsResult) {
this._directions = directions;
}
private _directions: google.maps.DirectionsResult;
/**
* See developers.google.com/maps/documentation/javascript/reference/directions
* #DirectionsRendererOptions
*/
@Input()
set options(options: google.maps.DirectionsRendererOptions) {
this._options = options;
}
private _options: google.maps.DirectionsRendererOptions;
/**
* See developers.google.com/maps/documentation/javascript/reference/directions
* #DirectionsRenderer.directions_changed
*/
@Output()
readonly directionsChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('directions_changed');
/** Event emitted when the directions renderer is initialized. */
@Output() readonly directionsRendererInitialized: EventEmitter<google.maps.DirectionsRenderer> =
new EventEmitter<google.maps.DirectionsRenderer>();
/** The underlying google.maps.DirectionsRenderer object. */
directionsRenderer?: google.maps.DirectionsRenderer;
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (this._googleMap._isBrowser) {
if (google.maps.DirectionsRenderer && this._googleMap.googleMap) {
this._initialize(this._googleMap.googleMap, google.maps.DirectionsRenderer);
} else {
this._ngZone.runOutsideAngular(() => {
Promise.all([this._googleMap._resolveMap(), google.maps.importLibrary('routes')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.RoutesLibrary).DirectionsRenderer);
},
);
});
}
}
}
private _initialize(
map: google.maps.Map,
rendererConstructor: typeof google.maps.DirectionsRenderer,
) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.directionsRenderer = new rendererConstructor(this._combineOptions());
this._assertInitialized();
this.directionsRenderer.setMap(map);
this._eventManager.setTarget(this.directionsRenderer);
this.directionsRendererInitialized.emit(this.directionsRenderer);
});
}
ngOnChanges(changes: SimpleChanges) {
if (this.directionsRenderer) {
if (changes['options']) {
this.directionsRenderer.setOptions(this._combineOptions());
}
if (changes['directions'] && this._directions !== undefined) {
this.directionsRenderer.setDirections(this._directions);
}
}
}
ngOnDestroy() {
this._eventManager.destroy();
this.directionsRenderer?.setMap(null);
}
/**
* See developers.google.com/maps/documentation/javascript/reference/directions
* #DirectionsRenderer.getDirections
*/
getDirections(): google.maps.DirectionsResult | null {
this._assertInitialized();
return this.directionsRenderer.getDirections();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/directions
* #DirectionsRenderer.getPanel
*/
getPanel(): Node | null {
this._assertInitialized();
return this.directionsRenderer.getPanel();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/directions
* #DirectionsRenderer.getRouteIndex
*/
getRouteIndex(): number {
this._assertInitialized();
return this.directionsRenderer.getRouteIndex();
}
private _combineOptions(): google.maps.DirectionsRendererOptions {
const options = this._options || {};
return {
...options,
directions: this._directions || options.directions,
map: this._googleMap.googleMap,
};
}
private _assertInitialized(): asserts this is {
directionsRenderer: google.maps.DirectionsRenderer;
} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.directionsRenderer) {
throw Error(
'Cannot interact with a Google Map Directions Renderer before it has been ' +
'initialized. Please wait for the Directions Renderer to load before trying ' +
'to interact with it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 5576,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-directions-renderer/map-directions-renderer.ts"
}
|
components/src/google-maps/map-directions-renderer/README.md_0_2938
|
# MapDirectionsRenderer
The `MapDirectionsRenderer` component wraps the [`google.maps.DirectionsRenderer` class](https://developers.google.com/maps/documentation/javascript/reference/directions#DirectionsRenderer) from the Google Maps JavaScript API. This can easily be used with the `MapDirectionsService` that wraps [`google.maps.DirectionsService`](https://developers.google.com/maps/documentation/javascript/reference/directions#DirectionsService) which is designed to be used with Angular by returning an `Observable` response and works inside the Angular Zone.
The `MapDirectionsService`, like the `google.maps.DirectionsService`, has a single method, `route`. Normally, the `google.maps.DirectionsService` takes two arguments, a `google.maps.DirectionsRequest` and a callback that takes the `google.maps.DirectionsResult` and `google.maps.DirectionsStatus` as arguments. The `MapDirectionsService` route method takes the `google.maps.DirectionsRequest` as the single argument, and returns an `Observable` of a `MapDirectionsResponse`, which is an interface defined as follows:
```typescript
export interface MapDirectionsResponse {
status: google.maps.DirectionsStatus;
result?: google.maps.DirectionsResult;
}
```
The most common use-case for the component and class would be to use the `MapDirectionsService` to request a route between two points on the map, and then render them on the map using the `MapDirectionsRenderer`.
## Loading the Library
Using the `MapDirectionsService` requires the Directions API to be enabled in Google Cloud Console on the same project as the one set up for the Google Maps JavaScript API, and requires an API key that has billing enabled. See [here](https://developers.google.com/maps/documentation/javascript/directions#GetStarted) for details.
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapDirectionsRenderer, MapDirectionsService} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapDirectionsRenderer],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
readonly directionsResults$: Observable<google.maps.DirectionsResult|undefined>;
constructor(mapDirectionsService: MapDirectionsService) {
const request: google.maps.DirectionsRequest = {
destination: {lat: 12, lng: 4},
origin: {lat: 14, lng: 8},
travelMode: google.maps.TravelMode.DRIVING
};
this.directionsResults$ = mapDirectionsService.route(request).pipe(map(response => response.result));
}
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map height="400px" width="750px" [center]="center" [zoom]="zoom">
@if (directionsResults$ | async; as directionsResults) {
<map-directions-renderer [directions]="directionsResults" />
}
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2938,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-directions-renderer/README.md"
}
|
components/src/google-maps/map-directions-renderer/map-directions-service.spec.ts_0_2036
|
import {TestBed} from '@angular/core/testing';
import {MapDirectionsResponse, MapDirectionsService} from './map-directions-service';
import {
createDirectionsServiceConstructorSpy,
createDirectionsServiceSpy,
} from '../testing/fake-google-map-utils';
describe('MapDirectionsService', () => {
let mapDirectionsService: MapDirectionsService;
let directionsServiceConstructorSpy: jasmine.Spy;
let directionsServiceSpy: jasmine.SpyObj<google.maps.DirectionsService>;
beforeEach(() => {
directionsServiceSpy = createDirectionsServiceSpy();
directionsServiceConstructorSpy = createDirectionsServiceConstructorSpy(directionsServiceSpy);
mapDirectionsService = TestBed.inject(MapDirectionsService);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('does not initialize the Google Maps Directions Service immediately', () => {
expect(directionsServiceConstructorSpy).not.toHaveBeenCalled();
});
it('initializes the Google Maps Directions Service when `route` is called', () => {
mapDirectionsService
.route({
origin: 'home',
destination: 'work',
travelMode: 'BICYCLING' as google.maps.TravelMode,
})
.subscribe();
expect(directionsServiceConstructorSpy).toHaveBeenCalled();
});
it('calls route on inputs', () => {
const result: google.maps.DirectionsResult = {
routes: [],
request: {
origin: 'foo',
destination: 'bar',
travelMode: 'BICYCLING' as google.maps.TravelMode,
},
};
const status = 'OK' as google.maps.DirectionsStatus;
directionsServiceSpy.route.and.callFake((_request, callback) => {
callback?.(result, status);
return Promise.resolve(result);
});
mapDirectionsService
.route({
origin: 'home',
destination: 'work',
travelMode: 'BICYCLING' as google.maps.TravelMode,
})
.subscribe(response => {
expect(response).toEqual({result, status} as MapDirectionsResponse);
});
});
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2036,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-directions-renderer/map-directions-service.spec.ts"
}
|
components/src/google-maps/map-directions-renderer/map-directions-renderer.spec.ts_0_5212
|
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {MapDirectionsRenderer} from './map-directions-renderer';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createDirectionsRendererConstructorSpy,
createDirectionsRendererSpy,
createMapConstructorSpy,
createMapSpy,
} from '../testing/fake-google-map-utils';
const DEFAULT_DIRECTIONS: google.maps.DirectionsResult = {
geocoded_waypoints: [],
routes: [],
request: {origin: 'foo', destination: 'bar', travelMode: 'BICYCLING' as google.maps.TravelMode},
};
describe('MapDirectionsRenderer', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Maps DirectionsRenderer', fakeAsync(() => {
const directionsRendererSpy = createDirectionsRendererSpy({directions: DEFAULT_DIRECTIONS});
const directionsRendererConstructorSpy =
createDirectionsRendererConstructorSpy(directionsRendererSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = {directions: DEFAULT_DIRECTIONS};
fixture.detectChanges();
flush();
expect(directionsRendererConstructorSpy).toHaveBeenCalledWith({
directions: DEFAULT_DIRECTIONS,
map: jasmine.any(Object),
});
expect(directionsRendererSpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
it('sets directions from directions input', fakeAsync(() => {
const directionsRendererSpy = createDirectionsRendererSpy({directions: DEFAULT_DIRECTIONS});
const directionsRendererConstructorSpy =
createDirectionsRendererConstructorSpy(directionsRendererSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.directions = DEFAULT_DIRECTIONS;
fixture.detectChanges();
flush();
expect(directionsRendererConstructorSpy).toHaveBeenCalledWith({
directions: DEFAULT_DIRECTIONS,
map: jasmine.any(Object),
});
expect(directionsRendererSpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
it('gives precedence to directions over options', fakeAsync(() => {
const updatedDirections: google.maps.DirectionsResult = {
geocoded_waypoints: [{partial_match: false, place_id: 'test', types: []}],
request: {
origin: 'foo',
destination: 'bar',
travelMode: 'BICYCLING' as google.maps.TravelMode,
},
routes: [],
};
const directionsRendererSpy = createDirectionsRendererSpy({directions: updatedDirections});
const directionsRendererConstructorSpy =
createDirectionsRendererConstructorSpy(directionsRendererSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = {directions: DEFAULT_DIRECTIONS};
fixture.componentInstance.directions = updatedDirections;
fixture.detectChanges();
flush();
expect(directionsRendererConstructorSpy).toHaveBeenCalledWith({
directions: updatedDirections,
map: jasmine.any(Object),
});
expect(directionsRendererSpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
it('exposes methods that provide information from the DirectionsRenderer', fakeAsync(() => {
const directionsRendererSpy = createDirectionsRendererSpy({});
createDirectionsRendererConstructorSpy(directionsRendererSpy);
const fixture = TestBed.createComponent(TestApp);
const directionsRendererComponent = fixture.debugElement
.query(By.directive(MapDirectionsRenderer))!
.injector.get<MapDirectionsRenderer>(MapDirectionsRenderer);
fixture.detectChanges();
flush();
directionsRendererSpy.getDirections.and.returnValue(DEFAULT_DIRECTIONS);
expect(directionsRendererComponent.getDirections()).toBe(DEFAULT_DIRECTIONS);
directionsRendererComponent.getPanel();
expect(directionsRendererSpy.getPanel).toHaveBeenCalled();
directionsRendererSpy.getRouteIndex.and.returnValue(10);
expect(directionsRendererComponent.getRouteIndex()).toBe(10);
}));
it('initializes DirectionsRenderer event handlers', fakeAsync(() => {
const directionsRendererSpy = createDirectionsRendererSpy({});
createDirectionsRendererConstructorSpy(directionsRendererSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(directionsRendererSpy.addListener).toHaveBeenCalledWith(
'directions_changed',
jasmine.any(Function),
);
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-directions-renderer
[options]="options"
[directions]="directions"
(directionsChanged)="handleDirectionsChanged()" />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapDirectionsRenderer],
})
class TestApp {
@ViewChild(MapDirectionsRenderer) directionsRenderer: MapDirectionsRenderer;
options?: google.maps.DirectionsRendererOptions;
directions?: google.maps.DirectionsResult;
handleDirectionsChanged() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 5212,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-directions-renderer/map-directions-renderer.spec.ts"
}
|
components/src/google-maps/map-transit-layer/map-transit-layer.ts_0_2548
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {Directive, EventEmitter, NgZone, OnDestroy, OnInit, Output, inject} from '@angular/core';
import {GoogleMap} from '../google-map/google-map';
/**
* Angular component that renders a Google Maps Transit Layer via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/map#TransitLayer
*/
@Directive({
selector: 'map-transit-layer',
exportAs: 'mapTransitLayer',
})
export class MapTransitLayer implements OnInit, OnDestroy {
private _map = inject(GoogleMap);
private _zone = inject(NgZone);
/**
* The underlying google.maps.TransitLayer object.
*
* See developers.google.com/maps/documentation/javascript/reference/map#TransitLayer
*/
transitLayer?: google.maps.TransitLayer;
/** Event emitted when the transit layer is initialized. */
@Output() readonly transitLayerInitialized: EventEmitter<google.maps.TransitLayer> =
new EventEmitter<google.maps.TransitLayer>();
ngOnInit(): void {
if (this._map._isBrowser) {
if (google.maps.TransitLayer && this._map.googleMap) {
this._initialize(this._map.googleMap, google.maps.TransitLayer);
} else {
this._zone.runOutsideAngular(() => {
Promise.all([this._map._resolveMap(), google.maps.importLibrary('maps')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.MapsLibrary).TransitLayer);
},
);
});
}
}
}
private _initialize(map: google.maps.Map, layerConstructor: typeof google.maps.TransitLayer) {
this._zone.runOutsideAngular(() => {
this.transitLayer = new layerConstructor();
this.transitLayerInitialized.emit(this.transitLayer);
this._assertLayerInitialized();
this.transitLayer.setMap(map);
});
}
ngOnDestroy() {
this.transitLayer?.setMap(null);
}
private _assertLayerInitialized(): asserts this is {transitLayer: google.maps.TransitLayer} {
if (!this.transitLayer) {
throw Error(
'Cannot interact with a Google Map Transit Layer before it has been initialized. ' +
'Please wait for the Transit Layer to load before trying to interact with it.',
);
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2548,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-transit-layer/map-transit-layer.ts"
}
|
components/src/google-maps/map-transit-layer/map-transit-layer.spec.ts_0_1289
|
import {Component} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createMapConstructorSpy,
createMapSpy,
createTransitLayerConstructorSpy,
createTransitLayerSpy,
} from '../testing/fake-google-map-utils';
import {MapTransitLayer} from './map-transit-layer';
describe('MapTransitLayer', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map Transit Layer', fakeAsync(() => {
const transitLayerSpy = createTransitLayerSpy();
const transitLayerConstructorSpy = createTransitLayerConstructorSpy(transitLayerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(transitLayerConstructorSpy).toHaveBeenCalled();
expect(transitLayerSpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-transit-layer />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapTransitLayer],
})
class TestApp {}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1289,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-transit-layer/map-transit-layer.spec.ts"
}
|
components/src/google-maps/map-transit-layer/README.md_0_786
|
# MapTransitLayer
The `MapTransitLayer` component wraps the [`google.maps.TransitLayer` class](https://developers.google.com/maps/documentation/javascript/reference/map#TransitLayer) from the Google Maps JavaScript API.
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapTransitLayer} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapTransitLayer],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map height="400px" width="750px" [center]="center" [zoom]="zoom">
<map-transit-layer />
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 786,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-transit-layer/README.md"
}
|
components/src/google-maps/map-geocoder/map-geocoder.ts_0_1908
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {Injectable, NgZone, inject} from '@angular/core';
import {Observable} from 'rxjs';
export interface MapGeocoderResponse {
status: google.maps.GeocoderStatus;
results: google.maps.GeocoderResult[];
}
/**
* Angular service that wraps the Google Maps Geocoder from the Google Maps JavaScript API.
* See developers.google.com/maps/documentation/javascript/reference/geocoder#Geocoder
*/
@Injectable({providedIn: 'root'})
export class MapGeocoder {
private readonly _ngZone = inject(NgZone);
private _geocoder: google.maps.Geocoder | undefined;
constructor(...args: unknown[]);
constructor() {}
/**
* See developers.google.com/maps/documentation/javascript/reference/geocoder#Geocoder.geocode
*/
geocode(request: google.maps.GeocoderRequest): Observable<MapGeocoderResponse> {
return new Observable(observer => {
this._getGeocoder().then(geocoder => {
geocoder.geocode(request, (results, status) => {
this._ngZone.run(() => {
observer.next({results: results || [], status});
observer.complete();
});
});
});
});
}
private _getGeocoder(): Promise<google.maps.Geocoder> {
if (!this._geocoder) {
if (google.maps.Geocoder) {
this._geocoder = new google.maps.Geocoder();
} else {
return google.maps.importLibrary('geocoding').then(lib => {
this._geocoder = new (lib as google.maps.GeocodingLibrary).Geocoder();
return this._geocoder;
});
}
}
return Promise.resolve(this._geocoder);
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1908,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-geocoder/map-geocoder.ts"
}
|
components/src/google-maps/map-geocoder/README.md_0_1444
|
# MapGeocoder
The `MapGeocoder`, like the `google.maps.Geocoder`, has a single method, `geocode`. Normally, the
`google.maps.Geocoder` takes two arguments, a `google.maps.GeocoderRequest` and a callback that
takes the `google.maps.GeocoderResult` and `google.maps.GeocoderStatus` as arguments.
The `MapGeocoder.geocode` method takes the `google.maps.GeocoderRequest` as the single
argument, and returns an `Observable` of a `MapGeocoderResponse`, which is an interface defined as
follows:
```typescript
export interface MapGeocoderResponse {
status: google.maps.GeocoderStatus;
results: google.maps.GeocoderResult[];
}
```
## Loading the Library
Using the `MapGeocoder` requires the Geocoding API to be enabled in Google Cloud Console on the
same project as the one set up for the Google Maps JavaScript API, and requires an API key that
has billing enabled. See [here](https://developers.google.com/maps/documentation/javascript/geocoding#GetStarted) for details.
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {MapGeocoder} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
})
export class GoogleMapDemo {
constructor(geocoder: MapGeocoder) {
geocoder.geocode({
address: '1600 Amphitheatre Parkway, Mountain View, CA'
}).subscribe(({results}) => {
console.log(results);
});
}
}
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1444,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-geocoder/README.md"
}
|
components/src/google-maps/map-geocoder/map-geocoder.spec.ts_0_1395
|
import {TestBed} from '@angular/core/testing';
import {MapGeocoderResponse, MapGeocoder} from './map-geocoder';
import {createGeocoderConstructorSpy, createGeocoderSpy} from '../testing/fake-google-map-utils';
describe('MapGeocoder', () => {
let geocoder: MapGeocoder;
let geocoderConstructorSpy: jasmine.Spy;
let geocoderSpy: jasmine.SpyObj<google.maps.Geocoder>;
beforeEach(() => {
geocoderSpy = createGeocoderSpy();
geocoderConstructorSpy = createGeocoderConstructorSpy(geocoderSpy);
geocoder = TestBed.inject(MapGeocoder);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('does not initialize the Google Maps Geocoder immediately', () => {
expect(geocoderConstructorSpy).not.toHaveBeenCalled();
});
it('initializes the Google Maps Geocoder after `geocode` is called', () => {
geocoder.geocode({}).subscribe();
expect(geocoderConstructorSpy).toHaveBeenCalled();
});
it('calls geocode on inputs', () => {
const results: google.maps.GeocoderResult[] = [];
const status = 'OK' as google.maps.GeocoderStatus;
geocoderSpy.geocode.and.callFake((_request, callback) => {
callback?.(results, status);
return Promise.resolve({results});
});
geocoder.geocode({region: 'Europe'}).subscribe(response => {
expect(response).toEqual({results, status} as MapGeocoderResponse);
});
});
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1395,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-geocoder/map-geocoder.spec.ts"
}
|
components/src/google-maps/map-kml-layer/map-kml-layer.spec.ts_0_5397
|
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createKmlLayerConstructorSpy,
createKmlLayerSpy,
createMapConstructorSpy,
createMapSpy,
} from '../testing/fake-google-map-utils';
import {MapKmlLayer} from './map-kml-layer';
const DEMO_URL = 'www.test.kml';
const DEFAULT_KML_OPTIONS: google.maps.KmlLayerOptions = {
clickable: true,
preserveViewport: true,
url: DEMO_URL,
};
describe('MapKmlLayer', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map Kml Layer', fakeAsync(() => {
const kmlLayerSpy = createKmlLayerSpy({});
const kmlLayerConstructorSpy = createKmlLayerConstructorSpy(kmlLayerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(kmlLayerConstructorSpy).toHaveBeenCalledWith({url: undefined});
expect(kmlLayerSpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
it('sets url from input', fakeAsync(() => {
const options: google.maps.KmlLayerOptions = {url: DEMO_URL};
const kmlLayerSpy = createKmlLayerSpy(options);
const kmlLayerConstructorSpy = createKmlLayerConstructorSpy(kmlLayerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.url = DEMO_URL;
fixture.detectChanges();
flush();
expect(kmlLayerConstructorSpy).toHaveBeenCalledWith(options);
}));
it('gives precedence to url input over options', fakeAsync(() => {
const expectedUrl = 'www.realurl.kml';
const expectedOptions: google.maps.KmlLayerOptions = {...DEFAULT_KML_OPTIONS, url: expectedUrl};
const kmlLayerSpy = createKmlLayerSpy(expectedOptions);
const kmlLayerConstructorSpy = createKmlLayerConstructorSpy(kmlLayerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = DEFAULT_KML_OPTIONS;
fixture.componentInstance.url = expectedUrl;
fixture.detectChanges();
flush();
expect(kmlLayerConstructorSpy).toHaveBeenCalledWith(expectedOptions);
}));
it('exposes methods that provide information about the KmlLayer', fakeAsync(() => {
const kmlLayerSpy = createKmlLayerSpy(DEFAULT_KML_OPTIONS);
createKmlLayerConstructorSpy(kmlLayerSpy);
const fixture = TestBed.createComponent(TestApp);
const kmlLayerComponent = fixture.debugElement
.query(By.directive(MapKmlLayer))!
.injector.get<MapKmlLayer>(MapKmlLayer);
fixture.detectChanges();
flush();
kmlLayerComponent.getDefaultViewport();
expect(kmlLayerSpy.getDefaultViewport).toHaveBeenCalled();
const metadata: google.maps.KmlLayerMetadata = {
author: {
email: 'test@test.com',
name: 'author',
uri: 'www.author.com',
},
description: 'test',
hasScreenOverlays: true,
name: 'metadata',
snippet: '...',
};
kmlLayerSpy.getMetadata.and.returnValue(metadata);
expect(kmlLayerComponent.getMetadata()).toBe(metadata);
kmlLayerComponent.getStatus();
expect(kmlLayerSpy.getStatus).toHaveBeenCalled();
kmlLayerSpy.getUrl.and.returnValue(DEMO_URL);
expect(kmlLayerComponent.getUrl()).toBe(DEMO_URL);
kmlLayerSpy.getZIndex.and.returnValue(3);
expect(kmlLayerComponent.getZIndex()).toBe(3);
}));
it('initializes KmlLayer event handlers', fakeAsync(() => {
const kmlLayerSpy = createKmlLayerSpy(DEFAULT_KML_OPTIONS);
createKmlLayerConstructorSpy(kmlLayerSpy);
const addSpy = kmlLayerSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).toHaveBeenCalledWith('click', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('defaultviewport_changed', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('status_changed', jasmine.any(Function));
}));
it('should be able to add an event listener after init', fakeAsync(() => {
const kmlLayerSpy = createKmlLayerSpy(DEFAULT_KML_OPTIONS);
createKmlLayerConstructorSpy(kmlLayerSpy);
const addSpy = kmlLayerSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).not.toHaveBeenCalledWith('defaultviewport_changed', jasmine.any(Function));
// Pick an event that isn't bound in the template.
const subscription = fixture.componentInstance.kmlLayer.defaultviewportChanged.subscribe();
fixture.detectChanges();
expect(addSpy).toHaveBeenCalledWith('defaultviewport_changed', jasmine.any(Function));
subscription.unsubscribe();
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-kml-layer
[options]="options"
[url]="url"
(kmlClick)="handleClick()"
(statusChanged)="handleStatusChange()" />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapKmlLayer],
})
class TestApp {
@ViewChild(MapKmlLayer) kmlLayer: MapKmlLayer;
options?: google.maps.KmlLayerOptions;
url?: string;
handleClick() {}
handleStatusChange() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 5397,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-kml-layer/map-kml-layer.spec.ts"
}
|
components/src/google-maps/map-kml-layer/map-kml-layer.ts_0_6533
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Directive,
EventEmitter,
Input,
NgZone,
OnDestroy,
OnInit,
Output,
inject,
} from '@angular/core';
import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs';
import {map, take, takeUntil} from 'rxjs/operators';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
/**
* Angular component that renders a Google Maps KML Layer via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer
*/
@Directive({
selector: 'map-kml-layer',
exportAs: 'mapKmlLayer',
})
export class MapKmlLayer implements OnInit, OnDestroy {
private readonly _map = inject(GoogleMap);
private _ngZone = inject(NgZone);
private _eventManager = new MapEventManager(inject(NgZone));
private readonly _options = new BehaviorSubject<google.maps.KmlLayerOptions>({});
private readonly _url = new BehaviorSubject<string>('');
private readonly _destroyed = new Subject<void>();
/**
* The underlying google.maps.KmlLayer object.
*
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer
*/
kmlLayer?: google.maps.KmlLayer;
@Input()
set options(options: google.maps.KmlLayerOptions) {
this._options.next(options || {});
}
@Input()
set url(url: string) {
this._url.next(url);
}
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.click
*/
@Output() readonly kmlClick: Observable<google.maps.KmlMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.KmlMouseEvent>('click');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/kml
* #KmlLayer.defaultviewport_changed
*/
@Output() readonly defaultviewportChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('defaultviewport_changed');
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.status_changed
*/
@Output() readonly statusChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('status_changed');
/** Event emitted when the KML layer is initialized. */
@Output() readonly kmlLayerInitialized: EventEmitter<google.maps.KmlLayer> =
new EventEmitter<google.maps.KmlLayer>();
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (this._map._isBrowser) {
this._combineOptions()
.pipe(take(1))
.subscribe(options => {
if (google.maps.KmlLayer && this._map.googleMap) {
this._initialize(this._map.googleMap, google.maps.KmlLayer, options);
} else {
this._ngZone.runOutsideAngular(() => {
Promise.all([this._map._resolveMap(), google.maps.importLibrary('maps')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.MapsLibrary).KmlLayer, options);
},
);
});
}
});
}
}
private _initialize(
map: google.maps.Map,
layerConstructor: typeof google.maps.KmlLayer,
options: google.maps.KmlLayerOptions,
) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.kmlLayer = new layerConstructor(options);
this._assertInitialized();
this.kmlLayer.setMap(map);
this._eventManager.setTarget(this.kmlLayer);
this.kmlLayerInitialized.emit(this.kmlLayer);
this._watchForOptionsChanges();
this._watchForUrlChanges();
});
}
ngOnDestroy() {
this._eventManager.destroy();
this._destroyed.next();
this._destroyed.complete();
this.kmlLayer?.setMap(null);
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getDefaultViewport
*/
getDefaultViewport(): google.maps.LatLngBounds | null {
this._assertInitialized();
return this.kmlLayer.getDefaultViewport();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getMetadata
*/
getMetadata(): google.maps.KmlLayerMetadata | null {
this._assertInitialized();
return this.kmlLayer.getMetadata();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getStatus
*/
getStatus(): google.maps.KmlLayerStatus {
this._assertInitialized();
return this.kmlLayer.getStatus();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getUrl
*/
getUrl(): string {
this._assertInitialized();
return this.kmlLayer.getUrl();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer.getZIndex
*/
getZIndex(): number {
this._assertInitialized();
return this.kmlLayer.getZIndex();
}
private _combineOptions(): Observable<google.maps.KmlLayerOptions> {
return combineLatest([this._options, this._url]).pipe(
map(([options, url]) => {
const combinedOptions: google.maps.KmlLayerOptions = {
...options,
url: url || options.url,
};
return combinedOptions;
}),
);
}
private _watchForOptionsChanges() {
this._options.pipe(takeUntil(this._destroyed)).subscribe(options => {
if (this.kmlLayer) {
this._assertInitialized();
this.kmlLayer.setOptions(options);
}
});
}
private _watchForUrlChanges() {
this._url.pipe(takeUntil(this._destroyed)).subscribe(url => {
if (url && this.kmlLayer) {
this._assertInitialized();
this.kmlLayer.setUrl(url);
}
});
}
private _assertInitialized(): asserts this is {kmlLayer: google.maps.KmlLayer} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.kmlLayer) {
throw Error(
'Cannot interact with a Google Map KmlLayer before it has been ' +
'initialized. Please wait for the KmlLayer to load before trying to interact with it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 6533,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-kml-layer/map-kml-layer.ts"
}
|
components/src/google-maps/map-kml-layer/README.md_0_876
|
# MapKmlLayer
The `MapKmlLayer` component wraps the [`google.maps.KmlLayer` class](https://developers.google.com/maps/documentation/javascript/reference/kml#KmlLayer) from the Google Maps JavaScript API.
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapKmlLayer} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapKmlLayer],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
kmlUrl = 'https://developers.google.com/maps/documentation/javascript/examples/kml/westcampus.kml';
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map height="400px" width="750px" [center]="center" [zoom]="zoom">
<map-kml-layer [url]="kmlUrl" />
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 876,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-kml-layer/README.md"
}
|
components/src/google-maps/map-info-window/map-info-window.spec.ts_0_9073
|
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {MapMarker} from '../map-marker/map-marker';
import {
createInfoWindowConstructorSpy,
createInfoWindowSpy,
createMapConstructorSpy,
createMapSpy,
} from '../testing/fake-google-map-utils';
import {MapInfoWindow} from './map-info-window';
describe('MapInfoWindow', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map Info Window', fakeAsync(() => {
const infoWindowSpy = createInfoWindowSpy({});
const infoWindowConstructorSpy = createInfoWindowConstructorSpy(infoWindowSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
expect(infoWindowConstructorSpy).toHaveBeenCalledWith({
position: undefined,
content: jasmine.any(Node),
});
}));
it('sets position', fakeAsync(() => {
const position: google.maps.LatLngLiteral = {lat: 5, lng: 7};
const infoWindowSpy = createInfoWindowSpy({position});
const infoWindowConstructorSpy = createInfoWindowConstructorSpy(infoWindowSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.position = position;
fixture.detectChanges();
flush();
expect(infoWindowConstructorSpy).toHaveBeenCalledWith({
position,
content: jasmine.any(Node),
});
}));
it('sets options', fakeAsync(() => {
const options: google.maps.InfoWindowOptions = {
position: {lat: 3, lng: 5},
maxWidth: 50,
disableAutoPan: true,
};
const infoWindowSpy = createInfoWindowSpy(options);
const infoWindowConstructorSpy = createInfoWindowConstructorSpy(infoWindowSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = options;
fixture.detectChanges();
flush();
expect(infoWindowConstructorSpy).toHaveBeenCalledWith({
...options,
content: jasmine.any(Node),
});
}));
it('gives preference to position over options', fakeAsync(() => {
const position: google.maps.LatLngLiteral = {lat: 5, lng: 7};
const options: google.maps.InfoWindowOptions = {
position: {lat: 3, lng: 5},
maxWidth: 50,
disableAutoPan: true,
};
const infoWindowSpy = createInfoWindowSpy({...options, position});
const infoWindowConstructorSpy = createInfoWindowConstructorSpy(infoWindowSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = options;
fixture.componentInstance.position = position;
fixture.detectChanges();
flush();
expect(infoWindowConstructorSpy).toHaveBeenCalledWith({
...options,
position,
content: jasmine.any(Node),
});
}));
it('exposes methods that change the configuration of the info window', fakeAsync(() => {
const fakeMarker = {} as unknown as google.maps.Marker;
const fakeMarkerComponent = {
marker: fakeMarker,
getAnchor: () => fakeMarker,
} as unknown as MapMarker;
const infoWindowSpy = createInfoWindowSpy({});
createInfoWindowConstructorSpy(infoWindowSpy);
const fixture = TestBed.createComponent(TestApp);
const infoWindowComponent = fixture.debugElement
.query(By.directive(MapInfoWindow))!
.injector.get<MapInfoWindow>(MapInfoWindow);
fixture.detectChanges();
flush();
infoWindowComponent.close();
expect(infoWindowSpy.close).toHaveBeenCalled();
infoWindowComponent.open(fakeMarkerComponent);
expect(infoWindowSpy.open).toHaveBeenCalledWith(
jasmine.objectContaining({
map: mapSpy,
anchor: fakeMarker,
shouldFocus: undefined,
}),
);
}));
it('should not try to reopen info window multiple times for the same marker', fakeAsync(() => {
const fakeMarker = {} as unknown as google.maps.Marker;
const fakeMarkerComponent = {
marker: fakeMarker,
getAnchor: () => fakeMarker,
} as unknown as MapMarker;
const infoWindowSpy = createInfoWindowSpy({});
createInfoWindowConstructorSpy(infoWindowSpy);
const fixture = TestBed.createComponent(TestApp);
const infoWindowComponent = fixture.debugElement
.query(By.directive(MapInfoWindow))!
.injector.get<MapInfoWindow>(MapInfoWindow);
fixture.detectChanges();
flush();
infoWindowComponent.open(fakeMarkerComponent);
expect(infoWindowSpy.open).toHaveBeenCalledTimes(1);
infoWindowComponent.open(fakeMarkerComponent);
expect(infoWindowSpy.open).toHaveBeenCalledTimes(1);
infoWindowComponent.close();
infoWindowComponent.open(fakeMarkerComponent);
expect(infoWindowSpy.open).toHaveBeenCalledTimes(2);
}));
it('exposes methods that provide information about the info window', fakeAsync(() => {
const infoWindowSpy = createInfoWindowSpy({});
createInfoWindowConstructorSpy(infoWindowSpy);
const fixture = TestBed.createComponent(TestApp);
const infoWindowComponent = fixture.debugElement
.query(By.directive(MapInfoWindow))!
.injector.get<MapInfoWindow>(MapInfoWindow);
fixture.detectChanges();
flush();
infoWindowSpy.getContent.and.returnValue('test content');
expect(infoWindowComponent.getContent()).toBe('test content');
infoWindowComponent.getPosition();
expect(infoWindowSpy.getPosition).toHaveBeenCalled();
infoWindowSpy.getZIndex.and.returnValue(5);
expect(infoWindowComponent.getZIndex()).toBe(5);
}));
it('initializes info window event handlers', fakeAsync(() => {
const infoWindowSpy = createInfoWindowSpy({});
createInfoWindowConstructorSpy(infoWindowSpy);
const addSpy = infoWindowSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).toHaveBeenCalledWith('closeclick', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('content_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('domready', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('position_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('zindex_changed', jasmine.any(Function));
}));
it('should be able to add an event listener after init', fakeAsync(() => {
const infoWindowSpy = createInfoWindowSpy({});
createInfoWindowConstructorSpy(infoWindowSpy);
const addSpy = infoWindowSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).not.toHaveBeenCalledWith('zindex_changed', jasmine.any(Function));
// Pick an event that isn't bound in the template.
const subscription = fixture.componentInstance.infoWindow.zindexChanged.subscribe();
fixture.detectChanges();
expect(addSpy).toHaveBeenCalledWith('zindex_changed', jasmine.any(Function));
subscription.unsubscribe();
}));
it('should be able to open an info window without passing in an anchor', fakeAsync(() => {
const infoWindowSpy = createInfoWindowSpy({});
createInfoWindowConstructorSpy(infoWindowSpy);
const fixture = TestBed.createComponent(TestApp);
const infoWindowComponent = fixture.debugElement
.query(By.directive(MapInfoWindow))!
.injector.get<MapInfoWindow>(MapInfoWindow);
fixture.detectChanges();
flush();
infoWindowComponent.open();
expect(infoWindowSpy.open).toHaveBeenCalledTimes(1);
}));
it('should allow for the focus behavior to be changed when opening the info window', fakeAsync(() => {
const fakeMarker = {} as unknown as google.maps.Marker;
const fakeMarkerComponent = {
marker: fakeMarker,
getAnchor: () => fakeMarker,
} as unknown as MapMarker;
const infoWindowSpy = createInfoWindowSpy({});
createInfoWindowConstructorSpy(infoWindowSpy);
const fixture = TestBed.createComponent(TestApp);
const infoWindowComponent = fixture.debugElement
.query(By.directive(MapInfoWindow))!
.injector.get<MapInfoWindow>(MapInfoWindow);
fixture.detectChanges();
flush();
infoWindowComponent.open(fakeMarkerComponent, false);
expect(infoWindowSpy.open).toHaveBeenCalledWith(
jasmine.objectContaining({
shouldFocus: false,
}),
);
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-info-window [position]="position" [options]="options" (closeclick)="handleClose()">
test content
</map-info-window>
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapInfoWindow],
})
class TestApp {
@ViewChild(MapInfoWindow) infoWindow: MapInfoWindow;
position?: google.maps.LatLngLiteral;
options?: google.maps.InfoWindowOptions;
handleClose() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 9073,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-info-window/map-info-window.spec.ts"
}
|
components/src/google-maps/map-info-window/map-info-window.ts_0_8971
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Directive,
ElementRef,
EventEmitter,
Input,
NgZone,
OnDestroy,
OnInit,
Output,
inject,
} from '@angular/core';
import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs';
import {map, take, takeUntil} from 'rxjs/operators';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
import {MapAnchorPoint} from '../map-anchor-point';
/**
* Angular component that renders a Google Maps info window via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/info-window
*/
@Directive({
selector: 'map-info-window',
exportAs: 'mapInfoWindow',
host: {'style': 'display: none'},
})
export class MapInfoWindow implements OnInit, OnDestroy {
private readonly _googleMap = inject(GoogleMap);
private _elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
private _ngZone = inject(NgZone);
private _eventManager = new MapEventManager(inject(NgZone));
private readonly _options = new BehaviorSubject<google.maps.InfoWindowOptions>({});
private readonly _position = new BehaviorSubject<
google.maps.LatLngLiteral | google.maps.LatLng | undefined
>(undefined);
private readonly _destroy = new Subject<void>();
/**
* Underlying google.maps.InfoWindow
*
* See developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow
*/
infoWindow?: google.maps.InfoWindow;
@Input()
set options(options: google.maps.InfoWindowOptions) {
this._options.next(options || {});
}
@Input()
set position(position: google.maps.LatLngLiteral | google.maps.LatLng) {
this._position.next(position);
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.closeclick
*/
@Output() readonly closeclick: Observable<void> =
this._eventManager.getLazyEmitter<void>('closeclick');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/info-window
* #InfoWindow.content_changed
*/
@Output() readonly contentChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('content_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.domready
*/
@Output() readonly domready: Observable<void> =
this._eventManager.getLazyEmitter<void>('domready');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/info-window
* #InfoWindow.position_changed
*/
@Output() readonly positionChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('position_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/info-window
* #InfoWindow.zindex_changed
*/
@Output() readonly zindexChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('zindex_changed');
/** Event emitted when the info window is initialized. */
@Output() readonly infoWindowInitialized: EventEmitter<google.maps.InfoWindow> =
new EventEmitter<google.maps.InfoWindow>();
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (this._googleMap._isBrowser) {
this._combineOptions()
.pipe(take(1))
.subscribe(options => {
if (google.maps.InfoWindow) {
this._initialize(google.maps.InfoWindow, options);
} else {
this._ngZone.runOutsideAngular(() => {
google.maps.importLibrary('maps').then(lib => {
this._initialize((lib as google.maps.MapsLibrary).InfoWindow, options);
});
});
}
});
}
}
private _initialize(
infoWindowConstructor: typeof google.maps.InfoWindow,
options: google.maps.InfoWindowOptions,
) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.infoWindow = new infoWindowConstructor(options);
this._eventManager.setTarget(this.infoWindow);
this.infoWindowInitialized.emit(this.infoWindow);
this._watchForOptionsChanges();
this._watchForPositionChanges();
});
}
ngOnDestroy() {
this._eventManager.destroy();
this._destroy.next();
this._destroy.complete();
// If no info window has been created on the server, we do not try closing it.
// On the server, an info window cannot be created and this would cause errors.
if (this.infoWindow) {
this.close();
}
}
/**
* See developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.close
*/
close() {
this._assertInitialized();
this.infoWindow.close();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.getContent
*/
getContent(): string | Node | null {
this._assertInitialized();
return this.infoWindow.getContent() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/info-window
* #InfoWindow.getPosition
*/
getPosition(): google.maps.LatLng | null {
this._assertInitialized();
return this.infoWindow.getPosition() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow.getZIndex
*/
getZIndex(): number {
this._assertInitialized();
return this.infoWindow.getZIndex();
}
/**
* Opens the MapInfoWindow using the provided AdvancedMarkerElement.
* @deprecated Use the `open` method instead.
* @breaking-change 20.0.0
*/
openAdvancedMarkerElement(
advancedMarkerElement: google.maps.marker.AdvancedMarkerElement,
content?: string | Element | Text,
): void {
this.open(
{
getAnchor: () => advancedMarkerElement,
},
undefined,
content,
);
}
/**
* Opens the MapInfoWindow using the provided anchor. If the anchor is not set,
* then the position property of the options input is used instead.
*/
open(anchor?: MapAnchorPoint, shouldFocus?: boolean, content?: string | Element | Text): void {
this._assertInitialized();
if ((typeof ngDevMode === 'undefined' || ngDevMode) && anchor && !anchor.getAnchor) {
throw new Error(
'Specified anchor does not implement the `getAnchor` method. ' +
'It cannot be used to open an info window.',
);
}
const anchorObject = anchor ? anchor.getAnchor() : undefined;
// Prevent the info window from initializing when trying to reopen on the same anchor.
// Note that when the window is opened for the first time, the anchor will always be
// undefined. If that's the case, we have to allow it to open in order to handle the
// case where the window doesn't have an anchor, but is placed at a particular position.
if (this.infoWindow.get('anchor') !== anchorObject || !anchorObject) {
this._elementRef.nativeElement.style.display = '';
if (content) {
this.infoWindow.setContent(content);
}
this.infoWindow.open({
map: this._googleMap.googleMap,
anchor: anchorObject,
shouldFocus,
});
}
}
private _combineOptions(): Observable<google.maps.InfoWindowOptions> {
return combineLatest([this._options, this._position]).pipe(
map(([options, position]) => {
const combinedOptions: google.maps.InfoWindowOptions = {
...options,
position: position || options.position,
content: this._elementRef.nativeElement,
};
return combinedOptions;
}),
);
}
private _watchForOptionsChanges() {
this._options.pipe(takeUntil(this._destroy)).subscribe(options => {
this._assertInitialized();
this.infoWindow.setOptions(options);
});
}
private _watchForPositionChanges() {
this._position.pipe(takeUntil(this._destroy)).subscribe(position => {
if (position) {
this._assertInitialized();
this.infoWindow.setPosition(position);
}
});
}
private _assertInitialized(): asserts this is {infoWindow: google.maps.InfoWindow} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.infoWindow) {
throw Error(
'Cannot interact with a Google Map Info Window before it has been ' +
'initialized. Please wait for the Info Window to load before trying to interact with ' +
'it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 8971,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-info-window/map-info-window.ts"
}
|
components/src/google-maps/map-info-window/README.md_0_2109
|
## MapInfoWindow
The `MapInfoWindow` component wraps the [`google.maps.InfoWindow` class](https://developers.google.com/maps/documentation/javascript/reference/info-window#InfoWindow) from the Google Maps JavaScript API. The `MapInfoWindow` has an `options` input as well as a convenience `position` input. Content for the `MapInfoWindow` is the inner HTML of the component, and will keep the structure and css styling of any content that is put there when it is displayed as an info window on the map.
To display the `MapInfoWindow`, it must be a child of a `GoogleMap` component, and it must have its `open` method called, so a reference to `MapInfoWindow` will need to be loaded using the [`ViewChild` decorator](https://angular.dev/api/core/ViewChild) or via [`viewChild`](https://angular.dev/api/core/viewChild). The `open` method accepts an `MapMarker` as an optional input, if you want to anchor the `MapInfoWindow` to a `MapMarker`.
## Example
```typescript
// google-maps-demo.component.ts
import {Component, ViewChild} from '@angular/core';
import {GoogleMap, MapInfoWindow, MapMarker} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapInfoWindow, MapMarker],
})
export class GoogleMapDemo {
@ViewChild(MapInfoWindow) infoWindow: MapInfoWindow;
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
markerPositions: google.maps.LatLngLiteral[] = [];
zoom = 4;
addMarker(event: google.maps.MapMouseEvent) {
this.markerPositions.push(event.latLng.toJSON());
}
openInfoWindow(marker: MapMarker) {
this.infoWindow.open(marker);
}
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map
height="400px"
width="750px"
[center]="center"
[zoom]="zoom"
(mapClick)="addMarker($event)">
@for (position of markerPositions; track position) {
<map-advanced-marker
#marker="mapAdvancedMarker"
[position]="position"
(mapClick)="openInfoWindow(marker)" />
}
<map-info-window>Info Window content</map-info-window>
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2109,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-info-window/README.md"
}
|
components/src/google-maps/map-traffic-layer/map-traffic-layer.spec.ts_0_1520
|
import {Component} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createMapConstructorSpy,
createMapSpy,
createTrafficLayerConstructorSpy,
createTrafficLayerSpy,
} from '../testing/fake-google-map-utils';
import {MapTrafficLayer} from './map-traffic-layer';
describe('MapTrafficLayer', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
const trafficLayerOptions: google.maps.TrafficLayerOptions = {autoRefresh: false};
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map Traffic Layer', fakeAsync(() => {
const trafficLayerSpy = createTrafficLayerSpy(trafficLayerOptions);
const trafficLayerConstructorSpy = createTrafficLayerConstructorSpy(trafficLayerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.autoRefresh = false;
fixture.detectChanges();
flush();
expect(trafficLayerConstructorSpy).toHaveBeenCalledWith(trafficLayerOptions);
expect(trafficLayerSpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-traffic-layer [autoRefresh]="autoRefresh" />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapTrafficLayer],
})
class TestApp {
autoRefresh?: boolean;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1520,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-traffic-layer/map-traffic-layer.spec.ts"
}
|
components/src/google-maps/map-traffic-layer/README.md_0_842
|
# MapTrafficLayer
The `MapTrafficLayer` component wraps the [`google.maps.TrafficLayer` class](https://developers.google.com/maps/documentation/javascript/reference/map#TrafficLayer) from the Google Maps JavaScript API. `autoRefresh` is true by default.
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapTrafficLayer} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapTrafficLayer],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map height="400px" width="750px" [center]="center" [zoom]="zoom">
<map-traffic-layer [autoRefresh]="false" />
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 842,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-traffic-layer/README.md"
}
|
components/src/google-maps/map-traffic-layer/map-traffic-layer.ts_0_3897
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Directive,
EventEmitter,
Input,
NgZone,
OnDestroy,
OnInit,
Output,
inject,
} from '@angular/core';
import {BehaviorSubject, Observable, Subject} from 'rxjs';
import {map, take, takeUntil} from 'rxjs/operators';
import {GoogleMap} from '../google-map/google-map';
/**
* Angular component that renders a Google Maps Traffic Layer via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/map#TrafficLayer
*/
@Directive({
selector: 'map-traffic-layer',
exportAs: 'mapTrafficLayer',
})
export class MapTrafficLayer implements OnInit, OnDestroy {
private readonly _map = inject(GoogleMap);
private readonly _ngZone = inject(NgZone);
private readonly _autoRefresh = new BehaviorSubject<boolean>(true);
private readonly _destroyed = new Subject<void>();
/**
* The underlying google.maps.TrafficLayer object.
*
* See developers.google.com/maps/documentation/javascript/reference/map#TrafficLayer
*/
trafficLayer?: google.maps.TrafficLayer;
/**
* Whether the traffic layer refreshes with updated information automatically.
*/
@Input()
set autoRefresh(autoRefresh: boolean) {
this._autoRefresh.next(autoRefresh);
}
/** Event emitted when the traffic layer is initialized. */
@Output() readonly trafficLayerInitialized: EventEmitter<google.maps.TrafficLayer> =
new EventEmitter<google.maps.TrafficLayer>();
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (this._map._isBrowser) {
this._combineOptions()
.pipe(take(1))
.subscribe(options => {
if (google.maps.TrafficLayer && this._map.googleMap) {
this._initialize(this._map.googleMap, google.maps.TrafficLayer, options);
} else {
this._ngZone.runOutsideAngular(() => {
Promise.all([this._map._resolveMap(), google.maps.importLibrary('maps')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.MapsLibrary).TrafficLayer, options);
},
);
});
}
});
}
}
private _initialize(
map: google.maps.Map,
layerConstructor: typeof google.maps.TrafficLayer,
options: google.maps.TrafficLayerOptions,
) {
this._ngZone.runOutsideAngular(() => {
this.trafficLayer = new layerConstructor(options);
this._assertInitialized();
this.trafficLayer.setMap(map);
this.trafficLayerInitialized.emit(this.trafficLayer);
this._watchForAutoRefreshChanges();
});
}
ngOnDestroy() {
this._destroyed.next();
this._destroyed.complete();
this.trafficLayer?.setMap(null);
}
private _combineOptions(): Observable<google.maps.TrafficLayerOptions> {
return this._autoRefresh.pipe(
map(autoRefresh => {
const combinedOptions: google.maps.TrafficLayerOptions = {autoRefresh};
return combinedOptions;
}),
);
}
private _watchForAutoRefreshChanges() {
this._combineOptions()
.pipe(takeUntil(this._destroyed))
.subscribe(options => {
this._assertInitialized();
this.trafficLayer.setOptions(options);
});
}
private _assertInitialized(): asserts this is {trafficLayer: google.maps.TrafficLayer} {
if (!this.trafficLayer) {
throw Error(
'Cannot interact with a Google Map Traffic Layer before it has been initialized. ' +
'Please wait for the Traffic Layer to load before trying to interact with it.',
);
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 3897,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-traffic-layer/map-traffic-layer.ts"
}
|
components/src/google-maps/map-marker/README.md_0_1552
|
# MapMarker
The `MapMarker` component wraps the [`google.maps.Marker` class](https://developers.google.com/maps/documentation/javascript/reference/marker#Marker) from the Google Maps JavaScript API. The `MapMarker` component displays a marker on the map when it is a content child of a `GoogleMap` component. Like `GoogleMap`, this component offers an `options` input as well as convenience inputs for `position`, `title`, `label`, and `clickable`, and supports all `google.maps.Marker` events as outputs.
**Note:** As of 2024, Google Maps has deprecated the `Marker` class. Consider using the `map-advanced-marker` instead.
## Example
```typescript
// google-map-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapMarker} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapMarker],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
markerOptions: google.maps.MarkerOptions = {draggable: false};
markerPositions: google.maps.LatLngLiteral[] = [];
addMarker(event: google.maps.MapMouseEvent) {
this.markerPositions.push(event.latLng.toJSON());
}
}
```
```html
<!-- google-map-demo.component.html -->
<google-map
height="400px"
width="750px"
[center]="center"
[zoom]="zoom"
(mapClick)="addMarker($event)">
@for (position of markerPositions; track position) {
<map-marker [position]="position" [options]="markerOptions" />
}
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1552,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-marker/README.md"
}
|
components/src/google-maps/map-marker/map-marker.spec.ts_0_8879
|
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createMapConstructorSpy,
createMapSpy,
createMarkerConstructorSpy,
createMarkerSpy,
} from '../testing/fake-google-map-utils';
import {DEFAULT_MARKER_OPTIONS, MapMarker} from './map-marker';
describe('MapMarker', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map marker', fakeAsync(() => {
const markerSpy = createMarkerSpy(DEFAULT_MARKER_OPTIONS);
const markerConstructorSpy = createMarkerConstructorSpy(markerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(markerConstructorSpy).toHaveBeenCalledWith({
...DEFAULT_MARKER_OPTIONS,
title: undefined,
label: undefined,
clickable: undefined,
icon: undefined,
visible: undefined,
map: mapSpy,
});
}));
it('sets marker inputs', fakeAsync(() => {
const options: google.maps.MarkerOptions = {
position: {lat: 3, lng: 5},
title: 'marker title',
label: 'marker label',
clickable: false,
icon: 'icon.png',
visible: false,
map: mapSpy,
};
const markerSpy = createMarkerSpy(options);
const markerConstructorSpy = createMarkerConstructorSpy(markerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.position = options.position;
fixture.componentInstance.title = options.title;
fixture.componentInstance.label = options.label;
fixture.componentInstance.clickable = options.clickable;
fixture.componentInstance.icon = 'icon.png';
fixture.componentInstance.visible = false;
fixture.detectChanges();
flush();
expect(markerConstructorSpy).toHaveBeenCalledWith(options);
}));
it('sets marker options, ignoring map', fakeAsync(() => {
const options: google.maps.MarkerOptions = {
position: {lat: 3, lng: 5},
title: 'marker title',
label: 'marker label',
clickable: false,
icon: 'icon name',
visible: undefined,
};
const markerSpy = createMarkerSpy(options);
const markerConstructorSpy = createMarkerConstructorSpy(markerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = options;
fixture.detectChanges();
flush();
expect(markerConstructorSpy).toHaveBeenCalledWith({...options, map: mapSpy});
}));
it('gives precedence to specific inputs over options', fakeAsync(() => {
const options: google.maps.MarkerOptions = {
position: {lat: 3, lng: 5},
title: 'marker title',
label: 'marker label',
clickable: false,
icon: 'icon name',
};
const expectedOptions: google.maps.MarkerOptions = {
position: {lat: 5, lng: 12},
title: 'updated title',
label: 'updated label',
clickable: true,
icon: 'icon name',
map: mapSpy,
visible: undefined,
};
const markerSpy = createMarkerSpy(options);
const markerConstructorSpy = createMarkerConstructorSpy(markerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.position = expectedOptions.position;
fixture.componentInstance.title = expectedOptions.title;
fixture.componentInstance.label = expectedOptions.label;
fixture.componentInstance.clickable = expectedOptions.clickable;
fixture.componentInstance.options = options;
fixture.detectChanges();
flush();
expect(markerConstructorSpy).toHaveBeenCalledWith(expectedOptions);
}));
it('exposes methods that provide information about the marker', fakeAsync(() => {
const markerSpy = createMarkerSpy(DEFAULT_MARKER_OPTIONS);
createMarkerConstructorSpy(markerSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
const marker = fixture.componentInstance.marker;
markerSpy.getAnimation.and.returnValue(null);
expect(marker.getAnimation()).toBe(null);
markerSpy.getClickable.and.returnValue(true);
expect(marker.getClickable()).toBe(true);
markerSpy.getCursor.and.returnValue('cursor');
expect(marker.getCursor()).toBe('cursor');
markerSpy.getDraggable.and.returnValue(true);
expect(marker.getDraggable()).toBe(true);
markerSpy.getIcon.and.returnValue('icon');
expect(marker.getIcon()).toBe('icon');
markerSpy.getLabel.and.returnValue(null);
expect(marker.getLabel()).toBe(null);
markerSpy.getOpacity.and.returnValue(5);
expect(marker.getOpacity()).toBe(5);
markerSpy.getPosition.and.returnValue(null);
expect(marker.getPosition()).toEqual(null);
markerSpy.getShape.and.returnValue(null);
expect(marker.getShape()).toBe(null);
markerSpy.getTitle.and.returnValue('title');
expect(marker.getTitle()).toBe('title');
markerSpy.getVisible.and.returnValue(true);
expect(marker.getVisible()).toBe(true);
markerSpy.getZIndex.and.returnValue(2);
expect(marker.getZIndex()).toBe(2);
}));
it('initializes marker event handlers', fakeAsync(() => {
const markerSpy = createMarkerSpy(DEFAULT_MARKER_OPTIONS);
createMarkerConstructorSpy(markerSpy);
const addSpy = markerSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).toHaveBeenCalledWith('click', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('position_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('animation_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('clickable_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('cursor_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dblclick', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('drag', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragend', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('draggable_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragstart', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('flat_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('icon_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mousedown', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseout', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseover', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseup', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('rightclick', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('shape_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('title_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('visible_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('zindex_changed', jasmine.any(Function));
}));
it('should be able to add an event listener after init', fakeAsync(() => {
const markerSpy = createMarkerSpy(DEFAULT_MARKER_OPTIONS);
createMarkerConstructorSpy(markerSpy);
const addSpy = markerSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).not.toHaveBeenCalledWith('flat_changed', jasmine.any(Function));
// Pick an event that isn't bound in the template.
const subscription = fixture.componentInstance.marker.flatChanged.subscribe();
fixture.detectChanges();
expect(addSpy).toHaveBeenCalledWith('flat_changed', jasmine.any(Function));
subscription.unsubscribe();
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-marker
[title]="title"
[position]="position"
[label]="label"
[clickable]="clickable"
[options]="options"
[icon]="icon"
[visible]="visible"
(mapClick)="handleClick()"
(positionChanged)="handlePositionChanged()" />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapMarker],
})
class TestApp {
@ViewChild(MapMarker) marker: MapMarker;
title?: string | null;
position?: google.maps.LatLng | google.maps.LatLngLiteral | null;
label?: string | google.maps.MarkerLabel | null;
clickable?: boolean | null;
options?: google.maps.MarkerOptions;
icon?: string;
visible?: boolean;
handleClick() {}
handlePositionChanged() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 8879,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-marker/map-marker.spec.ts"
}
|
components/src/google-maps/map-marker/map-marker.ts_0_1320
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Input,
OnDestroy,
OnInit,
Output,
NgZone,
Directive,
OnChanges,
SimpleChanges,
inject,
EventEmitter,
} from '@angular/core';
import {Observable} from 'rxjs';
import {take} from 'rxjs/operators';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
import {MapAnchorPoint} from '../map-anchor-point';
import {MAP_MARKER, MarkerDirective} from '../marker-utilities';
/**
* Default options for the Google Maps marker component. Displays a marker
* at the Googleplex.
*/
export const DEFAULT_MARKER_OPTIONS = {
position: {lat: 37.421995, lng: -122.084092},
};
/**
* Angular component that renders a Google Maps marker via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/marker
*/
@Directive({
selector: 'map-marker',
exportAs: 'mapMarker',
providers: [
{
provide: MAP_MARKER,
useExisting: MapMarker,
},
],
})
export
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1320,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-marker/map-marker.ts"
}
|
components/src/google-maps/map-marker/map-marker.ts_1321_10288
|
class MapMarker implements OnInit, OnChanges, OnDestroy, MapAnchorPoint, MarkerDirective {
private readonly _googleMap = inject(GoogleMap);
private _ngZone = inject(NgZone);
private _eventManager = new MapEventManager(inject(NgZone));
/**
* Title of the marker.
* See: developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.title
*/
@Input()
set title(title: string) {
this._title = title;
}
private _title: string;
/**
* Position of the marker. See:
* developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.position
*/
@Input()
set position(position: google.maps.LatLngLiteral | google.maps.LatLng) {
this._position = position;
}
private _position: google.maps.LatLngLiteral | google.maps.LatLng;
/**
* Label for the marker.
* See: developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.label
*/
@Input()
set label(label: string | google.maps.MarkerLabel) {
this._label = label;
}
private _label: string | google.maps.MarkerLabel;
/**
* Whether the marker is clickable. See:
* developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.clickable
*/
@Input()
set clickable(clickable: boolean) {
this._clickable = clickable;
}
private _clickable: boolean;
/**
* Options used to configure the marker.
* See: developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions
*/
@Input()
set options(options: google.maps.MarkerOptions) {
this._options = options;
}
private _options: google.maps.MarkerOptions;
/**
* Icon to be used for the marker.
* See: https://developers.google.com/maps/documentation/javascript/reference/marker#Icon
*/
@Input()
set icon(icon: string | google.maps.Icon | google.maps.Symbol) {
this._icon = icon;
}
private _icon: string | google.maps.Icon | google.maps.Symbol;
/**
* Whether the marker is visible.
* See: developers.google.com/maps/documentation/javascript/reference/marker#MarkerOptions.visible
*/
@Input()
set visible(value: boolean) {
this._visible = value;
}
private _visible: boolean;
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.animation_changed
*/
@Output() readonly animationChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('animation_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.click
*/
@Output() readonly mapClick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('click');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.clickable_changed
*/
@Output() readonly clickableChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('clickable_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.cursor_changed
*/
@Output() readonly cursorChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('cursor_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.dblclick
*/
@Output() readonly mapDblclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dblclick');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.drag
*/
@Output() readonly mapDrag: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('drag');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.dragend
*/
@Output() readonly mapDragend: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragend');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.draggable_changed
*/
@Output() readonly draggableChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('draggable_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.dragstart
*/
@Output() readonly mapDragstart: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragstart');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.flat_changed
*/
@Output() readonly flatChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('flat_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.icon_changed
*/
@Output() readonly iconChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('icon_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.mousedown
*/
@Output() readonly mapMousedown: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mousedown');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.mouseout
*/
@Output() readonly mapMouseout: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseout');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.mouseover
*/
@Output() readonly mapMouseover: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseover');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.mouseup
*/
@Output() readonly mapMouseup: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseup');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.position_changed
*/
@Output() readonly positionChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('position_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.rightclick
*/
@Output() readonly mapRightclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('rightclick');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.shape_changed
*/
@Output() readonly shapeChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('shape_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.title_changed
*/
@Output() readonly titleChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('title_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.visible_changed
*/
@Output() readonly visibleChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('visible_changed');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.zindex_changed
*/
@Output() readonly zindexChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('zindex_changed');
/** Event emitted when the marker is initialized. */
@Output() readonly markerInitialized: EventEmitter<google.maps.Marker> =
new EventEmitter<google.maps.Marker>();
/**
* The underlying google.maps.Marker object.
*
* See developers.google.com/maps/documentation/javascript/reference/marker#Marker
*/
marker?: google.maps.Marker;
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (!this._googleMap._isBrowser) {
return;
}
if (google.maps.Marker && this._googleMap.googleMap) {
this._initialize(this._googleMap.googleMap, google.maps.Marker);
} else {
this._ngZone.runOutsideAngular(() => {
Promise.all([this._googleMap._resolveMap(), google.maps.importLibrary('marker')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.MarkerLibrary).Marker);
},
);
});
}
}
private _initialize(map: google.maps.Map, markerConstructor: typeof google.maps.Marker) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.marker = new markerConstructor(this._combineOptions());
this._assertInitialized();
this.marker.setMap(map);
this._eventManager.setTarget(this.marker);
this.markerInitialized.next(this.marker);
});
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 10288,
"start_byte": 1321,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-marker/map-marker.ts"
}
|
components/src/google-maps/map-marker/map-marker.ts_10292_15412
|
ngOnChanges(changes: SimpleChanges) {
const {marker, _title, _position, _label, _clickable, _icon, _visible} = this;
if (marker) {
if (changes['options']) {
marker.setOptions(this._combineOptions());
}
if (changes['title'] && _title !== undefined) {
marker.setTitle(_title);
}
if (changes['position'] && _position) {
marker.setPosition(_position);
}
if (changes['label'] && _label !== undefined) {
marker.setLabel(_label);
}
if (changes['clickable'] && _clickable !== undefined) {
marker.setClickable(_clickable);
}
if (changes['icon'] && _icon) {
marker.setIcon(_icon);
}
if (changes['visible'] && _visible !== undefined) {
marker.setVisible(_visible);
}
}
}
ngOnDestroy() {
this.markerInitialized.complete();
this._eventManager.destroy();
this.marker?.setMap(null);
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getAnimation
*/
getAnimation(): google.maps.Animation | null {
this._assertInitialized();
return this.marker.getAnimation() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getClickable
*/
getClickable(): boolean {
this._assertInitialized();
return this.marker.getClickable();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getCursor
*/
getCursor(): string | null {
this._assertInitialized();
return this.marker.getCursor() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getDraggable
*/
getDraggable(): boolean {
this._assertInitialized();
return !!this.marker.getDraggable();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getIcon
*/
getIcon(): string | google.maps.Icon | google.maps.Symbol | null {
this._assertInitialized();
return this.marker.getIcon() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getLabel
*/
getLabel(): google.maps.MarkerLabel | string | null {
this._assertInitialized();
return this.marker.getLabel() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getOpacity
*/
getOpacity(): number | null {
this._assertInitialized();
return this.marker.getOpacity() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getPosition
*/
getPosition(): google.maps.LatLng | null {
this._assertInitialized();
return this.marker.getPosition() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getShape
*/
getShape(): google.maps.MarkerShape | null {
this._assertInitialized();
return this.marker.getShape() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getTitle
*/
getTitle(): string | null {
this._assertInitialized();
return this.marker.getTitle() || null;
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getVisible
*/
getVisible(): boolean {
this._assertInitialized();
return this.marker.getVisible();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/marker#Marker.getZIndex
*/
getZIndex(): number | null {
this._assertInitialized();
return this.marker.getZIndex() || null;
}
/** Gets the anchor point that can be used to attach other Google Maps objects. */
getAnchor(): google.maps.MVCObject {
this._assertInitialized();
return this.marker;
}
/** Returns a promise that resolves when the marker has been initialized. */
_resolveMarker(): Promise<google.maps.Marker> {
return this.marker
? Promise.resolve(this.marker)
: this.markerInitialized.pipe(take(1)).toPromise();
}
/** Creates a combined options object using the passed-in options and the individual inputs. */
private _combineOptions(): google.maps.MarkerOptions {
const options = this._options || DEFAULT_MARKER_OPTIONS;
return {
...options,
title: this._title || options.title,
position: this._position || options.position,
label: this._label || options.label,
clickable: this._clickable ?? options.clickable,
map: this._googleMap.googleMap,
icon: this._icon || options.icon,
visible: this._visible ?? options.visible,
};
}
private _assertInitialized(): asserts this is {marker: google.maps.Marker} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.marker) {
throw Error(
'Cannot interact with a Google Map Marker before it has been ' +
'initialized. Please wait for the Marker to load before trying to interact with it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 15412,
"start_byte": 10292,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-marker/map-marker.ts"
}
|
components/src/google-maps/testing/fake-google-map-utils.ts_0_7833
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type {MarkerClusterer} from '../map-marker-clusterer/map-marker-clusterer-types';
import {MarkerClusterer as DeprecatedMarkerClusterer} from '../deprecated-map-marker-clusterer/deprecated-marker-clusterer-types';
// The global `window` variable is typed as an intersection of `Window` and `globalThis`.
// We re-declare `window` here and omit `globalThis` as it is typed with the actual Google
// Maps types which we intend to override with jasmine spies for testing. Keeping `globalThis`
// would mean that `window` is not assignable to our testing window.
declare var window: Window;
/** Window interface for testing */
export interface TestingWindow extends Window {
google?: {
maps: {
Map?: jasmine.Spy;
Marker?: jasmine.Spy;
InfoWindow?: jasmine.Spy;
Polyline?: jasmine.Spy;
Polygon?: jasmine.Spy;
Rectangle?: jasmine.Spy;
Circle?: jasmine.Spy;
GroundOverlay?: jasmine.Spy;
KmlLayer?: jasmine.Spy;
TrafficLayer?: jasmine.Spy;
TransitLayer?: jasmine.Spy;
BicyclingLayer?: jasmine.Spy;
DirectionsRenderer?: jasmine.Spy;
DirectionsService?: jasmine.Spy;
LatLng?: jasmine.Spy;
visualization?: {
HeatmapLayer?: jasmine.Spy;
};
marker?: {
AdvancedMarkerElement?: jasmine.Spy;
};
Geocoder?: jasmine.Spy;
};
};
MarkerClusterer?: jasmine.Spy;
markerClusterer?: {
MarkerClusterer?: jasmine.Spy;
defaultOnClusterClickHandler?: jasmine.Spy;
};
}
/** Creates a jasmine.SpyObj for a google.maps.Map. */
export function createMapSpy(options: google.maps.MapOptions): jasmine.SpyObj<google.maps.Map> {
const mapSpy = jasmine.createSpyObj('google.maps.Map', [
'setOptions',
'setCenter',
'setZoom',
'setMap',
'addListener',
'fitBounds',
'panBy',
'panTo',
'panToBounds',
'getBounds',
'getCenter',
'getClickableIcons',
'getHeading',
'getMapTypeId',
'getProjection',
'getStreetView',
'getTilt',
'getZoom',
'setMapTypeId',
]);
mapSpy.addListener.and.returnValue({remove: () => {}});
return mapSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.Map. */
export function createMapConstructorSpy(
mapSpy: jasmine.SpyObj<google.maps.Map>,
apiLoaded = true,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const mapConstructorSpy = jasmine
.createSpy('Map constructor', function () {
return mapSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (apiLoaded) {
testingWindow.google = {
maps: {
'Map': mapConstructorSpy,
},
};
}
return mapConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.Marker */
export function createMarkerSpy(
options: google.maps.MarkerOptions,
): jasmine.SpyObj<google.maps.Marker> {
const markerSpy = jasmine.createSpyObj('google.maps.Marker', [
'setOptions',
'setMap',
'addListener',
'getAnimation',
'getClickable',
'getCursor',
'getDraggable',
'getIcon',
'getLabel',
'getOpacity',
'getPosition',
'getShape',
'getTitle',
'getVisible',
'getZIndex',
]);
markerSpy.addListener.and.returnValue({remove: () => {}});
return markerSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.Marker */
export function createMarkerConstructorSpy(
markerSpy: jasmine.SpyObj<google.maps.Marker>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const markerConstructorSpy = jasmine
.createSpy('Marker constructor', function () {
return markerSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['Marker'] = markerConstructorSpy;
} else {
testingWindow.google = {
maps: {
'Marker': markerConstructorSpy,
},
};
}
return markerConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.marker.AdvancedMarkerElement */
export function createAdvancedMarkerSpy(
options: google.maps.marker.AdvancedMarkerElementOptions,
): jasmine.SpyObj<google.maps.marker.AdvancedMarkerElement> {
const advancedMarkerSpy = jasmine.createSpyObj('google.maps.marker.AdvancedMarkerElement', [
'addListener',
]);
advancedMarkerSpy.addListener.and.returnValue({remove: () => {}});
return advancedMarkerSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.marker.AdvancedMarkerElement */
export function createAdvancedMarkerConstructorSpy(
advancedMarkerSpy: jasmine.SpyObj<google.maps.marker.AdvancedMarkerElement>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const advancedMarkerConstructorSpy = jasmine
.createSpy('Advanced Marker constructor', function () {
return advancedMarkerSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps.marker = {
'AdvancedMarkerElement': advancedMarkerConstructorSpy,
};
} else {
testingWindow.google = {
maps: {
marker: {
'AdvancedMarkerElement': advancedMarkerConstructorSpy,
},
},
};
}
return advancedMarkerConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.InfoWindow */
export function createInfoWindowSpy(
options: google.maps.InfoWindowOptions,
): jasmine.SpyObj<google.maps.InfoWindow> {
let anchor: any;
const infoWindowSpy = jasmine.createSpyObj('google.maps.InfoWindow', [
'addListener',
'close',
'getContent',
'getPosition',
'getZIndex',
'open',
'get',
'setOptions',
'setPosition',
]);
infoWindowSpy.addListener.and.returnValue({remove: () => {}});
infoWindowSpy.open.and.callFake((config: any) => (anchor = config.anchor));
infoWindowSpy.close.and.callFake(() => (anchor = null));
infoWindowSpy.get.and.callFake((key: string) => (key === 'anchor' ? anchor : null));
return infoWindowSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.InfoWindow */
export function createInfoWindowConstructorSpy(
infoWindowSpy: jasmine.SpyObj<google.maps.InfoWindow>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const infoWindowConstructorSpy = jasmine
.createSpy('InfoWindow constructor', function () {
return infoWindowSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['InfoWindow'] = infoWindowConstructorSpy;
} else {
testingWindow.google = {
maps: {
'InfoWindow': infoWindowConstructorSpy,
},
};
}
return infoWindowConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.Polyline */
export function createPolylineSpy(
options: google.maps.PolylineOptions,
): jasmine.SpyObj<google.maps.Polyline> {
const polylineSpy = jasmine.createSpyObj('google.maps.Polyline', [
'addListener',
'getDraggable',
'getEditable',
'getPath',
'getVisible',
'setMap',
'setOptions',
'setPath',
]);
polylineSpy.addListener.and.returnValue({remove: () => {}});
return polylineSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.Polyline */
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 7833,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/testing/fake-google-map-utils.ts"
}
|
components/src/google-maps/testing/fake-google-map-utils.ts_7834_16293
|
export function createPolylineConstructorSpy(
polylineSpy: jasmine.SpyObj<google.maps.Polyline>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const polylineConstructorSpy = jasmine
.createSpy('Polyline constructor', function () {
return polylineSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['Polyline'] = polylineConstructorSpy;
} else {
testingWindow.google = {
maps: {
'Polyline': polylineConstructorSpy,
},
};
}
return polylineConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.Polygon */
export function createPolygonSpy(
options: google.maps.PolygonOptions,
): jasmine.SpyObj<google.maps.Polygon> {
const polygonSpy = jasmine.createSpyObj('google.maps.Polygon', [
'addListener',
'getDraggable',
'getEditable',
'getPath',
'getPaths',
'getVisible',
'setMap',
'setOptions',
'setPath',
'setPaths',
]);
polygonSpy.addListener.and.returnValue({remove: () => {}});
return polygonSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.Polygon */
export function createPolygonConstructorSpy(
polygonSpy: jasmine.SpyObj<google.maps.Polygon>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const polygonConstructorSpy = jasmine
.createSpy('Polygon constructor', function () {
return polygonSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['Polygon'] = polygonConstructorSpy;
} else {
testingWindow.google = {
maps: {
'Polygon': polygonConstructorSpy,
},
};
}
return polygonConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.Rectangle */
export function createRectangleSpy(
options: google.maps.RectangleOptions,
): jasmine.SpyObj<google.maps.Rectangle> {
const rectangleSpy = jasmine.createSpyObj('google.maps.Rectangle', [
'addListener',
'getBounds',
'getDraggable',
'getEditable',
'getVisible',
'setMap',
'setOptions',
'setBounds',
]);
rectangleSpy.addListener.and.returnValue({remove: () => {}});
return rectangleSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.Rectangle */
export function createRectangleConstructorSpy(
rectangleSpy: jasmine.SpyObj<google.maps.Rectangle>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const rectangleConstructorSpy = jasmine
.createSpy('Rectangle constructor', function () {
return rectangleSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['Rectangle'] = rectangleConstructorSpy;
} else {
testingWindow.google = {
maps: {
'Rectangle': rectangleConstructorSpy,
},
};
}
return rectangleConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.Circle */
export function createCircleSpy(
options: google.maps.CircleOptions,
): jasmine.SpyObj<google.maps.Circle> {
const circleSpy = jasmine.createSpyObj('google.maps.Circle', [
'addListener',
'getCenter',
'getRadius',
'getDraggable',
'getEditable',
'getVisible',
'setMap',
'setOptions',
'setCenter',
'setRadius',
]);
circleSpy.addListener.and.returnValue({remove: () => {}});
return circleSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.Circle */
export function createCircleConstructorSpy(
circleSpy: jasmine.SpyObj<google.maps.Circle>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const circleConstructorSpy = jasmine
.createSpy('Circle constructor', function () {
return circleSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['Circle'] = circleConstructorSpy;
} else {
testingWindow.google = {
maps: {
'Circle': circleConstructorSpy,
},
};
}
return circleConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.GroundOverlay */
export function createGroundOverlaySpy(
url: string,
bounds: google.maps.LatLngBoundsLiteral,
options?: google.maps.GroundOverlayOptions,
): jasmine.SpyObj<google.maps.GroundOverlay> {
const values: {[key: string]: any} = {url};
const groundOverlaySpy = jasmine.createSpyObj('google.maps.GroundOverlay', [
'addListener',
'getBounds',
'getOpacity',
'getUrl',
'setMap',
'setOpacity',
'set',
]);
groundOverlaySpy.addListener.and.returnValue({remove: () => {}});
groundOverlaySpy.set.and.callFake((key: string, value: any) => (values[key] = value));
return groundOverlaySpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.GroundOverlay */
export function createGroundOverlayConstructorSpy(
groundOverlaySpy: jasmine.SpyObj<google.maps.GroundOverlay>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const groundOverlayConstructorSpy = jasmine
.createSpy('GroundOverlay constructor', function () {
return groundOverlaySpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['GroundOverlay'] = groundOverlayConstructorSpy;
} else {
testingWindow.google = {
maps: {
'GroundOverlay': groundOverlayConstructorSpy,
},
};
}
return groundOverlayConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.KmlLayer */
export function createKmlLayerSpy(
options?: google.maps.KmlLayerOptions,
): jasmine.SpyObj<google.maps.KmlLayer> {
const kmlLayerSpy = jasmine.createSpyObj('google.maps.KmlLayer', [
'addListener',
'getDefaultViewport',
'getMetadata',
'getStatus',
'getUrl',
'getZIndex',
'setOptions',
'setUrl',
'setMap',
]);
kmlLayerSpy.addListener.and.returnValue({remove: () => {}});
return kmlLayerSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.KmlLayer */
export function createKmlLayerConstructorSpy(
kmlLayerSpy: jasmine.SpyObj<google.maps.KmlLayer>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const kmlLayerConstructorSpy = jasmine
.createSpy('KmlLayer constructor', function () {
return kmlLayerSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['KmlLayer'] = kmlLayerConstructorSpy;
} else {
testingWindow.google = {
maps: {
'KmlLayer': kmlLayerConstructorSpy,
},
};
}
return kmlLayerConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.TrafficLayer */
export function createTrafficLayerSpy(
options?: google.maps.TrafficLayerOptions,
): jasmine.SpyObj<google.maps.TrafficLayer> {
const trafficLayerSpy = jasmine.createSpyObj('google.maps.TrafficLayer', [
'setOptions',
'setMap',
]);
return trafficLayerSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.TrafficLayer */
export function createTrafficLayerConstructorSpy(
trafficLayerSpy: jasmine.SpyObj<google.maps.TrafficLayer>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const trafficLayerConstructorSpy = jasmine
.createSpy('TrafficLayer constructor', function () {
return trafficLayerSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['TrafficLayer'] = trafficLayerConstructorSpy;
} else {
testingWindow.google = {
maps: {
'TrafficLayer': trafficLayerConstructorSpy,
},
};
}
return trafficLayerConstructorSpy;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 16293,
"start_byte": 7834,
"url": "https://github.com/angular/components/blob/main/src/google-maps/testing/fake-google-map-utils.ts"
}
|
components/src/google-maps/testing/fake-google-map-utils.ts_16295_24693
|
/** Creates a jasmine.SpyObj for a google.maps.TransitLayer */
export function createTransitLayerSpy(): jasmine.SpyObj<google.maps.TransitLayer> {
const transitLayerSpy = jasmine.createSpyObj('google.maps.TransitLayer', ['setMap']);
return transitLayerSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.TransitLayer */
export function createTransitLayerConstructorSpy(
transitLayerSpy: jasmine.SpyObj<google.maps.TransitLayer>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const transitLayerConstructorSpy = jasmine
.createSpy('TransitLayer constructor', function () {
return transitLayerSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['TransitLayer'] = transitLayerConstructorSpy;
} else {
testingWindow.google = {
maps: {
'TransitLayer': transitLayerConstructorSpy,
},
};
}
return transitLayerConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.BicyclingLayer */
export function createBicyclingLayerSpy(): jasmine.SpyObj<google.maps.BicyclingLayer> {
const bicylingLayerSpy = jasmine.createSpyObj('google.maps.BicyclingLayer', ['setMap']);
return bicylingLayerSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.BicyclingLayer */
export function createBicyclingLayerConstructorSpy(
bicylingLayerSpy: jasmine.SpyObj<google.maps.BicyclingLayer>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const bicylingLayerConstructorSpy = jasmine
.createSpy('BicyclingLayer constructor', function () {
return bicylingLayerSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['BicyclingLayer'] = bicylingLayerConstructorSpy;
} else {
testingWindow.google = {
maps: {
'BicyclingLayer': bicylingLayerConstructorSpy,
},
};
}
return bicylingLayerConstructorSpy;
}
/** Creates a jasmine.SpyObj for a MarkerClusterer */
export function createMarkerClustererSpy(): jasmine.SpyObj<MarkerClusterer> {
return jasmine.createSpyObj('MarkerClusterer', [
'addMarker',
'addMarkers',
'removeMarker',
'removeMarkers',
'clearMarkers',
'render',
'onAdd',
'onRemove',
]);
}
/** Creates a jasmine.Spy to watch for the constructor of a MarkerClusterer */
export function createMarkerClustererConstructorSpy(
markerClustererSpy: jasmine.SpyObj<MarkerClusterer>,
apiLoaded = true,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const markerClustererConstructorSpy = jasmine.createSpy(
'MarkerClusterer constructor',
function () {
return markerClustererSpy;
},
);
if (apiLoaded) {
const testingWindow: TestingWindow = window;
testingWindow.markerClusterer = {
MarkerClusterer: markerClustererConstructorSpy,
defaultOnClusterClickHandler: jasmine.createSpy('defaultOnClusterClickHandler'),
};
}
return markerClustererConstructorSpy;
}
/** Creates a jasmine.SpyObj for a MarkerClusterer */
export function createDeprecatedMarkerClustererSpy(): jasmine.SpyObj<DeprecatedMarkerClusterer> {
const deprecatedMarkerClustererSpy = jasmine.createSpyObj('DeprecatedMarkerClusterer', [
'addListener',
'addMarkers',
'fitMapToMarkers',
'getAverageCenter',
'getBatchSizeIE',
'getCalculator',
'getClusterClass',
'getClusters',
'getEnableRetinaIcons',
'getGridSize',
'getIgnoreHidden',
'getImageExtension',
'getImagePath',
'getImageSizes',
'getMaxZoom',
'getMinimumClusterSize',
'getStyles',
'getTitle',
'getTotalClusters',
'getTotalMarkers',
'getZIndex',
'getZoomOnClick',
'removeMarkers',
'repaint',
'setAverageCenter',
'setBatchSizeIE',
'setCalculator',
'setClusterClass',
'setEnableRetinaIcons',
'setGridSize',
'setIgnoreHidden',
'setImageExtension',
'setImagePath',
'setImageSizes',
'setMap',
'setMaxZoom',
'setMinimumClusterSize',
'setStyles',
'setTitle',
'setZIndex',
'setZoomOnClick',
'setOptions',
]);
deprecatedMarkerClustererSpy.addListener.and.returnValue({remove: () => {}});
return deprecatedMarkerClustererSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a MarkerClusterer */
export function createDeprecatedMarkerClustererConstructorSpy(
deprecatedMarkerClustererSpy: jasmine.SpyObj<DeprecatedMarkerClusterer>,
apiLoaded = true,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const deprecatedMarkerClustererConstructorSpy = jasmine
.createSpy('DeprecatedMarkerClusterer constructor', function () {
return deprecatedMarkerClustererSpy;
})
.and.callThrough();
if (apiLoaded) {
const testingWindow: TestingWindow = window;
testingWindow['MarkerClusterer'] = deprecatedMarkerClustererConstructorSpy;
}
return deprecatedMarkerClustererConstructorSpy;
}
/** Creates a jasmine.SpyObj for DirectionsRenderer */
export function createDirectionsRendererSpy(
options: google.maps.DirectionsRendererOptions,
): jasmine.SpyObj<google.maps.DirectionsRenderer> {
const directionsRendererSpy = jasmine.createSpyObj('google.maps.DirectionsRenderer', [
'addListener',
'getDirections',
'getPanel',
'getRouteIndex',
'setDirections',
'setMap',
'setOptions',
]);
directionsRendererSpy.addListener.and.returnValue({remove: () => {}});
return directionsRendererSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of a DirectionsRenderer */
export function createDirectionsRendererConstructorSpy(
directionsRendererSpy: jasmine.SpyObj<google.maps.DirectionsRenderer>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const directionsRendererConstructorSpy = jasmine
.createSpy('DirectionsRenderer constructor', function () {
return directionsRendererSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['DirectionsRenderer'] = directionsRendererConstructorSpy;
} else {
testingWindow.google = {
maps: {
'DirectionsRenderer': directionsRendererConstructorSpy,
},
};
}
return directionsRendererConstructorSpy;
}
/** Creates a jasmine.SpyObj for the DirectionsService */
export function createDirectionsServiceSpy(): jasmine.SpyObj<google.maps.DirectionsService> {
const directionsServiceSpy = jasmine.createSpyObj('google.maps.DirectionsService', ['route']);
return directionsServiceSpy;
}
/** Creates a jasmine.Spy to watch for the constructor of the DirectionsService */
export function createDirectionsServiceConstructorSpy(
directionsServiceSpy: jasmine.SpyObj<google.maps.DirectionsService>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const directionsServiceConstructorSpy = jasmine
.createSpy('DirectionsService constructor', function () {
return directionsServiceSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['DirectionsService'] = directionsServiceConstructorSpy;
} else {
testingWindow.google = {
maps: {
'DirectionsService': directionsServiceConstructorSpy,
},
};
}
return directionsServiceConstructorSpy;
}
/** Creates a jasmine.SpyObj for a `google.maps.visualization.HeatmapLayer`. */
export function createHeatmapLayerSpy(): jasmine.SpyObj<google.maps.visualization.HeatmapLayer> {
const heatmapLayerSpy = jasmine.createSpyObj('google.maps.visualization.HeatmapLayer', [
'setMap',
'setOptions',
'setData',
'getData',
]);
return heatmapLayerSpy;
}
/**
* Creates a jasmine.Spy to watch for the constructor
* of a `google.maps.visualization.HeatmapLayer`.
*/
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 24693,
"start_byte": 16295,
"url": "https://github.com/angular/components/blob/main/src/google-maps/testing/fake-google-map-utils.ts"
}
|
components/src/google-maps/testing/fake-google-map-utils.ts_24694_27540
|
export function createHeatmapLayerConstructorSpy(
heatmapLayerSpy: jasmine.SpyObj<google.maps.visualization.HeatmapLayer>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const heatmapLayerConstructorSpy = jasmine
.createSpy('HeatmapLayer constructor', function () {
return heatmapLayerSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
if (!testingWindow.google.maps.visualization) {
testingWindow.google.maps.visualization = {};
}
testingWindow.google.maps.visualization['HeatmapLayer'] = heatmapLayerConstructorSpy;
} else {
testingWindow.google = {
maps: {
visualization: {
'HeatmapLayer': heatmapLayerConstructorSpy,
},
},
};
}
return heatmapLayerConstructorSpy;
}
/** Creates a jasmine.SpyObj for a google.maps.LatLng. */
export function createLatLngSpy(): jasmine.SpyObj<google.maps.LatLng> {
return jasmine.createSpyObj('google.maps.LatLng', ['equals', 'lat', 'lng']);
}
/** Creates a jasmine.Spy to watch for the constructor of a google.maps.LatLng */
export function createLatLngConstructorSpy(
latLngSpy: jasmine.SpyObj<google.maps.LatLng>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const latLngConstructorSpy = jasmine
.createSpy('LatLng constructor', function () {
return latLngSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['LatLng'] = latLngConstructorSpy;
} else {
testingWindow.google = {
maps: {
'LatLng': latLngConstructorSpy,
},
};
}
return latLngConstructorSpy;
}
/** Creates a jasmine.SpyObj for the Geocoder */
export function createGeocoderSpy(): jasmine.SpyObj<google.maps.Geocoder> {
return jasmine.createSpyObj('google.maps.Geocoder', ['geocode']);
}
/** Creates a jasmine.Spy to watch for the constructor of the Geocoder. */
export function createGeocoderConstructorSpy(
geocoderSpy: jasmine.SpyObj<google.maps.Geocoder>,
): jasmine.Spy {
// The spy target function cannot be an arrow-function as this breaks when created through `new`.
const geocoderConstructorSpy = jasmine
.createSpy('Geocoder constructor', function () {
return geocoderSpy;
})
.and.callThrough();
const testingWindow: TestingWindow = window;
if (testingWindow.google && testingWindow.google.maps) {
testingWindow.google.maps['Geocoder'] = geocoderConstructorSpy;
} else {
testingWindow.google = {
maps: {
'Geocoder': geocoderConstructorSpy,
},
};
}
return geocoderConstructorSpy;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 27540,
"start_byte": 24694,
"url": "https://github.com/angular/components/blob/main/src/google-maps/testing/fake-google-map-utils.ts"
}
|
components/src/google-maps/testing/BUILD.bazel_0_303
|
load("//tools:defaults.bzl", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "testing",
testonly = True,
srcs = glob(["**/*.ts"]),
deps = [
"//src/google-maps",
"@npm//@types/google.maps",
"@npm//@types/jasmine",
],
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 303,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/testing/BUILD.bazel"
}
|
components/src/google-maps/map-circle/map-circle.ts_0_875
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Directive,
EventEmitter,
Input,
NgZone,
OnDestroy,
OnInit,
Output,
inject,
} from '@angular/core';
import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs';
import {map, take, takeUntil} from 'rxjs/operators';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
/**
* Angular component that renders a Google Maps Circle via the Google Maps JavaScript API.
* @see developers.google.com/maps/documentation/javascript/reference/polygon#Circle
*/
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 875,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-circle/map-circle.ts"
}
|
components/src/google-maps/map-circle/map-circle.ts_876_9990
|
@Directive({
selector: 'map-circle',
exportAs: 'mapCircle',
})
export class MapCircle implements OnInit, OnDestroy {
private readonly _map = inject(GoogleMap);
private readonly _ngZone = inject(NgZone);
private _eventManager = new MapEventManager(inject(NgZone));
private readonly _options = new BehaviorSubject<google.maps.CircleOptions>({});
private readonly _center = new BehaviorSubject<
google.maps.LatLng | google.maps.LatLngLiteral | undefined
>(undefined);
private readonly _radius = new BehaviorSubject<number | undefined>(undefined);
private readonly _destroyed = new Subject<void>();
/**
* Underlying google.maps.Circle object.
*
* @see developers.google.com/maps/documentation/javascript/reference/polygon#Circle
*/
circle?: google.maps.Circle; // initialized in ngOnInit
@Input()
set options(options: google.maps.CircleOptions) {
this._options.next(options || {});
}
@Input()
set center(center: google.maps.LatLng | google.maps.LatLngLiteral) {
this._center.next(center);
}
@Input()
set radius(radius: number) {
this._radius.next(radius);
}
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.center_changed
*/
@Output() readonly centerChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('center_changed');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.click
*/
@Output() readonly circleClick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('click');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.dblclick
*/
@Output() readonly circleDblclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dblclick');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.drag
*/
@Output() readonly circleDrag: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('drag');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.dragend
*/
@Output() readonly circleDragend: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragend');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.dragstart
*/
@Output() readonly circleDragstart: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragstart');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.mousedown
*/
@Output() readonly circleMousedown: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mousedown');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.mousemove
*/
@Output() readonly circleMousemove: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mousemove');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.mouseout
*/
@Output() readonly circleMouseout: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseout');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.mouseover
*/
@Output() readonly circleMouseover: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseover');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.mouseup
*/
@Output() readonly circleMouseup: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseup');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.radius_changed
*/
@Output() readonly radiusChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('radius_changed');
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.rightclick
*/
@Output() readonly circleRightclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('rightclick');
/** Event emitted when the circle is initialized. */
@Output() readonly circleInitialized: EventEmitter<google.maps.Circle> =
new EventEmitter<google.maps.Circle>();
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (!this._map._isBrowser) {
return;
}
this._combineOptions()
.pipe(take(1))
.subscribe(options => {
if (google.maps.Circle && this._map.googleMap) {
this._initialize(this._map.googleMap, google.maps.Circle, options);
} else {
this._ngZone.runOutsideAngular(() => {
Promise.all([this._map._resolveMap(), google.maps.importLibrary('maps')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.MapsLibrary).Circle, options);
},
);
});
}
});
}
private _initialize(
map: google.maps.Map,
circleConstructor: typeof google.maps.Circle,
options: google.maps.CircleOptions,
) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.circle = new circleConstructor(options);
this._assertInitialized();
this.circle.setMap(map);
this._eventManager.setTarget(this.circle);
this.circleInitialized.emit(this.circle);
this._watchForOptionsChanges();
this._watchForCenterChanges();
this._watchForRadiusChanges();
});
}
ngOnDestroy() {
this._eventManager.destroy();
this._destroyed.next();
this._destroyed.complete();
this.circle?.setMap(null);
}
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.getBounds
*/
getBounds(): google.maps.LatLngBounds | null {
this._assertInitialized();
return this.circle.getBounds();
}
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.getCenter
*/
getCenter(): google.maps.LatLng | null {
this._assertInitialized();
return this.circle.getCenter();
}
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.getDraggable
*/
getDraggable(): boolean {
this._assertInitialized();
return this.circle.getDraggable();
}
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.getEditable
*/
getEditable(): boolean {
this._assertInitialized();
return this.circle.getEditable();
}
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.getRadius
*/
getRadius(): number {
this._assertInitialized();
return this.circle.getRadius();
}
/**
* @see
* developers.google.com/maps/documentation/javascript/reference/polygon#Circle.getVisible
*/
getVisible(): boolean {
this._assertInitialized();
return this.circle.getVisible();
}
private _combineOptions(): Observable<google.maps.CircleOptions> {
return combineLatest([this._options, this._center, this._radius]).pipe(
map(([options, center, radius]) => {
const combinedOptions: google.maps.CircleOptions = {
...options,
center: center || options.center,
radius: radius !== undefined ? radius : options.radius,
};
return combinedOptions;
}),
);
}
private _watchForOptionsChanges() {
this._options.pipe(takeUntil(this._destroyed)).subscribe(options => {
this._assertInitialized();
this.circle.setOptions(options);
});
}
private _watchForCenterChanges() {
this._center.pipe(takeUntil(this._destroyed)).subscribe(center => {
if (center) {
this._assertInitialized();
this.circle.setCenter(center);
}
});
}
private _watchForRadiusChanges() {
this._radius.pipe(takeUntil(this._destroyed)).subscribe(radius => {
if (radius !== undefined) {
this._assertInitialized();
this.circle.setRadius(radius);
}
});
}
private _assertInitialized(): asserts this is {circle: google.maps.Circle} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.circle) {
throw Error(
'Cannot interact with a Google Map Circle before it has been ' +
'initialized. Please wait for the Circle to load before trying to interact with it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 9990,
"start_byte": 876,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-circle/map-circle.ts"
}
|
components/src/google-maps/map-circle/README.md_0_870
|
# MapCircle
The `MapCircle` component wraps the [`google.maps.Circle` class](https://developers.google.com/maps/documentation/javascript/reference/polygon#Circle) from the Google Maps JavaScript API.
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapCircle} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapCircle],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
circleCenter: google.maps.LatLngLiteral = {lat: 10, lng: 15};
radius = 3;
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map height="400px" width="750px" [center]="center" [zoom]="zoom">
<map-circle [center]="circleCenter" [radius]="radius" />
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 870,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-circle/README.md"
}
|
components/src/google-maps/map-circle/map-circle.spec.ts_0_6303
|
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createCircleConstructorSpy,
createCircleSpy,
createMapConstructorSpy,
createMapSpy,
} from '../testing/fake-google-map-utils';
import {MapCircle} from './map-circle';
describe('MapCircle', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
let circleCenter: google.maps.LatLngLiteral;
let circleRadius: number;
let circleOptions: google.maps.CircleOptions;
beforeEach(() => {
circleCenter = {lat: 30, lng: 15};
circleRadius = 15;
circleOptions = {
center: circleCenter,
radius: circleRadius,
strokeColor: 'grey',
strokeOpacity: 0.8,
};
});
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map Circle', fakeAsync(() => {
const circleSpy = createCircleSpy({});
const circleConstructorSpy = createCircleConstructorSpy(circleSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(circleConstructorSpy).toHaveBeenCalledWith({center: undefined, radius: undefined});
expect(circleSpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
it('sets center and radius from input', fakeAsync(() => {
const center: google.maps.LatLngLiteral = {lat: 3, lng: 5};
const radius = 15;
const options: google.maps.CircleOptions = {center, radius};
const circleSpy = createCircleSpy(options);
const circleConstructorSpy = createCircleConstructorSpy(circleSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.center = center;
fixture.componentInstance.radius = radius;
fixture.detectChanges();
flush();
expect(circleConstructorSpy).toHaveBeenCalledWith(options);
}));
it('gives precedence to other inputs over options', fakeAsync(() => {
const center: google.maps.LatLngLiteral = {lat: 3, lng: 5};
const radius = 15;
const expectedOptions: google.maps.CircleOptions = {...circleOptions, center, radius};
const circleSpy = createCircleSpy(expectedOptions);
const circleConstructorSpy = createCircleConstructorSpy(circleSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = circleOptions;
fixture.componentInstance.center = center;
fixture.componentInstance.radius = radius;
fixture.detectChanges();
flush();
expect(circleConstructorSpy).toHaveBeenCalledWith(expectedOptions);
}));
it('exposes methods that provide information about the Circle', fakeAsync(() => {
const circleSpy = createCircleSpy(circleOptions);
createCircleConstructorSpy(circleSpy);
const fixture = TestBed.createComponent(TestApp);
const circleComponent = fixture.debugElement
.query(By.directive(MapCircle))!
.injector.get<MapCircle>(MapCircle);
fixture.detectChanges();
flush();
circleComponent.getCenter();
expect(circleSpy.getCenter).toHaveBeenCalled();
circleSpy.getRadius.and.returnValue(10);
expect(circleComponent.getRadius()).toBe(10);
circleSpy.getDraggable.and.returnValue(true);
expect(circleComponent.getDraggable()).toBe(true);
circleSpy.getEditable.and.returnValue(true);
expect(circleComponent.getEditable()).toBe(true);
circleSpy.getVisible.and.returnValue(true);
expect(circleComponent.getVisible()).toBe(true);
}));
it('initializes Circle event handlers', fakeAsync(() => {
const circleSpy = createCircleSpy(circleOptions);
createCircleConstructorSpy(circleSpy);
const addSpy = circleSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).toHaveBeenCalledWith('center_changed', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('click', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dblclick', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('drag', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragend', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragstart', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mousedown', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mousemove', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseout', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseover', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseup', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('radius_changed', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('rightclick', jasmine.any(Function));
}));
it('should be able to add an event listener after init', fakeAsync(() => {
const circleSpy = createCircleSpy(circleOptions);
createCircleConstructorSpy(circleSpy);
const addSpy = circleSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).not.toHaveBeenCalledWith('dragend', jasmine.any(Function));
// Pick an event that isn't bound in the template.
const subscription = fixture.componentInstance.circle.circleDragend.subscribe();
fixture.detectChanges();
expect(addSpy).toHaveBeenCalledWith('dragend', jasmine.any(Function));
subscription.unsubscribe();
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-circle
[options]="options"
[center]="center"
[radius]="radius"
(centerChanged)="handleCenterChange()"
(circleClick)="handleClick()"
(circleRightclick)="handleRightclick()" />
</google-map>`,
standalone: true,
imports: [GoogleMap, MapCircle],
})
class TestApp {
@ViewChild(MapCircle) circle: MapCircle;
options?: google.maps.CircleOptions;
center?: google.maps.LatLngLiteral;
radius?: number;
handleCenterChange() {}
handleClick() {}
handleRightclick() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 6303,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-circle/map-circle.spec.ts"
}
|
components/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.spec.ts_0_716
|
import {Component, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush} from '@angular/core/testing';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {MapMarker} from '../map-marker/map-marker';
import {
createMapConstructorSpy,
createMapSpy,
createDeprecatedMarkerClustererConstructorSpy,
createDeprecatedMarkerClustererSpy,
createMarkerConstructorSpy,
createMarkerSpy,
} from '../testing/fake-google-map-utils';
import {DeprecatedMapMarkerClusterer} from './deprecated-map-marker-clusterer';
import {
AriaLabelFn,
Calculator,
ClusterIconStyle,
MarkerClusterer,
MarkerClustererOptions,
} from './deprecated-marker-clusterer-types';
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 716,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.spec.ts"
}
|
components/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.spec.ts_718_10720
|
describe('DeprecatedMapMarkerClusterer', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
let markerClustererSpy: jasmine.SpyObj<MarkerClusterer>;
let markerClustererConstructorSpy: jasmine.Spy;
let fixture: ComponentFixture<TestApp>;
const anyMarkerMatcher = jasmine.any(Object) as unknown as google.maps.Marker;
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
const markerSpy = createMarkerSpy({});
// The spy target function cannot be an arrow-function as this breaks when created
// through `new`.
createMarkerConstructorSpy(markerSpy).and.callFake(function () {
return createMarkerSpy({});
});
markerClustererSpy = createDeprecatedMarkerClustererSpy();
markerClustererConstructorSpy =
createDeprecatedMarkerClustererConstructorSpy(markerClustererSpy);
fixture = TestBed.createComponent(TestApp);
});
afterEach(() => {
(window.google as any) = undefined;
(window as any).MarkerClusterer = undefined;
});
it('throws an error if the clustering library has not been loaded', fakeAsync(() => {
(window as any).MarkerClusterer = undefined;
markerClustererConstructorSpy = createDeprecatedMarkerClustererConstructorSpy(
markerClustererSpy,
false,
);
expect(() => {
fixture.detectChanges();
flush();
}).toThrowError(/MarkerClusterer class not found, cannot construct a marker cluster/);
}));
it('initializes a Google Map Marker Clusterer', fakeAsync(() => {
fixture.detectChanges();
flush();
expect(markerClustererConstructorSpy).toHaveBeenCalledWith(mapSpy, [], {
ariaLabelFn: undefined,
averageCenter: undefined,
batchSize: undefined,
batchSizeIE: undefined,
calculator: undefined,
clusterClass: undefined,
enableRetinaIcons: undefined,
gridSize: undefined,
ignoreHidden: undefined,
imageExtension: undefined,
imagePath: undefined,
imageSizes: undefined,
maxZoom: undefined,
minimumClusterSize: undefined,
styles: undefined,
title: undefined,
zIndex: undefined,
zoomOnClick: undefined,
});
}));
it('sets marker clusterer inputs', fakeAsync(() => {
fixture.componentInstance.ariaLabelFn = (testString: string) => testString;
fixture.componentInstance.averageCenter = true;
fixture.componentInstance.batchSize = 1;
fixture.componentInstance.clusterClass = 'testClusterClass';
fixture.componentInstance.enableRetinaIcons = true;
fixture.componentInstance.gridSize = 2;
fixture.componentInstance.ignoreHidden = true;
fixture.componentInstance.imageExtension = 'testImageExtension';
fixture.componentInstance.imagePath = 'testImagePath';
fixture.componentInstance.imageSizes = [3];
fixture.componentInstance.maxZoom = 4;
fixture.componentInstance.minimumClusterSize = 5;
fixture.componentInstance.styles = [];
fixture.componentInstance.title = 'testTitle';
fixture.componentInstance.zIndex = 6;
fixture.componentInstance.zoomOnClick = true;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(markerClustererConstructorSpy).toHaveBeenCalledWith(mapSpy, [], {
ariaLabelFn: jasmine.any(Function),
averageCenter: true,
batchSize: 1,
batchSizeIE: undefined,
calculator: undefined,
clusterClass: 'testClusterClass',
enableRetinaIcons: true,
gridSize: 2,
ignoreHidden: true,
imageExtension: 'testImageExtension',
imagePath: 'testImagePath',
imageSizes: [3],
maxZoom: 4,
minimumClusterSize: 5,
styles: [],
title: 'testTitle',
zIndex: 6,
zoomOnClick: true,
});
}));
it('sets marker clusterer options', fakeAsync(() => {
fixture.detectChanges();
flush();
const options: MarkerClustererOptions = {
enableRetinaIcons: true,
gridSize: 1337,
ignoreHidden: true,
imageExtension: 'png',
};
fixture.componentInstance.options = options;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(markerClustererSpy.setOptions).toHaveBeenCalledWith(jasmine.objectContaining(options));
}));
it('gives precedence to specific inputs over options', fakeAsync(() => {
fixture.detectChanges();
flush();
const options: MarkerClustererOptions = {
enableRetinaIcons: true,
gridSize: 1337,
ignoreHidden: true,
imageExtension: 'png',
};
const expectedOptions: MarkerClustererOptions = {
enableRetinaIcons: false,
gridSize: 42,
ignoreHidden: false,
imageExtension: 'jpeg',
};
fixture.componentInstance.enableRetinaIcons = expectedOptions.enableRetinaIcons;
fixture.componentInstance.gridSize = expectedOptions.gridSize;
fixture.componentInstance.ignoreHidden = expectedOptions.ignoreHidden;
fixture.componentInstance.imageExtension = expectedOptions.imageExtension;
fixture.componentInstance.options = options;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(markerClustererSpy.setOptions).toHaveBeenCalledWith(
jasmine.objectContaining(expectedOptions),
);
}));
it('sets Google Maps Markers in the MarkerClusterer', fakeAsync(() => {
fixture.detectChanges();
flush();
expect(markerClustererSpy.addMarkers).toHaveBeenCalledWith([
anyMarkerMatcher,
anyMarkerMatcher,
]);
}));
it('updates Google Maps Markers in the Marker Clusterer', fakeAsync(() => {
fixture.detectChanges();
flush();
expect(markerClustererSpy.addMarkers).toHaveBeenCalledWith([
anyMarkerMatcher,
anyMarkerMatcher,
]);
fixture.componentInstance.state = 'state2';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(markerClustererSpy.addMarkers).toHaveBeenCalledWith([anyMarkerMatcher], true);
expect(markerClustererSpy.removeMarkers).toHaveBeenCalledWith([anyMarkerMatcher], true);
expect(markerClustererSpy.repaint).toHaveBeenCalledTimes(1);
fixture.componentInstance.state = 'state0';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(markerClustererSpy.addMarkers).toHaveBeenCalledWith([], true);
expect(markerClustererSpy.removeMarkers).toHaveBeenCalledWith(
[anyMarkerMatcher, anyMarkerMatcher],
true,
);
expect(markerClustererSpy.repaint).toHaveBeenCalledTimes(2);
}));
it('exposes marker clusterer methods', fakeAsync(() => {
fixture.detectChanges();
flush();
const markerClustererComponent = fixture.componentInstance.markerClusterer;
markerClustererComponent.fitMapToMarkers(5);
expect(markerClustererSpy.fitMapToMarkers).toHaveBeenCalledWith(5);
markerClustererSpy.getAverageCenter.and.returnValue(true);
expect(markerClustererComponent.getAverageCenter()).toBe(true);
markerClustererSpy.getBatchSizeIE.and.returnValue(6);
expect(markerClustererComponent.getBatchSizeIE()).toBe(6);
const calculator = (markers: google.maps.Marker[], count: number) => ({
index: 1,
text: 'testText',
title: 'testTitle',
});
markerClustererSpy.getCalculator.and.returnValue(calculator);
expect(markerClustererComponent.getCalculator()).toBe(calculator);
markerClustererSpy.getClusterClass.and.returnValue('testClusterClass');
expect(markerClustererComponent.getClusterClass()).toBe('testClusterClass');
markerClustererSpy.getClusters.and.returnValue([]);
expect(markerClustererComponent.getClusters()).toEqual([]);
markerClustererSpy.getEnableRetinaIcons.and.returnValue(true);
expect(markerClustererComponent.getEnableRetinaIcons()).toBe(true);
markerClustererSpy.getGridSize.and.returnValue(7);
expect(markerClustererComponent.getGridSize()).toBe(7);
markerClustererSpy.getIgnoreHidden.and.returnValue(true);
expect(markerClustererComponent.getIgnoreHidden()).toBe(true);
markerClustererSpy.getImageExtension.and.returnValue('testImageExtension');
expect(markerClustererComponent.getImageExtension()).toBe('testImageExtension');
markerClustererSpy.getImagePath.and.returnValue('testImagePath');
expect(markerClustererComponent.getImagePath()).toBe('testImagePath');
markerClustererSpy.getImageSizes.and.returnValue([]);
expect(markerClustererComponent.getImageSizes()).toEqual([]);
markerClustererSpy.getMaxZoom.and.returnValue(8);
expect(markerClustererComponent.getMaxZoom()).toBe(8);
markerClustererSpy.getMinimumClusterSize.and.returnValue(9);
expect(markerClustererComponent.getMinimumClusterSize()).toBe(9);
markerClustererSpy.getStyles.and.returnValue([]);
expect(markerClustererComponent.getStyles()).toEqual([]);
markerClustererSpy.getTitle.and.returnValue('testTitle');
expect(markerClustererComponent.getTitle()).toBe('testTitle');
markerClustererSpy.getTotalClusters.and.returnValue(10);
expect(markerClustererComponent.getTotalClusters()).toBe(10);
markerClustererSpy.getTotalMarkers.and.returnValue(11);
expect(markerClustererComponent.getTotalMarkers()).toBe(11);
markerClustererSpy.getZIndex.and.returnValue(12);
expect(markerClustererComponent.getZIndex()).toBe(12);
markerClustererSpy.getZoomOnClick.and.returnValue(true);
expect(markerClustererComponent.getZoomOnClick()).toBe(true);
}));
it('initializes marker clusterer event handlers', fakeAsync(() => {
fixture.detectChanges();
flush();
expect(markerClustererSpy.addListener).toHaveBeenCalledWith(
'clusteringbegin',
jasmine.any(Function),
);
expect(markerClustererSpy.addListener).not.toHaveBeenCalledWith(
'clusteringend',
jasmine.any(Function),
);
expect(markerClustererSpy.addListener).toHaveBeenCalledWith('click', jasmine.any(Function));
}));
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 10720,
"start_byte": 718,
"url": "https://github.com/angular/components/blob/main/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.spec.ts"
}
|
components/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.spec.ts_10722_12643
|
@Component({
selector: 'test-app',
template: `
<google-map>
<deprecated-map-marker-clusterer
[ariaLabelFn]="ariaLabelFn"
[averageCenter]="averageCenter"
[batchSize]="batchSize"
[batchSizeIE]="batchSizeIE"
[calculator]="calculator"
[clusterClass]="clusterClass"
[enableRetinaIcons]="enableRetinaIcons"
[gridSize]="gridSize"
[ignoreHidden]="ignoreHidden"
[imageExtension]="imageExtension"
[imagePath]="imagePath"
[imageSizes]="imageSizes"
[maxZoom]="maxZoom"
[minimumClusterSize]="minimumClusterSize"
[styles]="styles"
[title]="title"
[zIndex]="zIndex"
[zoomOnClick]="zoomOnClick"
[options]="options"
(clusteringbegin)="onClusteringBegin()"
(clusterClick)="onClusterClick()">
@if (state === 'state1') {
<map-marker />
}
@if (state === 'state1' || state === 'state2') {
<map-marker />
}
@if (state === 'state2') {
<map-marker />
}
</deprecated-map-marker-clusterer>
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapMarker, DeprecatedMapMarkerClusterer],
})
class TestApp {
@ViewChild(DeprecatedMapMarkerClusterer) markerClusterer: DeprecatedMapMarkerClusterer;
ariaLabelFn?: AriaLabelFn;
averageCenter?: boolean;
batchSize?: number;
batchSizeIE?: number;
calculator?: Calculator;
clusterClass?: string;
enableRetinaIcons?: boolean;
gridSize?: number;
ignoreHidden?: boolean;
imageExtension?: string;
imagePath?: string;
imageSizes?: number[];
maxZoom?: number;
minimumClusterSize?: number;
styles?: ClusterIconStyle[];
title?: string;
zIndex?: number;
zoomOnClick?: boolean;
options?: MarkerClustererOptions;
state = 'state1';
onClusteringBegin() {}
onClusterClick() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 12643,
"start_byte": 10722,
"url": "https://github.com/angular/components/blob/main/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.spec.ts"
}
|
components/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.ts_0_1984
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
AfterContentInit,
ChangeDetectionStrategy,
Component,
ContentChildren,
EventEmitter,
Input,
NgZone,
OnChanges,
OnDestroy,
OnInit,
Output,
QueryList,
SimpleChanges,
ViewEncapsulation,
inject,
} from '@angular/core';
import {Observable, Subject} from 'rxjs';
import {take, takeUntil} from 'rxjs/operators';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
import {MapMarker} from '../map-marker/map-marker';
import {
AriaLabelFn,
Calculator,
Cluster,
ClusterIconStyle,
MarkerClusterer as MarkerClustererInstance,
MarkerClustererOptions,
} from './deprecated-marker-clusterer-types';
/** Default options for a clusterer. */
const DEFAULT_CLUSTERER_OPTIONS: MarkerClustererOptions = {};
/**
* The clusterer has to be defined and referred to as a global variable,
* otherwise it'll cause issues when minified through Closure.
*/
declare const MarkerClusterer: typeof MarkerClustererInstance;
/**
* Angular component for implementing a Google Maps Marker Clusterer.
* See https://developers.google.com/maps/documentation/javascript/marker-clustering
*
* @deprecated This component is using a deprecated clustering implementation. Use the
* `map-marker-clusterer` component instead.
* @breaking-change 21.0.0
*
*/
@Component({
selector: 'deprecated-map-marker-clusterer',
exportAs: 'mapMarkerClusterer',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content/>',
encapsulation: ViewEncapsulation.None,
})
export class DeprecatedMapMarkerClusterer
implements OnInit, AfterContentInit, OnChanges, OnDestroy
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1984,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.ts"
}
|
components/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.ts_1985_10153
|
{
private readonly _googleMap = inject(GoogleMap);
private readonly _ngZone = inject(NgZone);
private readonly _currentMarkers = new Set<google.maps.Marker>();
private readonly _eventManager = new MapEventManager(inject(NgZone));
private readonly _destroy = new Subject<void>();
/** Whether the clusterer is allowed to be initialized. */
private readonly _canInitialize = this._googleMap._isBrowser;
@Input()
ariaLabelFn: AriaLabelFn = () => '';
@Input()
set averageCenter(averageCenter: boolean) {
this._averageCenter = averageCenter;
}
private _averageCenter: boolean;
@Input() batchSize?: number;
@Input()
set batchSizeIE(batchSizeIE: number) {
this._batchSizeIE = batchSizeIE;
}
private _batchSizeIE: number;
@Input()
set calculator(calculator: Calculator) {
this._calculator = calculator;
}
private _calculator: Calculator;
@Input()
set clusterClass(clusterClass: string) {
this._clusterClass = clusterClass;
}
private _clusterClass: string;
@Input()
set enableRetinaIcons(enableRetinaIcons: boolean) {
this._enableRetinaIcons = enableRetinaIcons;
}
private _enableRetinaIcons: boolean;
@Input()
set gridSize(gridSize: number) {
this._gridSize = gridSize;
}
private _gridSize: number;
@Input()
set ignoreHidden(ignoreHidden: boolean) {
this._ignoreHidden = ignoreHidden;
}
private _ignoreHidden: boolean;
@Input()
set imageExtension(imageExtension: string) {
this._imageExtension = imageExtension;
}
private _imageExtension: string;
@Input()
set imagePath(imagePath: string) {
this._imagePath = imagePath;
}
private _imagePath: string;
@Input()
set imageSizes(imageSizes: number[]) {
this._imageSizes = imageSizes;
}
private _imageSizes: number[];
@Input()
set maxZoom(maxZoom: number) {
this._maxZoom = maxZoom;
}
private _maxZoom: number;
@Input()
set minimumClusterSize(minimumClusterSize: number) {
this._minimumClusterSize = minimumClusterSize;
}
private _minimumClusterSize: number;
@Input()
set styles(styles: ClusterIconStyle[]) {
this._styles = styles;
}
private _styles: ClusterIconStyle[];
@Input()
set title(title: string) {
this._title = title;
}
private _title: string;
@Input()
set zIndex(zIndex: number) {
this._zIndex = zIndex;
}
private _zIndex: number;
@Input()
set zoomOnClick(zoomOnClick: boolean) {
this._zoomOnClick = zoomOnClick;
}
private _zoomOnClick: boolean;
@Input()
set options(options: MarkerClustererOptions) {
this._options = options;
}
private _options: MarkerClustererOptions;
/**
* See
* googlemaps.github.io/v3-utility-library/modules/
* _google_markerclustererplus.html#clusteringbegin
*/
@Output() readonly clusteringbegin: Observable<void> =
this._eventManager.getLazyEmitter<void>('clusteringbegin');
/**
* See
* googlemaps.github.io/v3-utility-library/modules/_google_markerclustererplus.html#clusteringend
*/
@Output() readonly clusteringend: Observable<void> =
this._eventManager.getLazyEmitter<void>('clusteringend');
/** Emits when a cluster has been clicked. */
@Output()
readonly clusterClick: Observable<Cluster> = this._eventManager.getLazyEmitter<Cluster>('click');
@ContentChildren(MapMarker, {descendants: true}) _markers: QueryList<MapMarker>;
/**
* The underlying MarkerClusterer object.
*
* See
* googlemaps.github.io/v3-utility-library/classes/
* _google_markerclustererplus.markerclusterer.html
*/
markerClusterer?: MarkerClustererInstance;
/** Event emitted when the clusterer is initialized. */
@Output() readonly markerClustererInitialized: EventEmitter<MarkerClustererInstance> =
new EventEmitter<MarkerClustererInstance>();
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (this._canInitialize) {
this._ngZone.runOutsideAngular(() => {
this._googleMap._resolveMap().then(map => {
if (
typeof MarkerClusterer !== 'function' &&
(typeof ngDevMode === 'undefined' || ngDevMode)
) {
throw Error(
'MarkerClusterer class not found, cannot construct a marker cluster. ' +
'Please install the MarkerClustererPlus library: ' +
'https://github.com/googlemaps/js-markerclustererplus',
);
}
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this.markerClusterer = this._ngZone.runOutsideAngular(() => {
return new MarkerClusterer(map, [], this._combineOptions());
});
this._assertInitialized();
this._eventManager.setTarget(this.markerClusterer);
this.markerClustererInitialized.emit(this.markerClusterer);
});
});
}
}
ngAfterContentInit() {
if (this._canInitialize) {
if (this.markerClusterer) {
this._watchForMarkerChanges();
} else {
this.markerClustererInitialized
.pipe(take(1), takeUntil(this._destroy))
.subscribe(() => this._watchForMarkerChanges());
}
}
}
ngOnChanges(changes: SimpleChanges) {
const {
markerClusterer: clusterer,
ariaLabelFn,
_averageCenter,
_batchSizeIE,
_calculator,
_styles,
_clusterClass,
_enableRetinaIcons,
_gridSize,
_ignoreHidden,
_imageExtension,
_imagePath,
_imageSizes,
_maxZoom,
_minimumClusterSize,
_title,
_zIndex,
_zoomOnClick,
} = this;
if (clusterer) {
if (changes['options']) {
clusterer.setOptions(this._combineOptions());
}
if (changes['ariaLabelFn']) {
clusterer.ariaLabelFn = ariaLabelFn;
}
if (changes['averageCenter'] && _averageCenter !== undefined) {
clusterer.setAverageCenter(_averageCenter);
}
if (changes['batchSizeIE'] && _batchSizeIE !== undefined) {
clusterer.setBatchSizeIE(_batchSizeIE);
}
if (changes['calculator'] && !!_calculator) {
clusterer.setCalculator(_calculator);
}
if (changes['clusterClass'] && _clusterClass !== undefined) {
clusterer.setClusterClass(_clusterClass);
}
if (changes['enableRetinaIcons'] && _enableRetinaIcons !== undefined) {
clusterer.setEnableRetinaIcons(_enableRetinaIcons);
}
if (changes['gridSize'] && _gridSize !== undefined) {
clusterer.setGridSize(_gridSize);
}
if (changes['ignoreHidden'] && _ignoreHidden !== undefined) {
clusterer.setIgnoreHidden(_ignoreHidden);
}
if (changes['imageExtension'] && _imageExtension !== undefined) {
clusterer.setImageExtension(_imageExtension);
}
if (changes['imagePath'] && _imagePath !== undefined) {
clusterer.setImagePath(_imagePath);
}
if (changes['imageSizes'] && _imageSizes) {
clusterer.setImageSizes(_imageSizes);
}
if (changes['maxZoom'] && _maxZoom !== undefined) {
clusterer.setMaxZoom(_maxZoom);
}
if (changes['minimumClusterSize'] && _minimumClusterSize !== undefined) {
clusterer.setMinimumClusterSize(_minimumClusterSize);
}
if (changes['styles'] && _styles) {
clusterer.setStyles(_styles);
}
if (changes['title'] && _title !== undefined) {
clusterer.setTitle(_title);
}
if (changes['zIndex'] && _zIndex !== undefined) {
clusterer.setZIndex(_zIndex);
}
if (changes['zoomOnClick'] && _zoomOnClick !== undefined) {
clusterer.setZoomOnClick(_zoomOnClick);
}
}
}
ngOnDestroy() {
this._destroy.next();
this._destroy.complete();
this._eventManager.destroy();
this.markerClusterer?.setMap(null);
}
fitMapToMarkers(padding: number | google.maps.Padding) {
this._assertInitialized();
this.markerClusterer.fitMapToMarkers(padding);
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 10153,
"start_byte": 1985,
"url": "https://github.com/angular/components/blob/main/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.ts"
}
|
components/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.ts_10157_15857
|
getAverageCenter(): boolean {
this._assertInitialized();
return this.markerClusterer.getAverageCenter();
}
getBatchSizeIE(): number {
this._assertInitialized();
return this.markerClusterer.getBatchSizeIE();
}
getCalculator(): Calculator {
this._assertInitialized();
return this.markerClusterer.getCalculator();
}
getClusterClass(): string {
this._assertInitialized();
return this.markerClusterer.getClusterClass();
}
getClusters(): Cluster[] {
this._assertInitialized();
return this.markerClusterer.getClusters();
}
getEnableRetinaIcons(): boolean {
this._assertInitialized();
return this.markerClusterer.getEnableRetinaIcons();
}
getGridSize(): number {
this._assertInitialized();
return this.markerClusterer.getGridSize();
}
getIgnoreHidden(): boolean {
this._assertInitialized();
return this.markerClusterer.getIgnoreHidden();
}
getImageExtension(): string {
this._assertInitialized();
return this.markerClusterer.getImageExtension();
}
getImagePath(): string {
this._assertInitialized();
return this.markerClusterer.getImagePath();
}
getImageSizes(): number[] {
this._assertInitialized();
return this.markerClusterer.getImageSizes();
}
getMaxZoom(): number {
this._assertInitialized();
return this.markerClusterer.getMaxZoom();
}
getMinimumClusterSize(): number {
this._assertInitialized();
return this.markerClusterer.getMinimumClusterSize();
}
getStyles(): ClusterIconStyle[] {
this._assertInitialized();
return this.markerClusterer.getStyles();
}
getTitle(): string {
this._assertInitialized();
return this.markerClusterer.getTitle();
}
getTotalClusters(): number {
this._assertInitialized();
return this.markerClusterer.getTotalClusters();
}
getTotalMarkers(): number {
this._assertInitialized();
return this.markerClusterer.getTotalMarkers();
}
getZIndex(): number {
this._assertInitialized();
return this.markerClusterer.getZIndex();
}
getZoomOnClick(): boolean {
this._assertInitialized();
return this.markerClusterer.getZoomOnClick();
}
private _combineOptions(): MarkerClustererOptions {
const options = this._options || DEFAULT_CLUSTERER_OPTIONS;
return {
...options,
ariaLabelFn: this.ariaLabelFn ?? options.ariaLabelFn,
averageCenter: this._averageCenter ?? options.averageCenter,
batchSize: this.batchSize ?? options.batchSize,
batchSizeIE: this._batchSizeIE ?? options.batchSizeIE,
calculator: this._calculator ?? options.calculator,
clusterClass: this._clusterClass ?? options.clusterClass,
enableRetinaIcons: this._enableRetinaIcons ?? options.enableRetinaIcons,
gridSize: this._gridSize ?? options.gridSize,
ignoreHidden: this._ignoreHidden ?? options.ignoreHidden,
imageExtension: this._imageExtension ?? options.imageExtension,
imagePath: this._imagePath ?? options.imagePath,
imageSizes: this._imageSizes ?? options.imageSizes,
maxZoom: this._maxZoom ?? options.maxZoom,
minimumClusterSize: this._minimumClusterSize ?? options.minimumClusterSize,
styles: this._styles ?? options.styles,
title: this._title ?? options.title,
zIndex: this._zIndex ?? options.zIndex,
zoomOnClick: this._zoomOnClick ?? options.zoomOnClick,
};
}
private _watchForMarkerChanges() {
this._assertInitialized();
this._ngZone.runOutsideAngular(() => {
this._getInternalMarkers(this._markers).then(markers => {
const initialMarkers: google.maps.Marker[] = [];
for (const marker of markers) {
this._currentMarkers.add(marker);
initialMarkers.push(marker);
}
this.markerClusterer.addMarkers(initialMarkers);
});
});
this._markers.changes
.pipe(takeUntil(this._destroy))
.subscribe((markerComponents: MapMarker[]) => {
this._assertInitialized();
this._ngZone.runOutsideAngular(() => {
this._getInternalMarkers(markerComponents).then(markers => {
const newMarkers = new Set(markers);
const markersToAdd: google.maps.Marker[] = [];
const markersToRemove: google.maps.Marker[] = [];
for (const marker of Array.from(newMarkers)) {
if (!this._currentMarkers.has(marker)) {
this._currentMarkers.add(marker);
markersToAdd.push(marker);
}
}
for (const marker of Array.from(this._currentMarkers)) {
if (!newMarkers.has(marker)) {
markersToRemove.push(marker);
}
}
this.markerClusterer.addMarkers(markersToAdd, true);
this.markerClusterer.removeMarkers(markersToRemove, true);
this.markerClusterer.repaint();
for (const marker of markersToRemove) {
this._currentMarkers.delete(marker);
}
});
});
});
}
private _getInternalMarkers(
markers: MapMarker[] | QueryList<MapMarker>,
): Promise<google.maps.Marker[]> {
return Promise.all(markers.map(markerComponent => markerComponent._resolveMarker()));
}
private _assertInitialized(): asserts this is {markerClusterer: MarkerClustererInstance} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.markerClusterer) {
throw Error(
'Cannot interact with a MarkerClusterer before it has been initialized. ' +
'Please wait for the MarkerClusterer to load before trying to interact with it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 15857,
"start_byte": 10157,
"url": "https://github.com/angular/components/blob/main/src/google-maps/deprecated-map-marker-clusterer/deprecated-map-marker-clusterer.ts"
}
|
components/src/google-maps/deprecated-map-marker-clusterer/README.md_0_2499
|
# Deprecation warning ⚠️
This component is based on the deprecated `@googlemaps/markerclustererplus` library. Use the `map-marker-clusterer` component instead.
## DeprecatedMapMarkerClusterer
The `DeprecatedMapMarkerClusterer` component wraps the [`MarkerClusterer` class](https://googlemaps.github.io/js-markerclustererplus/classes/markerclusterer.html) from the [Google Maps JavaScript MarkerClustererPlus Library](https://github.com/googlemaps/js-markerclustererplus). The `DeprecatedMapMarkerClusterer` component displays a cluster of markers that are children of the `<deprecated-map-marker-clusterer>` tag. Unlike the other Google Maps components, MapMarkerClusterer does not have an `options` input, so any input (listed in the [documentation](https://googlemaps.github.io/js-markerclustererplus/index.html) for the `MarkerClusterer` class) should be set directly.
## Loading the Library
Like the Google Maps JavaScript API, the MarkerClustererPlus library needs to be loaded separately. This can be accomplished by using this script tag:
```html
<script src="https://unpkg.com/@googlemaps/markerclustererplus/dist/index.min.js"></script>
```
Additional information can be found by looking at [Marker Clustering](https://developers.google.com/maps/documentation/javascript/marker-clustering) in the Google Maps JavaScript API documentation.
## Example
```typescript
// google-map-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapMarker, DeprecatedMapMarkerClusterer} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapMarker, DeprecatedMapMarkerClusterer],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
markerPositions: google.maps.LatLngLiteral[] = [];
markerClustererImagePath =
'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m';
addMarker(event: google.maps.MapMouseEvent) {
this.markerPositions.push(event.latLng.toJSON());
}
}
```
```html
<!-- google-map-demo.component.html -->
<google-map
height="400px"
width="750px"
[center]="center"
[zoom]="zoom"
(mapClick)="addMarker($event)">
<deprecated-map-marker-clusterer [imagePath]="markerClustererImagePath">
@for (position of markerPositions; track position) {
<map-marker [position]="position" />
}
</deprecated-map-marker-clusterer>
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2499,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/deprecated-map-marker-clusterer/README.md"
}
|
components/src/google-maps/deprecated-map-marker-clusterer/deprecated-marker-clusterer-types.ts_0_5825
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/// <reference types="google.maps" preserve="true" />
/**
* Class for clustering markers on a Google Map.
*
* See
* googlemaps.github.io/v3-utility-library/classes/_google_markerclustererplus.markerclusterer.html
*/
export declare class MarkerClusterer {
constructor(
map: google.maps.Map,
markers?: google.maps.Marker[],
options?: MarkerClustererOptions,
);
ariaLabelFn: AriaLabelFn;
static BATCH_SIZE: number;
static BATCH_SIZE_IE: number;
static IMAGE_EXTENSION: string;
static IMAGE_PATH: string;
static IMAGE_SIZES: number[];
addListener(eventName: string, handler: Function): google.maps.MapsEventListener;
addMarker(marker: MarkerClusterer, nodraw: boolean): void;
addMarkers(markers: google.maps.Marker[], nodraw?: boolean): void;
bindTo(key: string, target: google.maps.MVCObject, targetKey: string, noNotify: boolean): void;
changed(key: string): void;
clearMarkers(): void;
fitMapToMarkers(padding: number | google.maps.Padding): void;
get(key: string): any;
getAverageCenter(): boolean;
getBatchSizeIE(): number;
getCalculator(): Calculator;
getClusterClass(): string;
getClusters(): Cluster[];
getEnableRetinaIcons(): boolean;
getGridSize(): number;
getIgnoreHidden(): boolean;
getImageExtension(): string;
getImagePath(): string;
getImageSizes(): number[];
getMap(): google.maps.Map | google.maps.StreetViewPanorama;
getMarkers(): google.maps.Marker[];
getMaxZoom(): number;
getMinimumClusterSize(): number;
getPanes(): google.maps.MapPanes;
getProjection(): google.maps.MapCanvasProjection;
getStyles(): ClusterIconStyle[];
getTitle(): string;
getTotalClusters(): number;
getTotalMarkers(): number;
getZIndex(): number;
getZoomOnClick(): boolean;
notify(key: string): void;
removeMarker(marker: google.maps.Marker, nodraw: boolean): boolean;
removeMarkers(markers: google.maps.Marker[], nodraw?: boolean): boolean;
repaint(): void;
set(key: string, value: any): void;
setAverageCenter(averageCenter: boolean): void;
setBatchSizeIE(batchSizeIE: number): void;
setCalculator(calculator: Calculator): void;
setClusterClass(clusterClass: string): void;
setEnableRetinaIcons(enableRetinaIcons: boolean): void;
setGridSize(gridSize: number): void;
setIgnoreHidden(ignoreHidden: boolean): void;
setImageExtension(imageExtension: string): void;
setImagePath(imagePath: string): void;
setImageSizes(imageSizes: number[]): void;
setMap(map: google.maps.Map | null): void;
setMaxZoom(maxZoom: number): void;
setMinimumClusterSize(minimumClusterSize: number): void;
setStyles(styles: ClusterIconStyle[]): void;
setTitle(title: string): void;
setValues(values: any): void;
setZIndex(zIndex: number): void;
setZoomOnClick(zoomOnClick: boolean): void;
// Note: This one doesn't appear in the docs page, but it exists at runtime.
setOptions(options: MarkerClustererOptions): void;
unbind(key: string): void;
unbindAll(): void;
static CALCULATOR(markers: google.maps.Marker[], numStyles: number): ClusterIconInfo;
static withDefaultStyle(overrides: ClusterIconStyle): ClusterIconStyle;
}
/**
* Cluster class from the @google/markerclustererplus library.
*
* See googlemaps.github.io/v3-utility-library/classes/_google_markerclustererplus.cluster.html
*/
export declare class Cluster {
constructor(markerClusterer: MarkerClusterer);
getCenter(): google.maps.LatLng;
getMarkers(): google.maps.Marker[];
getSize(): number;
updateIcon(): void;
}
/**
* Options for constructing a MarkerClusterer from the @google/markerclustererplus library.
*
* See
* googlemaps.github.io/v3-utility-library/classes/
* _google_markerclustererplus.markerclustereroptions.html
*/
export declare interface MarkerClustererOptions {
ariaLabelFn?: AriaLabelFn;
averageCenter?: boolean;
batchSize?: number;
batchSizeIE?: number;
calculator?: Calculator;
clusterClass?: string;
enableRetinaIcons?: boolean;
gridSize?: number;
ignoreHidden?: boolean;
imageExtension?: string;
imagePath?: string;
imageSizes?: number[];
maxZoom?: number;
minimumClusterSize?: number;
styles?: ClusterIconStyle[];
title?: string;
zIndex?: number;
zoomOnClick?: boolean;
}
/**
* Style interface for a marker cluster icon.
*
* See
* googlemaps.github.io/v3-utility-library/interfaces/
* _google_markerclustererplus.clustericonstyle.html
*/
export declare interface ClusterIconStyle {
anchorIcon?: [number, number];
anchorText?: [number, number];
backgroundPosition?: string;
className?: string;
fontFamily?: string;
fontStyle?: string;
fontWeight?: string;
height: number;
textColor?: string;
textDecoration?: string;
textLineHeight?: number;
textSize?: number;
url?: string;
width: number;
}
/**
* Info interface for a marker cluster icon.
*
* See
* googlemaps.github.io/v3-utility-library/interfaces/
* _google_markerclustererplus.clustericoninfo.html
*/
export declare interface ClusterIconInfo {
index: number;
text: string;
title: string;
}
/**
* Function type alias for determining the aria label on a Google Maps marker cluster.
*
* See googlemaps.github.io/v3-utility-library/modules/_google_markerclustererplus.html#arialabelfn
*/
export declare type AriaLabelFn = (text: string) => string;
/**
* Function type alias for calculating how a marker cluster is displayed.
*
* See googlemaps.github.io/v3-utility-library/modules/_google_markerclustererplus.html#calculator
*/
export declare type Calculator = (
markers: google.maps.Marker[],
clusterIconStylesCount: number,
) => ClusterIconInfo;
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 5825,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/deprecated-map-marker-clusterer/deprecated-marker-clusterer-types.ts"
}
|
components/src/google-maps/map-ground-overlay/map-ground-overlay.spec.ts_0_6704
|
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createGroundOverlayConstructorSpy,
createGroundOverlaySpy,
createMapConstructorSpy,
createMapSpy,
} from '../testing/fake-google-map-utils';
import {MapGroundOverlay} from './map-ground-overlay';
describe('MapGroundOverlay', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
const url = 'www.testimg.com/img.jpg';
const bounds: google.maps.LatLngBoundsLiteral = {east: 3, north: 5, west: -3, south: -5};
const clickable = true;
const opacity = 0.5;
const groundOverlayOptions: google.maps.GroundOverlayOptions = {clickable, opacity};
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map Ground Overlay', fakeAsync(() => {
const groundOverlaySpy = createGroundOverlaySpy(url, bounds, groundOverlayOptions);
const groundOverlayConstructorSpy = createGroundOverlayConstructorSpy(groundOverlaySpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.url = url;
fixture.componentInstance.bounds = bounds;
fixture.componentInstance.clickable = clickable;
fixture.componentInstance.opacity = opacity;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(groundOverlayConstructorSpy).toHaveBeenCalledWith(url, bounds, groundOverlayOptions);
expect(groundOverlaySpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
it('exposes methods that provide information about the Ground Overlay', fakeAsync(() => {
const groundOverlaySpy = createGroundOverlaySpy(url, bounds, groundOverlayOptions);
createGroundOverlayConstructorSpy(groundOverlaySpy);
const fixture = TestBed.createComponent(TestApp);
const groundOverlayComponent = fixture.debugElement
.query(By.directive(MapGroundOverlay))!
.injector.get<MapGroundOverlay>(MapGroundOverlay);
fixture.componentInstance.url = url;
fixture.componentInstance.bounds = bounds;
fixture.componentInstance.opacity = opacity;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
groundOverlayComponent.getBounds();
expect(groundOverlaySpy.getBounds).toHaveBeenCalled();
groundOverlaySpy.getOpacity.and.returnValue(opacity);
expect(groundOverlayComponent.getOpacity()).toBe(opacity);
groundOverlaySpy.getUrl.and.returnValue(url);
expect(groundOverlayComponent.getUrl()).toBe(url);
}));
it('initializes Ground Overlay event handlers', fakeAsync(() => {
const groundOverlaySpy = createGroundOverlaySpy(url, bounds, groundOverlayOptions);
createGroundOverlayConstructorSpy(groundOverlaySpy);
const addSpy = groundOverlaySpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.url = url;
fixture.componentInstance.bounds = bounds;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(addSpy).toHaveBeenCalledWith('click', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dblclick', jasmine.any(Function));
}));
it('should be able to add an event listener after init', fakeAsync(() => {
const groundOverlaySpy = createGroundOverlaySpy(url, bounds, groundOverlayOptions);
createGroundOverlayConstructorSpy(groundOverlaySpy);
const addSpy = groundOverlaySpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.url = url;
fixture.componentInstance.bounds = bounds;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(addSpy).not.toHaveBeenCalledWith('dblclick', jasmine.any(Function));
// Pick an event that isn't bound in the template.
const subscription = fixture.componentInstance.groundOverlay.mapDblclick.subscribe();
fixture.detectChanges();
expect(addSpy).toHaveBeenCalledWith('dblclick', jasmine.any(Function));
subscription.unsubscribe();
}));
it('should be able to change the image after init', fakeAsync(() => {
const groundOverlaySpy = createGroundOverlaySpy(url, bounds, groundOverlayOptions);
const groundOverlayConstructorSpy = createGroundOverlayConstructorSpy(groundOverlaySpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.url = url;
fixture.componentInstance.bounds = bounds;
fixture.componentInstance.clickable = clickable;
fixture.componentInstance.opacity = opacity;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(groundOverlayConstructorSpy).toHaveBeenCalledWith(url, bounds, groundOverlayOptions);
expect(groundOverlaySpy.setMap).toHaveBeenCalledWith(mapSpy);
groundOverlaySpy.setMap.calls.reset();
fixture.componentInstance.url = 'foo.png';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(groundOverlaySpy.set).toHaveBeenCalledWith('url', 'foo.png');
expect(groundOverlaySpy.setMap).toHaveBeenCalledTimes(2);
expect(groundOverlaySpy.setMap).toHaveBeenCalledWith(null);
expect(groundOverlaySpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
it('should recreate the ground overlay when the bounds change', fakeAsync(() => {
const groundOverlaySpy = createGroundOverlaySpy(url, bounds, groundOverlayOptions);
createGroundOverlayConstructorSpy(groundOverlaySpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
const oldOverlay = fixture.componentInstance.groundOverlay.groundOverlay;
fixture.componentInstance.bounds = {...bounds};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
const newOverlay = fixture.componentInstance.groundOverlay.groundOverlay;
expect(newOverlay).toBeTruthy();
expect(newOverlay).not.toBe(oldOverlay);
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-ground-overlay
[url]="url"
[bounds]="bounds"
[clickable]="clickable"
[opacity]="opacity"
(mapClick)="handleClick()" />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapGroundOverlay],
})
class TestApp {
@ViewChild(MapGroundOverlay) groundOverlay: MapGroundOverlay;
url!: string;
bounds!: google.maps.LatLngBoundsLiteral;
clickable = false;
opacity = 1;
handleClick() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 6704,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-ground-overlay/map-ground-overlay.spec.ts"
}
|
components/src/google-maps/map-ground-overlay/README.md_0_1068
|
# MapGroundOverlay
The `MapGroundOverlay` component wraps the [`google.maps.GroundOverlay` class](https://developers.google.com/maps/documentation/javascript/reference/image-overlay#GroundOverlay) from the Google Maps JavaScript API. A url and a bounds are required.
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapGroundOverlay} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapGroundOverlay],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
imageUrl = 'https://angular.io/assets/images/logos/angular/angular.svg';
imageBounds: google.maps.LatLngBoundsLiteral = {
east: 10,
north: 10,
south: -10,
west: -10,
};
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map height="400px" width="750px" [center]="center" [zoom]="zoom">
<map-ground-overlay [url]="imageUrl" [bounds]="imageBounds" />
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1068,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-ground-overlay/README.md"
}
|
components/src/google-maps/map-ground-overlay/map-ground-overlay.ts_0_7119
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Directive,
EventEmitter,
Input,
NgZone,
OnDestroy,
OnInit,
Output,
inject,
} from '@angular/core';
import {BehaviorSubject, Observable, Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
/**
* Angular component that renders a Google Maps Ground Overlay via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/image-overlay#GroundOverlay
*/
@Directive({
selector: 'map-ground-overlay',
exportAs: 'mapGroundOverlay',
})
export class MapGroundOverlay implements OnInit, OnDestroy {
private readonly _map = inject(GoogleMap);
private readonly _ngZone = inject(NgZone);
private _eventManager = new MapEventManager(inject(NgZone));
private readonly _opacity = new BehaviorSubject<number>(1);
private readonly _url = new BehaviorSubject<string>('');
private readonly _bounds = new BehaviorSubject<
google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral | undefined
>(undefined);
private readonly _destroyed = new Subject<void>();
private _hasWatchers: boolean;
/**
* The underlying google.maps.GroundOverlay object.
*
* See developers.google.com/maps/documentation/javascript/reference/image-overlay#GroundOverlay
*/
groundOverlay?: google.maps.GroundOverlay;
/** URL of the image that will be shown in the overlay. */
@Input()
set url(url: string) {
this._url.next(url);
}
/** Bounds for the overlay. */
@Input()
get bounds(): google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral {
return this._bounds.value!;
}
set bounds(bounds: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral) {
this._bounds.next(bounds);
}
/** Whether the overlay is clickable */
@Input() clickable: boolean = false;
/** Opacity of the overlay. */
@Input()
set opacity(opacity: number) {
this._opacity.next(opacity);
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/image-overlay#GroundOverlay.click
*/
@Output() readonly mapClick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('click');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/image-overlay
* #GroundOverlay.dblclick
*/
@Output() readonly mapDblclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dblclick');
/** Event emitted when the ground overlay is initialized. */
@Output() readonly groundOverlayInitialized: EventEmitter<google.maps.GroundOverlay> =
new EventEmitter<google.maps.GroundOverlay>();
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (this._map._isBrowser) {
// The ground overlay setup is slightly different from the other Google Maps objects in that
// we have to recreate the `GroundOverlay` object whenever the bounds change, because
// Google Maps doesn't provide an API to update the bounds of an existing overlay.
this._bounds.pipe(takeUntil(this._destroyed)).subscribe(bounds => {
if (this.groundOverlay) {
this.groundOverlay.setMap(null);
this.groundOverlay = undefined;
}
if (!bounds) {
return;
}
if (google.maps.GroundOverlay && this._map.googleMap) {
this._initialize(this._map.googleMap, google.maps.GroundOverlay, bounds);
} else {
this._ngZone.runOutsideAngular(() => {
Promise.all([this._map._resolveMap(), google.maps.importLibrary('maps')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.MapsLibrary).GroundOverlay, bounds);
},
);
});
}
});
}
}
private _initialize(
map: google.maps.Map,
overlayConstructor: typeof google.maps.GroundOverlay,
bounds: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral,
) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.groundOverlay = new overlayConstructor(this._url.getValue(), bounds, {
clickable: this.clickable,
opacity: this._opacity.value,
});
this._assertInitialized();
this.groundOverlay.setMap(map);
this._eventManager.setTarget(this.groundOverlay);
this.groundOverlayInitialized.emit(this.groundOverlay);
// We only need to set up the watchers once.
if (!this._hasWatchers) {
this._hasWatchers = true;
this._watchForOpacityChanges();
this._watchForUrlChanges();
}
});
}
ngOnDestroy() {
this._eventManager.destroy();
this._destroyed.next();
this._destroyed.complete();
this.groundOverlay?.setMap(null);
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/image-overlay
* #GroundOverlay.getBounds
*/
getBounds(): google.maps.LatLngBounds | null {
this._assertInitialized();
return this.groundOverlay.getBounds();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/image-overlay
* #GroundOverlay.getOpacity
*/
getOpacity(): number {
this._assertInitialized();
return this.groundOverlay.getOpacity();
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/image-overlay
* #GroundOverlay.getUrl
*/
getUrl(): string {
this._assertInitialized();
return this.groundOverlay.getUrl();
}
private _watchForOpacityChanges() {
this._opacity.pipe(takeUntil(this._destroyed)).subscribe(opacity => {
if (opacity != null) {
this.groundOverlay?.setOpacity(opacity);
}
});
}
private _watchForUrlChanges() {
this._url.pipe(takeUntil(this._destroyed)).subscribe(url => {
const overlay = this.groundOverlay;
if (overlay) {
overlay.set('url', url);
// Google Maps only redraws the overlay if we re-set the map.
overlay.setMap(null);
overlay.setMap(this._map.googleMap!);
}
});
}
private _assertInitialized(): asserts this is {groundOverlay: google.maps.GroundOverlay} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.groundOverlay) {
throw Error(
'Cannot interact with a Google Map GroundOverlay before it has been initialized. ' +
'Please wait for the GroundOverlay to load before trying to interact with it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 7119,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-ground-overlay/map-ground-overlay.ts"
}
|
components/src/google-maps/google-map/README.md_0_2075
|
# GoogleMap
The `GoogleMap` component wraps the [`google.maps.Map` class](https://developers.google.com/maps/documentation/javascript/reference/map) from the Google Maps JavaScript API. You can configure the map via the component's inputs. The `options` input accepts a full [`google.maps.MapOptions` object](https://developers.google.com/maps/documentation/javascript/reference/map#MapOptions), and the component additionally offers convenience inputs for setting the `center` and `zoom` of the map without needing an entire `google.maps.MapOptions` object. The `height` and `width` inputs accept a string to set the size of the Google map. [Events](https://developers.google.com/maps/documentation/javascript/reference/map#Map.bounds_changed) can be bound using the outputs of the `GoogleMap` component, although events have the same name as native mouse events (e.g. `mouseenter`) have been prefixed with "map" as to not collide with the native mouse events. Other members on the `google.maps.Map` object are available on the `GoogleMap` component and can be accessed using the [`ViewChild` decorator](https://angular.dev/api/core/ViewChild) or via [`viewChild`](https://angular.dev/api/core/viewChild).
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
display: google.maps.LatLngLiteral;
moveMap(event: google.maps.MapMouseEvent) {
this.center = (event.latLng.toJSON());
}
move(event: google.maps.MapMouseEvent) {
this.display = event.latLng.toJSON();
}
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map
height="400px"
width="750px"
[center]="center"
[zoom]="zoom"
(mapClick)="moveMap($event)"
(mapMousemove)="move($event)" />
<div>Latitude: {{display?.lat}}</div>
<div>Longitude: {{display?.lng}}</div>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2075,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/google-map/README.md"
}
|
components/src/google-maps/google-map/google-map.spec.ts_0_9256
|
import {Component, ViewChild} from '@angular/core';
import {TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {createMapConstructorSpy, createMapSpy} from '../testing/fake-google-map-utils';
import {DEFAULT_HEIGHT, DEFAULT_OPTIONS, DEFAULT_WIDTH, GoogleMap} from './google-map';
/** Represents boundaries of a map to be used in tests. */
const testBounds: google.maps.LatLngBoundsLiteral = {
east: 12,
north: 13,
south: 14,
west: 15,
};
/** Represents a latitude/longitude position to be used in tests. */
const testPosition: google.maps.LatLngLiteral = {
lat: 30,
lng: 35,
};
describe('GoogleMap', () => {
let mapConstructorSpy: jasmine.Spy;
let mapSpy: jasmine.SpyObj<google.maps.Map>;
afterEach(() => {
(window.google as any) = undefined;
(window as any).gm_authFailure = undefined;
});
it('throws an error is the Google Maps JavaScript API was not loaded', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
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,
mapId: undefined,
});
});
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.changeDetectorRef.markForCheck();
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,
mapId: undefined,
});
fixture.componentInstance.height = '650px';
fixture.componentInstance.width = '350px';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(container.nativeElement.style.height).toBe('650px');
expect(container.nativeElement.style.width).toBe('350px');
});
it('should be able to set a number value as the width/height', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
const instance = fixture.componentInstance;
instance.height = 750;
instance.width = 400;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const container = fixture.debugElement.query(By.css('div'))!.nativeElement;
expect(container.style.height).toBe('750px');
expect(container.style.width).toBe('400px');
instance.height = '500';
instance.width = '600';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(container.style.height).toBe('500px');
expect(container.style.width).toBe('600px');
});
it('should be able to set null as the width/height', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
const instance = fixture.componentInstance;
instance.height = instance.width = null;
fixture.detectChanges();
const container = fixture.debugElement.query(By.css('div'))!.nativeElement;
expect(container.style.height).toBeFalsy();
expect(container.style.width).toBeFalsy();
});
it('sets center and zoom of the map', () => {
const options = {
center: {lat: 3, lng: 5},
zoom: 7,
mapTypeId: DEFAULT_OPTIONS.mapTypeId,
mapId: undefined,
};
mapSpy = createMapSpy(options);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.center = options.center;
fixture.componentInstance.zoom = options.zoom;
fixture.changeDetectorRef.markForCheck();
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.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(mapSpy.setCenter).toHaveBeenCalledWith({lat: 8, lng: 9});
expect(mapSpy.setZoom).toHaveBeenCalledWith(12);
});
it('sets map options', () => {
const options = {
center: {lat: 3, lng: 5},
zoom: 7,
draggable: false,
mapTypeId: DEFAULT_OPTIONS.mapTypeId,
mapId: '123',
};
mapSpy = createMapSpy(options);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = options;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
const container = fixture.debugElement.query(By.css('div'))!;
expect(mapConstructorSpy).toHaveBeenCalledWith(container.nativeElement, options);
fixture.componentInstance.options = {...options, heading: 170};
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(mapSpy.setOptions).toHaveBeenCalledWith({...options, heading: 170});
});
it('should set a default center if the custom options do not provide one', () => {
const options = {zoom: 7};
mapSpy = createMapSpy(options);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = options;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(mapConstructorSpy.calls.mostRecent()?.args[1].center).toBeTruthy();
});
it('should set a default zoom level if the custom options do not provide one', () => {
const options = {};
mapSpy = createMapSpy(options);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = options;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(mapConstructorSpy.calls.mostRecent()?.args[1].zoom).toEqual(DEFAULT_OPTIONS.zoom);
});
it('should not set a default zoom level if the custom options provide "zoom: 0"', () => {
const options = {zoom: 0};
mapSpy = createMapSpy(options);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = options;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(mapConstructorSpy.calls.mostRecent()?.args[1].zoom).toEqual(0);
});
it('gives precedence to center and zoom over options', () => {
const inputOptions = {center: {lat: 3, lng: 5}, zoom: 7, heading: 170, mapId: '123'};
const correctedOptions = {
center: {lat: 12, lng: 15},
zoom: 5,
heading: 170,
mapTypeId: DEFAULT_OPTIONS.mapTypeId,
mapId: '123',
};
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.changeDetectorRef.markForCheck();
fixture.detectChanges();
const container = fixture.debugElement.query(By.css('div'))!;
expect(mapConstructorSpy).toHaveBeenCalledWith(container.nativeElement, correctedOptions);
});
it('exposes methods that change the configuration of the Google Map', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const component = fixture.debugElement.query(By.directive(GoogleMap)).componentInstance;
component.fitBounds(testBounds, 10);
expect(mapSpy.fitBounds).toHaveBeenCalledWith(testBounds, 10);
component.panBy(12, 13);
expect(mapSpy.panBy).toHaveBeenCalledWith(12, 13);
component.panTo(testPosition);
expect(mapSpy.panTo).toHaveBeenCalledWith(testPosition);
component.panToBounds(testBounds, 10);
expect(mapSpy.panToBounds).toHaveBeenCalledWith(testBounds, 10);
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 9256,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/google-map/google-map.spec.ts"
}
|
components/src/google-maps/google-map/google-map.spec.ts_9260_16632
|
it('exposes methods that get information about the Google Map', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
const component = fixture.debugElement.query(By.directive(GoogleMap)).componentInstance;
mapSpy.getBounds.and.returnValue(undefined);
expect(component.getBounds()).toBe(null);
component.getCenter();
expect(mapSpy.getCenter).toHaveBeenCalled();
mapSpy.getClickableIcons.and.returnValue(true);
expect(component.getClickableIcons()).toBe(true);
mapSpy.getHeading.and.returnValue(10);
expect(component.getHeading()).toBe(10);
component.getMapTypeId();
expect(mapSpy.getMapTypeId).toHaveBeenCalled();
mapSpy.getProjection.and.returnValue(undefined);
expect(component.getProjection()).toBe(null);
component.getStreetView();
expect(mapSpy.getStreetView).toHaveBeenCalled();
mapSpy.getTilt.and.returnValue(7);
expect(component.getTilt()).toBe(7);
mapSpy.getZoom.and.returnValue(5);
expect(component.getZoom()).toBe(5);
});
it('initializes event handlers that are set on the map', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
const addSpy = mapSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
expect(addSpy).toHaveBeenCalledWith('click', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('center_changed', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('rightclick', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('bounds_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dblclick', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('drag', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragend', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragstart', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('heading_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('idle', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('maptypeid_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mousemove', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseout', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseover', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('projection_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('tilesloaded', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('tilt_changed', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('zoom_changed', jasmine.any(Function));
});
it('should be able to add an event listener after init', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
const addSpy = mapSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
expect(addSpy).not.toHaveBeenCalledWith('projection_changed', jasmine.any(Function));
// Pick an event that isn't bound in the template.
const subscription = fixture.componentInstance.map.projectionChanged.subscribe();
fixture.detectChanges();
expect(addSpy).toHaveBeenCalledWith('projection_changed', jasmine.any(Function));
subscription.unsubscribe();
});
it('should set the map type', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.mapTypeId = 'terrain' as unknown as google.maps.MapTypeId;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(mapConstructorSpy).toHaveBeenCalledWith(
jasmine.any(HTMLElement),
jasmine.objectContaining({mapTypeId: 'terrain'}),
);
fixture.componentInstance.mapTypeId = 'roadmap' as unknown as google.maps.MapTypeId;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(mapSpy.setMapTypeId).toHaveBeenCalledWith('roadmap');
});
it('should set the map ID', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.mapId = '123';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(mapConstructorSpy).toHaveBeenCalledWith(
jasmine.any(HTMLElement),
jasmine.objectContaining({mapId: '123'}),
);
});
it('sets mapTypeId through the options', () => {
const options = {mapTypeId: 'satellite'};
mapSpy = createMapSpy(options);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = options;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
expect(mapConstructorSpy.calls.mostRecent()?.args[1].mapTypeId).toBe('satellite');
});
it('should emit mapInitialized event when the map is initialized', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
expect(fixture.componentInstance.mapInitializedSpy).toHaveBeenCalledOnceWith(
fixture.componentInstance.map.googleMap,
);
});
it('should emit authFailure event when window.gm_authFailure is called', () => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
mapConstructorSpy = createMapConstructorSpy(mapSpy);
expect((window as any).gm_authFailure).toBeUndefined();
const createFixture = () => {
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
spyOn(fixture.componentInstance.map.authFailure, 'emit');
return fixture;
};
const fixture1 = createFixture();
const fixture2 = createFixture();
expect((window as any).gm_authFailure).toBeDefined();
(window as any).gm_authFailure();
expect(fixture1.componentInstance.map.authFailure.emit).toHaveBeenCalled();
expect(fixture2.componentInstance.map.authFailure.emit).toHaveBeenCalled();
});
});
@Component({
selector: 'test-app',
template: `
<google-map
[height]="height"
[width]="width"
[center]="center"
[zoom]="zoom"
[options]="options"
[mapTypeId]="mapTypeId"
[mapId]="mapId"
(mapClick)="handleClick($event)"
(centerChanged)="handleCenterChanged()"
(mapRightclick)="handleRightclick($event)"
(mapInitialized)="mapInitializedSpy($event)" />
`,
standalone: true,
imports: [GoogleMap],
})
class TestApp {
@ViewChild(GoogleMap) map: GoogleMap;
height?: string | number | null;
width?: string | number | null;
center?: google.maps.LatLngLiteral;
zoom?: number;
options?: google.maps.MapOptions;
mapTypeId?: google.maps.MapTypeId;
mapId?: string;
handleClick(event: google.maps.MapMouseEvent) {}
handleCenterChanged() {}
handleRightclick(event: google.maps.MapMouseEvent) {}
mapInitializedSpy = jasmine.createSpy('mapInitialized');
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 16632,
"start_byte": 9260,
"url": "https://github.com/angular/components/blob/main/src/google-maps/google-map/google-map.spec.ts"
}
|
components/src/google-maps/google-map/google-map.ts_0_1800
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
ChangeDetectionStrategy,
Component,
ElementRef,
Input,
OnChanges,
OnDestroy,
OnInit,
Output,
ViewEncapsulation,
PLATFORM_ID,
NgZone,
SimpleChanges,
EventEmitter,
inject,
} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';
import {Observable} from 'rxjs';
import {MapEventManager} from '../map-event-manager';
import {take} from 'rxjs/operators';
interface GoogleMapsWindow extends Window {
gm_authFailure?: () => void;
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,
// Note: the type conversion here isn't necessary for our CI, but it resolves a g3 failure.
mapTypeId: 'roadmap' as unknown as google.maps.MapTypeId,
};
/** 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
* API.
* @see https://developers.google.com/maps/documentation/javascript/reference/
*/
@Component({
selector: 'google-map',
exportAs: 'googleMap',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<div class="map-container"></div><ng-content />',
encapsulation: ViewEncapsulation.None,
})
export class GoogleMap implements OnChanges, OnInit, OnDestroy
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1800,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/google-map/google-map.ts"
}
|
components/src/google-maps/google-map/google-map.ts_1801_10602
|
{
private readonly _elementRef = inject(ElementRef);
private _ngZone = inject(NgZone);
private _eventManager = new MapEventManager(inject(NgZone));
private _mapEl: HTMLElement;
private _existingAuthFailureCallback: GoogleMapsWindow['gm_authFailure'];
/**
* The underlying google.maps.Map object
*
* See developers.google.com/maps/documentation/javascript/reference/map#Map
*/
googleMap?: google.maps.Map;
/** Whether we're currently rendering inside a browser. */
_isBrowser: boolean;
/** Height of the map. Set this to `null` if you'd like to control the height through CSS. */
@Input() height: string | number | null = DEFAULT_HEIGHT;
/** Width of the map. Set this to `null` if you'd like to control the width through CSS. */
@Input() width: string | number | null = DEFAULT_WIDTH;
/**
* The Map ID of the map. This parameter cannot be set or changed after a map is instantiated.
* See: https://developers.google.com/maps/documentation/javascript/reference/map#MapOptions.mapId
*/
@Input() mapId: string | undefined;
/**
* Type of map that should be rendered. E.g. hybrid map, terrain map etc.
* See: https://developers.google.com/maps/documentation/javascript/reference/map#MapTypeId
*/
@Input() mapTypeId: google.maps.MapTypeId | undefined;
@Input()
set center(center: google.maps.LatLngLiteral | google.maps.LatLng) {
this._center = center;
}
private _center: google.maps.LatLngLiteral | google.maps.LatLng;
@Input()
set zoom(zoom: number) {
this._zoom = zoom;
}
private _zoom: number;
@Input()
set options(options: google.maps.MapOptions) {
this._options = options || DEFAULT_OPTIONS;
}
private _options = DEFAULT_OPTIONS;
/** Event emitted when the map is initialized. */
@Output() readonly mapInitialized: EventEmitter<google.maps.Map> =
new EventEmitter<google.maps.Map>();
/**
* See
* https://developers.google.com/maps/documentation/javascript/events#auth-errors
*/
@Output() readonly authFailure: EventEmitter<void> = new EventEmitter<void>();
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.bounds_changed
*/
@Output() readonly boundsChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('bounds_changed');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.center_changed
*/
@Output() readonly centerChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('center_changed');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.click
*/
@Output() readonly mapClick: Observable<google.maps.MapMouseEvent | google.maps.IconMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent | google.maps.IconMouseEvent>(
'click',
);
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.dblclick
*/
@Output() readonly mapDblclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dblclick');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.drag
*/
@Output() readonly mapDrag: Observable<void> = this._eventManager.getLazyEmitter<void>('drag');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.dragend
*/
@Output() readonly mapDragend: Observable<void> =
this._eventManager.getLazyEmitter<void>('dragend');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.dragstart
*/
@Output() readonly mapDragstart: Observable<void> =
this._eventManager.getLazyEmitter<void>('dragstart');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.heading_changed
*/
@Output() readonly headingChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('heading_changed');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.idle
*/
@Output() readonly idle: Observable<void> = this._eventManager.getLazyEmitter<void>('idle');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.maptypeid_changed
*/
@Output() readonly maptypeidChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('maptypeid_changed');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.mousemove
*/
@Output()
readonly mapMousemove: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mousemove');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.mouseout
*/
@Output() readonly mapMouseout: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseout');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.mouseover
*/
@Output() readonly mapMouseover: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('mouseover');
/**
* See
* developers.google.com/maps/documentation/javascript/reference/map#Map.projection_changed
*/
@Output() readonly projectionChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('projection_changed');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.rightclick
*/
@Output() readonly mapRightclick: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('rightclick');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.tilesloaded
*/
@Output() readonly tilesloaded: Observable<void> =
this._eventManager.getLazyEmitter<void>('tilesloaded');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.tilt_changed
*/
@Output() readonly tiltChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('tilt_changed');
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.zoom_changed
*/
@Output() readonly zoomChanged: Observable<void> =
this._eventManager.getLazyEmitter<void>('zoom_changed');
constructor(...args: unknown[]);
constructor() {
const platformId = inject<Object>(PLATFORM_ID);
this._isBrowser = isPlatformBrowser(platformId);
if (this._isBrowser) {
const googleMapsWindow: GoogleMapsWindow = window;
if (!googleMapsWindow.google && (typeof ngDevMode === 'undefined' || ngDevMode)) {
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',
);
}
this._existingAuthFailureCallback = googleMapsWindow.gm_authFailure;
googleMapsWindow.gm_authFailure = () => {
if (this._existingAuthFailureCallback) {
this._existingAuthFailureCallback();
}
this.authFailure.emit();
};
}
}
ngOnChanges(changes: SimpleChanges) {
if (changes['height'] || changes['width']) {
this._setSize();
}
const googleMap = this.googleMap;
if (googleMap) {
if (changes['options']) {
googleMap.setOptions(this._combineOptions());
}
if (changes['center'] && this._center) {
googleMap.setCenter(this._center);
}
// Note that the zoom can be zero.
if (changes['zoom'] && this._zoom != null) {
googleMap.setZoom(this._zoom);
}
if (changes['mapTypeId'] && this.mapTypeId) {
googleMap.setMapTypeId(this.mapTypeId);
}
}
}
ngOnInit() {
// It should be a noop during server-side rendering.
if (this._isBrowser) {
this._mapEl = this._elementRef.nativeElement.querySelector('.map-container')!;
this._setSize();
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
if (google.maps.Map) {
this._initialize(google.maps.Map);
} else {
this._ngZone.runOutsideAngular(() => {
google.maps
.importLibrary('maps')
.then(lib => this._initialize((lib as google.maps.MapsLibrary).Map));
});
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 10602,
"start_byte": 1801,
"url": "https://github.com/angular/components/blob/main/src/google-maps/google-map/google-map.ts"
}
|
components/src/google-maps/google-map/google-map.ts_10606_17408
|
private _initialize(mapConstructor: typeof google.maps.Map) {
this._ngZone.runOutsideAngular(() => {
this.googleMap = new mapConstructor(this._mapEl, this._combineOptions());
this._eventManager.setTarget(this.googleMap);
this.mapInitialized.emit(this.googleMap);
});
}
ngOnDestroy() {
this.mapInitialized.complete();
this._eventManager.destroy();
if (this._isBrowser) {
const googleMapsWindow: GoogleMapsWindow = window;
googleMapsWindow.gm_authFailure = this._existingAuthFailureCallback;
}
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.fitBounds
*/
fitBounds(
bounds: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral,
padding?: number | google.maps.Padding,
) {
this._assertInitialized();
this.googleMap.fitBounds(bounds, padding);
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.panBy
*/
panBy(x: number, y: number) {
this._assertInitialized();
this.googleMap.panBy(x, y);
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.panTo
*/
panTo(latLng: google.maps.LatLng | google.maps.LatLngLiteral) {
this._assertInitialized();
this.googleMap.panTo(latLng);
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.panToBounds
*/
panToBounds(
latLngBounds: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral,
padding?: number | google.maps.Padding,
) {
this._assertInitialized();
this.googleMap.panToBounds(latLngBounds, padding);
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.getBounds
*/
getBounds(): google.maps.LatLngBounds | null {
this._assertInitialized();
return this.googleMap.getBounds() || null;
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.getCenter
*/
getCenter(): google.maps.LatLng | undefined {
this._assertInitialized();
return this.googleMap.getCenter();
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.getClickableIcons
*/
getClickableIcons(): boolean | undefined {
this._assertInitialized();
return this.googleMap.getClickableIcons();
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.getHeading
*/
getHeading(): number | undefined {
this._assertInitialized();
return this.googleMap.getHeading();
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.getMapTypeId
*/
getMapTypeId(): google.maps.MapTypeId | string | undefined {
this._assertInitialized();
return this.googleMap.getMapTypeId();
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.getProjection
*/
getProjection(): google.maps.Projection | null {
this._assertInitialized();
return this.googleMap.getProjection() || null;
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.getStreetView
*/
getStreetView(): google.maps.StreetViewPanorama {
this._assertInitialized();
return this.googleMap.getStreetView();
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.getTilt
*/
getTilt(): number | undefined {
this._assertInitialized();
return this.googleMap.getTilt();
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.getZoom
*/
getZoom(): number | undefined {
this._assertInitialized();
return this.googleMap.getZoom();
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.controls
*/
get controls(): google.maps.MVCArray<Node>[] {
this._assertInitialized();
return this.googleMap.controls;
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.data
*/
get data(): google.maps.Data {
this._assertInitialized();
return this.googleMap.data;
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.mapTypes
*/
get mapTypes(): google.maps.MapTypeRegistry {
this._assertInitialized();
return this.googleMap.mapTypes;
}
/**
* See
* https://developers.google.com/maps/documentation/javascript/reference/map#Map.overlayMapTypes
*/
get overlayMapTypes(): google.maps.MVCArray<google.maps.MapType | null> {
this._assertInitialized();
return this.googleMap.overlayMapTypes;
}
/** Returns a promise that resolves when the map has been initialized. */
_resolveMap(): Promise<google.maps.Map> {
return this.googleMap
? Promise.resolve(this.googleMap)
: this.mapInitialized.pipe(take(1)).toPromise();
}
private _setSize() {
if (this._mapEl) {
const styles = this._mapEl.style;
styles.height =
this.height === null ? '' : coerceCssPixelValue(this.height) || DEFAULT_HEIGHT;
styles.width = this.width === null ? '' : coerceCssPixelValue(this.width) || DEFAULT_WIDTH;
}
}
/** Combines the center and zoom and the other map options into a single object */
private _combineOptions(): google.maps.MapOptions {
const options = this._options || {};
return {
...options,
// It's important that we set **some** kind of `center` and `zoom`, otherwise
// Google Maps will render a blank rectangle which looks broken.
center: this._center || options.center || DEFAULT_OPTIONS.center,
zoom: this._zoom ?? options.zoom ?? DEFAULT_OPTIONS.zoom,
// Passing in an undefined `mapTypeId` seems to break tile loading
// so make sure that we have some kind of default (see #22082).
mapTypeId: this.mapTypeId || options.mapTypeId || DEFAULT_OPTIONS.mapTypeId,
mapId: this.mapId || options.mapId,
};
}
/** Asserts that the map has been initialized. */
private _assertInitialized(): asserts this is {googleMap: google.maps.Map} {
if (!this.googleMap && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error(
'Cannot access Google Map information before the API has been initialized. ' +
'Please wait for the API to load before trying to interact with it.',
);
}
}
}
const cssUnitsPattern = /([A-Za-z%]+)$/;
/** Coerces a value to a CSS pixel value. */
function coerceCssPixelValue(value: any): string {
if (value == null) {
return '';
}
return cssUnitsPattern.test(value) ? value : `${value}px`;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 17408,
"start_byte": 10606,
"url": "https://github.com/angular/components/blob/main/src/google-maps/google-map/google-map.ts"
}
|
components/src/google-maps/map-marker-clusterer/map-marker-clusterer.ts_0_7830
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
ChangeDetectionStrategy,
Component,
ContentChildren,
EventEmitter,
inject,
Input,
NgZone,
OnChanges,
OnDestroy,
OnInit,
Output,
QueryList,
SimpleChanges,
ViewEncapsulation,
} from '@angular/core';
import {Observable, Subscription} from 'rxjs';
import type {
Cluster,
MarkerClusterer,
onClusterClickHandler,
Renderer,
Algorithm,
} from './map-marker-clusterer-types';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
import {MAP_MARKER, Marker, MarkerDirective} from '../marker-utilities';
declare const markerClusterer: {
MarkerClusterer: typeof MarkerClusterer;
defaultOnClusterClickHandler: onClusterClickHandler;
};
/**
* Angular component for implementing a Google Maps Marker Clusterer.
*
* See https://developers.google.com/maps/documentation/javascript/marker-clustering
*/
@Component({
selector: 'map-marker-clusterer',
exportAs: 'mapMarkerClusterer',
changeDetection: ChangeDetectionStrategy.OnPush,
template: '<ng-content/>',
encapsulation: ViewEncapsulation.None,
})
export class MapMarkerClusterer implements OnInit, OnChanges, OnDestroy {
private readonly _googleMap = inject(GoogleMap);
private readonly _ngZone = inject(NgZone);
private readonly _currentMarkers = new Set<Marker>();
private readonly _closestMapEventManager = new MapEventManager(this._ngZone);
private _markersSubscription = Subscription.EMPTY;
/** Whether the clusterer is allowed to be initialized. */
private readonly _canInitialize = this._googleMap._isBrowser;
/**
* Used to customize how the marker cluster is rendered.
* See https://googlemaps.github.io/js-markerclusterer/interfaces/Renderer.html.
*/
@Input()
renderer: Renderer;
/**
* Algorithm used to cluster the markers.
* See https://googlemaps.github.io/js-markerclusterer/interfaces/Algorithm.html.
*/
@Input()
algorithm: Algorithm;
/** Emits when clustering has started. */
@Output() readonly clusteringbegin: Observable<void> =
this._closestMapEventManager.getLazyEmitter<void>('clusteringbegin');
/** Emits when clustering is done. */
@Output() readonly clusteringend: Observable<void> =
this._closestMapEventManager.getLazyEmitter<void>('clusteringend');
/** Emits when a cluster has been clicked. */
@Output()
readonly clusterClick: EventEmitter<Cluster> = new EventEmitter<Cluster>();
/** Event emitted when the marker clusterer is initialized. */
@Output() readonly markerClustererInitialized: EventEmitter<MarkerClusterer> =
new EventEmitter<MarkerClusterer>();
@ContentChildren(MAP_MARKER, {descendants: true}) _markers: QueryList<MarkerDirective>;
/** Underlying MarkerClusterer object used to interact with Google Maps. */
markerClusterer?: MarkerClusterer;
async ngOnInit() {
if (this._canInitialize) {
await this._createCluster();
// The `clusteringbegin` and `clusteringend` events are
// emitted on the map so that's why set it as the target.
this._closestMapEventManager.setTarget(this._googleMap.googleMap!);
}
}
async ngOnChanges(changes: SimpleChanges) {
const change = changes['renderer'] || changes['algorithm'];
// Since the options are set in the constructor, we have to recreate the cluster if they change.
if (this.markerClusterer && change && !change.isFirstChange()) {
await this._createCluster();
}
}
ngOnDestroy() {
this._markersSubscription.unsubscribe();
this._closestMapEventManager.destroy();
this._destroyCluster();
}
private async _createCluster() {
if (!markerClusterer?.MarkerClusterer && (typeof ngDevMode === 'undefined' || ngDevMode)) {
throw Error(
'MarkerClusterer class not found, cannot construct a marker cluster. ' +
'Please install the MarkerClusterer library: ' +
'https://github.com/googlemaps/js-markerclusterer',
);
}
const map = await this._googleMap._resolveMap();
this._destroyCluster();
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.markerClusterer = new markerClusterer.MarkerClusterer({
map,
renderer: this.renderer,
algorithm: this.algorithm,
onClusterClick: (event, cluster, map) => {
if (this.clusterClick.observers.length) {
this._ngZone.run(() => this.clusterClick.emit(cluster));
} else {
markerClusterer.defaultOnClusterClickHandler(event, cluster, map);
}
},
});
this.markerClustererInitialized.emit(this.markerClusterer);
});
await this._watchForMarkerChanges();
}
private async _watchForMarkerChanges() {
this._assertInitialized();
const initialMarkers: Marker[] = [];
const markers = await this._getInternalMarkers(this._markers.toArray());
for (const marker of markers) {
this._currentMarkers.add(marker);
initialMarkers.push(marker);
}
this.markerClusterer.addMarkers(initialMarkers);
this._markersSubscription.unsubscribe();
this._markersSubscription = this._markers.changes.subscribe(
async (markerComponents: MarkerDirective[]) => {
this._assertInitialized();
const newMarkers = new Set<Marker>(await this._getInternalMarkers(markerComponents));
const markersToAdd: Marker[] = [];
const markersToRemove: Marker[] = [];
for (const marker of Array.from(newMarkers)) {
if (!this._currentMarkers.has(marker)) {
this._currentMarkers.add(marker);
markersToAdd.push(marker);
}
}
for (const marker of Array.from(this._currentMarkers)) {
if (!newMarkers.has(marker)) {
markersToRemove.push(marker);
}
}
this.markerClusterer.addMarkers(markersToAdd, true);
this.markerClusterer.removeMarkers(markersToRemove, true);
this.markerClusterer.render();
for (const marker of markersToRemove) {
this._currentMarkers.delete(marker);
}
},
);
}
private _destroyCluster() {
// TODO(crisbeto): the naming here seems odd, but the `MarkerCluster` method isn't
// exposed. All this method seems to do at the time of writing is to call into `reset`.
// See: https://github.com/googlemaps/js-markerclusterer/blob/main/src/markerclusterer.ts#L205
this.markerClusterer?.onRemove();
this.markerClusterer = undefined;
}
private _getInternalMarkers(markers: MarkerDirective[]): Promise<Marker[]> {
return Promise.all(markers.map(marker => marker._resolveMarker()));
}
private _assertInitialized(): asserts this is {markerClusterer: MarkerClusterer} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this._googleMap.googleMap) {
throw Error(
'Cannot access Google Map information before the API has been initialized. ' +
'Please wait for the API to load before trying to interact with it.',
);
}
if (!this.markerClusterer) {
throw Error(
'Cannot interact with a MarkerClusterer before it has been initialized. ' +
'Please wait for the MarkerClusterer to load before trying to interact with it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 7830,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-marker-clusterer/map-marker-clusterer.ts"
}
|
components/src/google-maps/map-marker-clusterer/README.md_0_2036
|
# MapMarkerClusterer
The `MapMarkerClusterer` component wraps the [`MarkerClusterer` class](https://googlemaps.github.io/js-markerclusterer/classes/MarkerClusterer.html) from the [Google Maps JavaScript MarkerClusterer Library](https://github.com/googlemaps/js-markerclusterer). The `MapMarkerClusterer` component displays a cluster of markers that are children of the `<map-marker-clusterer>` tag. Unlike the other Google Maps components, MapMarkerClusterer does not have an `options` input, so any input (listed in the [documentation](https://googlemaps.github.io/js-markerclusterer/) for the `MarkerClusterer` class) should be set directly.
## Loading the Library
Like the Google Maps JavaScript API, the MarkerClusterer library needs to be loaded separately. This can be accomplished by using this script tag:
```html
<script src="https://unpkg.com/@googlemaps/markerclusterer/dist/index.min.js"></script>
```
Additional information can be found by looking at [Marker Clustering](https://developers.google.com/maps/documentation/javascript/marker-clustering) in the Google Maps JavaScript API documentation.
## Example
```typescript
// google-map-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapMarkerClusterer, MapAdvancedMarker} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapMarkerClusterer, MapAdvancedMarker],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
markerPositions: google.maps.LatLngLiteral[] = [];
addMarker(event: google.maps.MapMouseEvent) {
this.markerPositions.push(event.latLng.toJSON());
}
}
```
```html
<google-map
height="400px"
width="750px"
[center]="center"
[zoom]="zoom"
(mapClick)="addMarker($event)">
<map-marker-clusterer>
@for (markerPosition of markerPositions; track $index) {
<map-advanced-marker [position]="markerPosition"/>
}
</map-marker-clusterer>
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 2036,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-marker-clusterer/README.md"
}
|
components/src/google-maps/map-marker-clusterer/map-marker-clusterer.spec.ts_0_6778
|
import {Component, ViewChild} from '@angular/core';
import {ComponentFixture, TestBed, fakeAsync, flush} from '@angular/core/testing';
import type {MarkerClusterer, Renderer, Algorithm} from './map-marker-clusterer-types';
import {DEFAULT_OPTIONS} from '../google-map/google-map';
import {GoogleMapsModule} from '../google-maps-module';
import {
createMapConstructorSpy,
createMapSpy,
createMarkerClustererConstructorSpy,
createMarkerClustererSpy,
createAdvancedMarkerSpy,
createAdvancedMarkerConstructorSpy,
} from '../testing/fake-google-map-utils';
import {MapMarkerClusterer} from './map-marker-clusterer';
describe('MapMarkerClusterer', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
let markerClustererSpy: jasmine.SpyObj<MarkerClusterer>;
let markerClustererConstructorSpy: jasmine.Spy;
let fixture: ComponentFixture<TestApp>;
const anyMarkerMatcher = jasmine.any(
Object,
) as unknown as google.maps.marker.AdvancedMarkerElement;
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy).and.callThrough();
const markerSpy = createAdvancedMarkerSpy({});
// The spy target function cannot be an arrow-function as this breaks when created
// through `new`.
createAdvancedMarkerConstructorSpy(markerSpy).and.callFake(function () {
return createAdvancedMarkerSpy({});
});
markerClustererSpy = createMarkerClustererSpy();
markerClustererConstructorSpy =
createMarkerClustererConstructorSpy(markerClustererSpy).and.callThrough();
fixture = TestBed.createComponent(TestApp);
});
afterEach(() => {
(window.google as any) = undefined;
(window as any).markerClusterer = undefined;
});
it('throws an error if the clustering library has not been loaded', fakeAsync(() => {
(window as any).markerClusterer = undefined;
markerClustererConstructorSpy = createMarkerClustererConstructorSpy(
markerClustererSpy,
false,
).and.callThrough();
expect(() => {
fixture.detectChanges();
flush();
}).toThrowError(/MarkerClusterer class not found, cannot construct a marker cluster/);
}));
it('initializes a Google Map Marker Clusterer', fakeAsync(() => {
fixture.detectChanges();
flush();
expect(markerClustererConstructorSpy).toHaveBeenCalledWith({
map: mapSpy,
renderer: undefined,
algorithm: undefined,
onClusterClick: jasmine.any(Function),
});
}));
it('sets marker clusterer inputs', fakeAsync(() => {
fixture.componentInstance.algorithm = {name: 'custom'} as any;
fixture.componentInstance.renderer = {render: () => null!};
fixture.detectChanges();
flush();
expect(markerClustererConstructorSpy).toHaveBeenCalledWith({
map: mapSpy,
algorithm: fixture.componentInstance.algorithm,
renderer: fixture.componentInstance.renderer,
onClusterClick: jasmine.any(Function),
});
}));
it('recreates the clusterer if the options change', fakeAsync(() => {
fixture.componentInstance.algorithm = {name: 'custom1'} as any;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(markerClustererConstructorSpy).toHaveBeenCalledWith({
map: mapSpy,
algorithm: jasmine.objectContaining({name: 'custom1'}),
renderer: undefined,
onClusterClick: jasmine.any(Function),
});
fixture.componentInstance.algorithm = {name: 'custom2'} as any;
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(markerClustererConstructorSpy).toHaveBeenCalledWith({
map: mapSpy,
algorithm: jasmine.objectContaining({name: 'custom2'}),
renderer: undefined,
onClusterClick: jasmine.any(Function),
});
}));
it('sets Google Maps Markers in the MarkerClusterer', fakeAsync(() => {
fixture.detectChanges();
flush();
expect(markerClustererSpy.addMarkers).toHaveBeenCalledWith([
anyMarkerMatcher,
anyMarkerMatcher,
]);
}));
it('updates Google Maps Markers in the Marker Clusterer', fakeAsync(() => {
fixture.detectChanges();
flush();
expect(markerClustererSpy.addMarkers).toHaveBeenCalledWith([
anyMarkerMatcher,
anyMarkerMatcher,
]);
fixture.componentInstance.state = 'state2';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(markerClustererSpy.addMarkers).toHaveBeenCalledWith([anyMarkerMatcher], true);
expect(markerClustererSpy.removeMarkers).toHaveBeenCalledWith([anyMarkerMatcher], true);
expect(markerClustererSpy.render).toHaveBeenCalledTimes(1);
fixture.componentInstance.state = 'state0';
fixture.changeDetectorRef.markForCheck();
fixture.detectChanges();
flush();
expect(markerClustererSpy.addMarkers).toHaveBeenCalledWith([], true);
expect(markerClustererSpy.removeMarkers).toHaveBeenCalledWith(
[anyMarkerMatcher, anyMarkerMatcher],
true,
);
expect(markerClustererSpy.render).toHaveBeenCalledTimes(2);
}));
it('initializes event handlers on the map related to clustering', fakeAsync(() => {
fixture.detectChanges();
flush();
expect(mapSpy.addListener).toHaveBeenCalledWith('clusteringbegin', jasmine.any(Function));
expect(mapSpy.addListener).not.toHaveBeenCalledWith('clusteringend', jasmine.any(Function));
}));
it('emits to clusterClick when the `onClusterClick` callback is invoked', fakeAsync(() => {
fixture.detectChanges();
flush();
expect(fixture.componentInstance.onClusterClick).not.toHaveBeenCalled();
const callback = markerClustererConstructorSpy.calls.mostRecent().args[0].onClusterClick;
callback({}, {}, {});
fixture.detectChanges();
flush();
expect(fixture.componentInstance.onClusterClick).toHaveBeenCalledTimes(1);
}));
});
@Component({
selector: 'test-app',
standalone: true,
imports: [GoogleMapsModule],
template: `
<google-map>
<map-marker-clusterer
(clusteringbegin)="onClusteringBegin()"
(clusterClick)="onClusterClick()"
[renderer]="renderer"
[algorithm]="algorithm">
@if (state === 'state1') {
<map-advanced-marker/>
}
@if (state === 'state1' || state === 'state2') {
<map-advanced-marker/>
}
@if (state === 'state2') {
<map-advanced-marker/>
}
</map-marker-clusterer>
</google-map>
`,
})
class TestApp {
@ViewChild(MapMarkerClusterer) markerClusterer: MapMarkerClusterer;
renderer: Renderer;
algorithm: Algorithm;
state = 'state1';
onClusteringBegin = jasmine.createSpy('onclusteringbegin spy');
onClusterClick = jasmine.createSpy('clusterClick spy');
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 6778,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-marker-clusterer/map-marker-clusterer.spec.ts"
}
|
components/src/google-maps/map-marker-clusterer/map-marker-clusterer-types.ts_0_4636
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/// <reference types="google.maps" preserve="true" />
import {Marker} from '../marker-utilities';
// This file duplicates the necessary types from the `@googlemaps/markerclusterer`
// package which isn't available for use internally.
// tslint:disable
export interface ClusterOptions {
position?: google.maps.LatLng | google.maps.LatLngLiteral;
markers?: Marker[];
}
export declare class Cluster {
marker?: Marker;
readonly markers?: Marker[];
protected _position: google.maps.LatLng;
constructor({markers, position}: ClusterOptions);
get bounds(): google.maps.LatLngBounds | undefined;
get position(): google.maps.LatLng;
/**
* Get the count of **visible** markers.
*/
get count(): number;
/**
* Add a marker to the cluster.
*/
push(marker: Marker): void;
/**
* Cleanup references and remove marker from map.
*/
delete(): void;
}
export declare class MarkerClusterer extends google.maps.OverlayView {
onClusterClick: onClusterClickHandler;
protected algorithm: Algorithm;
protected clusters: Cluster[];
protected markers: Marker[];
protected renderer: Renderer;
protected map: google.maps.Map | null;
protected idleListener: google.maps.MapsEventListener;
constructor({
map,
markers,
algorithmOptions,
algorithm,
renderer,
onClusterClick,
}: MarkerClustererOptions);
addMarker(marker: Marker, noDraw?: boolean): void;
addMarkers(markers: Marker[], noDraw?: boolean): void;
removeMarker(marker: Marker, noDraw?: boolean): boolean;
removeMarkers(markers: Marker[], noDraw?: boolean): boolean;
clearMarkers(noDraw?: boolean): void;
render(): void;
onAdd(): void;
onRemove(): void;
protected reset(): void;
protected renderClusters(): void;
}
export type onClusterClickHandler = (
event: google.maps.MapMouseEvent,
cluster: Cluster,
map: google.maps.Map,
) => void;
export interface MarkerClustererOptions {
markers?: Marker[];
/**
* An algorithm to cluster markers. Default is {@link SuperClusterAlgorithm}. Must
* provide a `calculate` method accepting {@link AlgorithmInput} and returning
* an array of {@link Cluster}.
*/
algorithm?: Algorithm;
algorithmOptions?: AlgorithmOptions;
map?: google.maps.Map | null;
/**
* An object that converts a {@link Cluster} into a `google.maps.Marker`.
* Default is {@link DefaultRenderer}.
*/
renderer?: Renderer;
onClusterClick?: onClusterClickHandler;
}
export declare enum MarkerClustererEvents {
CLUSTERING_BEGIN = 'clusteringbegin',
CLUSTERING_END = 'clusteringend',
CLUSTER_CLICK = 'click',
}
export declare const defaultOnClusterClickHandler: onClusterClickHandler;
export interface Renderer {
/**
* Turn a {@link Cluster} into a `Marker`.
*
* Below is a simple example to create a marker with the number of markers in the cluster as a label.
*
* ```typescript
* return new google.maps.Marker({
* position,
* label: String(markers.length),
* });
* ```
*/
render(cluster: Cluster, stats: ClusterStats, map: google.maps.Map): Marker;
}
export declare class ClusterStats {
readonly markers: {
sum: number;
};
readonly clusters: {
count: number;
markers: {
mean: number;
sum: number;
min: number;
max: number;
};
};
constructor(markers: Marker[], clusters: Cluster[]);
}
export interface Algorithm {
/**
* Calculates an array of {@link Cluster}.
*/
calculate: ({markers, map}: AlgorithmInput) => AlgorithmOutput;
}
export interface AlgorithmOptions {
maxZoom?: number;
}
export interface AlgorithmInput {
/**
* The map containing the markers and clusters.
*/
map: google.maps.Map;
/**
* An array of markers to be clustered.
*
* There are some specific edge cases to be aware of including the following:
* * Markers that are not visible.
*/
markers: Marker[];
/**
* The `mapCanvasProjection` enables easy conversion from lat/lng to pixel.
*
* @see [MapCanvasProjection](https://developers.google.com/maps/documentation/javascript/reference/overlay-view#MapCanvasProjection)
*/
mapCanvasProjection: google.maps.MapCanvasProjection;
}
export interface AlgorithmOutput {
/**
* The clusters returned based upon the {@link AlgorithmInput}.
*/
clusters: Cluster[];
/**
* A boolean flag indicating that the clusters have not changed.
*/
changed?: boolean;
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 4636,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-marker-clusterer/map-marker-clusterer-types.ts"
}
|
components/src/google-maps/map-polyline/map-polyline.ts_0_8708
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Directive,
Input,
OnDestroy,
OnInit,
Output,
NgZone,
inject,
EventEmitter,
} from '@angular/core';
import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs';
import {map, take, takeUntil} from 'rxjs/operators';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
/**
* Angular component that renders a Google Maps Polyline via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline
*/
@Directive({
selector: 'map-polyline',
exportAs: 'mapPolyline',
})
export class MapPolyline implements OnInit, OnDestroy {
private readonly _map = inject(GoogleMap);
private _ngZone = inject(NgZone);
private _eventManager = new MapEventManager(inject(NgZone));
private readonly _options = new BehaviorSubject<google.maps.PolylineOptions>({});
private readonly _path = new BehaviorSubject<
| google.maps.MVCArray<google.maps.LatLng>
| google.maps.LatLng[]
| google.maps.LatLngLiteral[]
| undefined
>(undefined);
private readonly _destroyed = new Subject<void>();
/**
* The underlying google.maps.Polyline object.
*
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline
*/
polyline?: google.maps.Polyline;
@Input()
set options(options: google.maps.PolylineOptions) {
this._options.next(options || {});
}
@Input()
set path(
path:
| google.maps.MVCArray<google.maps.LatLng>
| google.maps.LatLng[]
| google.maps.LatLngLiteral[],
) {
this._path.next(path);
}
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.click
*/
@Output() readonly polylineClick: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('click');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.dblclick
*/
@Output() readonly polylineDblclick: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('dblclick');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.drag
*/
@Output() readonly polylineDrag: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('drag');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.dragend
*/
@Output() readonly polylineDragend: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragend');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.dragstart
*/
@Output() readonly polylineDragstart: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragstart');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.mousedown
*/
@Output() readonly polylineMousedown: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('mousedown');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.mousemove
*/
@Output() readonly polylineMousemove: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('mousemove');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.mouseout
*/
@Output() readonly polylineMouseout: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('mouseout');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.mouseover
*/
@Output() readonly polylineMouseover: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('mouseover');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.mouseup
*/
@Output() readonly polylineMouseup: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('mouseup');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.rightclick
*/
@Output() readonly polylineRightclick: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('rightclick');
/** Event emitted when the polyline is initialized. */
@Output() readonly polylineInitialized: EventEmitter<google.maps.Polyline> =
new EventEmitter<google.maps.Polyline>();
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (this._map._isBrowser) {
this._combineOptions()
.pipe(take(1))
.subscribe(options => {
if (google.maps.Polyline && this._map.googleMap) {
this._initialize(this._map.googleMap, google.maps.Polyline, options);
} else {
this._ngZone.runOutsideAngular(() => {
Promise.all([this._map._resolveMap(), google.maps.importLibrary('maps')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.MapsLibrary).Polyline, options);
},
);
});
}
});
}
}
private _initialize(
map: google.maps.Map,
polylineConstructor: typeof google.maps.Polyline,
options: google.maps.PolygonOptions,
) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.polyline = new polylineConstructor(options);
this._assertInitialized();
this.polyline.setMap(map);
this._eventManager.setTarget(this.polyline);
this.polylineInitialized.emit(this.polyline);
this._watchForOptionsChanges();
this._watchForPathChanges();
});
}
ngOnDestroy() {
this._eventManager.destroy();
this._destroyed.next();
this._destroyed.complete();
this.polyline?.setMap(null);
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.getDraggable
*/
getDraggable(): boolean {
this._assertInitialized();
return this.polyline.getDraggable();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.getEditable
*/
getEditable(): boolean {
this._assertInitialized();
return this.polyline.getEditable();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.getPath
*/
getPath(): google.maps.MVCArray<google.maps.LatLng> {
this._assertInitialized();
return this.polyline.getPath();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polyline.getVisible
*/
getVisible(): boolean {
this._assertInitialized();
return this.polyline.getVisible();
}
private _combineOptions(): Observable<google.maps.PolylineOptions> {
return combineLatest([this._options, this._path]).pipe(
map(([options, path]) => {
const combinedOptions: google.maps.PolylineOptions = {
...options,
path: path || options.path,
};
return combinedOptions;
}),
);
}
private _watchForOptionsChanges() {
this._options.pipe(takeUntil(this._destroyed)).subscribe(options => {
this._assertInitialized();
this.polyline.setOptions(options);
});
}
private _watchForPathChanges() {
this._path.pipe(takeUntil(this._destroyed)).subscribe(path => {
if (path) {
this._assertInitialized();
this.polyline.setPath(path);
}
});
}
private _assertInitialized(): asserts this is {polyline: google.maps.Polyline} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.polyline) {
throw Error(
'Cannot interact with a Google Map Polyline before it has been ' +
'initialized. Please wait for the Polyline to load before trying to interact with it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 8708,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-polyline/map-polyline.ts"
}
|
components/src/google-maps/map-polyline/map-polyline.spec.ts_0_5849
|
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createMapConstructorSpy,
createMapSpy,
createPolylineConstructorSpy,
createPolylineSpy,
} from '../testing/fake-google-map-utils';
import {MapPolyline} from './map-polyline';
describe('MapPolyline', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
let polylinePath: google.maps.LatLngLiteral[];
let polylineOptions: google.maps.PolylineOptions;
beforeEach(() => {
polylinePath = [
{lat: 25, lng: 26},
{lat: 26, lng: 27},
{lat: 30, lng: 34},
];
polylineOptions = {
path: polylinePath,
strokeColor: 'grey',
strokeOpacity: 0.8,
};
});
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map Polyline', fakeAsync(() => {
const polylineSpy = createPolylineSpy({});
const polylineConstructorSpy = createPolylineConstructorSpy(polylineSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(polylineConstructorSpy).toHaveBeenCalledWith({path: undefined});
expect(polylineSpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
it('sets path from input', fakeAsync(() => {
const path: google.maps.LatLngLiteral[] = [{lat: 3, lng: 5}];
const options: google.maps.PolylineOptions = {path};
const polylineSpy = createPolylineSpy(options);
const polylineConstructorSpy = createPolylineConstructorSpy(polylineSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.path = path;
fixture.detectChanges();
flush();
expect(polylineConstructorSpy).toHaveBeenCalledWith(options);
}));
it('gives precedence to path input over options', fakeAsync(() => {
const path: google.maps.LatLngLiteral[] = [{lat: 3, lng: 5}];
const expectedOptions: google.maps.PolylineOptions = {...polylineOptions, path};
const polylineSpy = createPolylineSpy(expectedOptions);
const polylineConstructorSpy = createPolylineConstructorSpy(polylineSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = polylineOptions;
fixture.componentInstance.path = path;
fixture.detectChanges();
flush();
expect(polylineConstructorSpy).toHaveBeenCalledWith(expectedOptions);
}));
it('exposes methods that provide information about the Polyline', fakeAsync(() => {
const polylineSpy = createPolylineSpy(polylineOptions);
createPolylineConstructorSpy(polylineSpy);
const fixture = TestBed.createComponent(TestApp);
const polylineComponent = fixture.debugElement
.query(By.directive(MapPolyline))!
.injector.get<MapPolyline>(MapPolyline);
fixture.detectChanges();
flush();
polylineSpy.getDraggable.and.returnValue(true);
expect(polylineComponent.getDraggable()).toBe(true);
polylineSpy.getEditable.and.returnValue(true);
expect(polylineComponent.getEditable()).toBe(true);
polylineComponent.getPath();
expect(polylineSpy.getPath).toHaveBeenCalled();
polylineSpy.getVisible.and.returnValue(true);
expect(polylineComponent.getVisible()).toBe(true);
}));
it('initializes Polyline event handlers', fakeAsync(() => {
const polylineSpy = createPolylineSpy(polylineOptions);
createPolylineConstructorSpy(polylineSpy);
const addSpy = polylineSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).toHaveBeenCalledWith('click', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dblclick', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('drag', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragend', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragstart', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mousedown', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mousemove', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseout', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseover', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseup', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('rightclick', jasmine.any(Function));
}));
it('should be able to add an event listener after init', fakeAsync(() => {
const polylineSpy = createPolylineSpy(polylineOptions);
createPolylineConstructorSpy(polylineSpy);
const addSpy = polylineSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).not.toHaveBeenCalledWith('dragend', jasmine.any(Function));
// Pick an event that isn't bound in the template.
const subscription = fixture.componentInstance.polyline.polylineDragend.subscribe();
fixture.detectChanges();
expect(addSpy).toHaveBeenCalledWith('dragend', jasmine.any(Function));
subscription.unsubscribe();
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-polyline
[options]="options"
[path]="path"
(polylineClick)="handleClick()"
(polylineRightclick)="handleRightclick()" />
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapPolyline],
})
class TestApp {
@ViewChild(MapPolyline) polyline: MapPolyline;
options?: google.maps.PolylineOptions;
path?: google.maps.LatLngLiteral[];
handleClick() {}
handleRightclick() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 5849,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-polyline/map-polyline.spec.ts"
}
|
components/src/google-maps/map-polyline/README.md_0_902
|
# MapPolyline
The `MapPolyline` component wraps the [`google.maps.Polyline` class](https://developers.google.com/maps/documentation/javascript/reference/polygon#Polyline) from the Google Maps JavaScript API.
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapPolyline} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapPolyline],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
vertices: google.maps.LatLngLiteral[] = [
{lat: 13, lng: 13},
{lat: -13, lng: 0},
{lat: 13, lng: -13},
];
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map height="400px" width="750px" [center]="center" [zoom]="zoom">
<map-polyline [path]="vertices" />
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 902,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-polyline/README.md"
}
|
components/src/google-maps/schematics/BUILD.bazel_0_963
|
load("@build_bazel_rules_nodejs//:index.bzl", "copy_to_bin")
load("//tools:defaults.bzl", "pkg_npm", "ts_library")
package(default_visibility = ["//visibility:public"])
copy_to_bin(
name = "schematics_assets",
srcs = glob(["**/*.json"]),
)
ts_library(
name = "schematics",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
# Schematics can not yet run in ESM module. For now we continue to use CommonJS.
# TODO(ESM): remove this once the Angular CLI supports ESM schematics.
devmode_module = "commonjs",
prodmode_module = "commonjs",
deps = [
"@npm//@angular-devkit/schematics",
"@npm//@types/node",
],
)
# This package is intended to be combined into the main @angular/google-maps package as a dep.
pkg_npm(
name = "npm_package",
deps = [
":schematics",
":schematics_assets",
"//src/google-maps/schematics/ng-update:ng_update_index",
],
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 963,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/schematics/BUILD.bazel"
}
|
components/src/google-maps/schematics/ng-update/v19-ng-update.spec.ts_0_5995
|
import {getSystemPath, normalize, virtualFs} from '@angular-devkit/core';
import {TempScopedNodeJsSyncHost} from '@angular-devkit/core/node/testing';
import {HostTree} from '@angular-devkit/schematics';
import {SchematicTestRunner, UnitTestTree} from '@angular-devkit/schematics/testing';
import {runfiles} from '@bazel/runfiles';
import shx from 'shelljs';
describe('v19 migration', () => {
let runner: SchematicTestRunner;
let host: TempScopedNodeJsSyncHost;
let tree: UnitTestTree;
let tmpDirPath: string;
function writeFile(filePath: string, contents: string) {
host.sync.write(normalize(filePath), virtualFs.stringToFileBuffer(contents));
}
function runMigration() {
return runner.runSchematic('migration-v19', {}, tree);
}
function stripWhitespace(value: string) {
return value.replace(/\s/g, '');
}
beforeEach(() => {
runner = new SchematicTestRunner('test', runfiles.resolvePackageRelative('../migration.json'));
host = new TempScopedNodeJsSyncHost();
tree = new UnitTestTree(new HostTree(host));
writeFile(
'/angular.json',
JSON.stringify({
version: 1,
projects: {t: {root: '', architect: {build: {options: {tsConfig: './tsconfig.json'}}}}},
}),
);
tmpDirPath = getSystemPath(host.root);
shx.cd(tmpDirPath);
});
it('should migrate the clusterer in HTML files', async () => {
writeFile(
'/my-comp.html',
`
<section>
<map-marker-clusterer>
<map-marker/>
<map-marker/>
<map-marker/>
</map-marker-clusterer>
</section>
<main>
<div>
<map-marker-clusterer some-attr>
@for (marker of markers; track $index) {
<map-marker/>
}
</map-marker-clusterer>
</div>
</main>
`,
);
await runMigration();
const content = tree.readContent('/my-comp.html');
expect(stripWhitespace(content)).toBe(
stripWhitespace(`
<section>
<deprecated-map-marker-clusterer>
<map-marker/>
<map-marker/>
<map-marker/>
</deprecated-map-marker-clusterer>
</section>
<main>
<div>
<deprecated-map-marker-clusterer some-attr>
@for (marker of markers; track $index) {
<map-marker/>
}
</deprecated-map-marker-clusterer>
</div>
</main>
`),
);
});
it('should migrate the clusterer in a TypeScript file', async () => {
writeFile(
'/my-comp.ts',
`
import {Component} from '@angular/core';
import {MapMarkerClusterer, MapMarker} from '@angular/google-maps';
@Component({
template: '<map-marker-clusterer><map-marker/></map-marker-clusterer>',
imports: [MapMarkerClusterer, MapMarker]
})
export class MyComp {}
`,
);
await runMigration();
const content = tree.readContent('/my-comp.ts');
expect(stripWhitespace(content)).toBe(
stripWhitespace(`
import {Component} from '@angular/core';
import {DeprecatedMapMarkerClusterer as MapMarkerClusterer, MapMarker} from '@angular/google-maps';
@Component({
template: '<deprecated-map-marker-clusterer><map-marker/></deprecated-map-marker-clusterer>',
imports: [MapMarkerClusterer, MapMarker]
})
export class MyComp {}
`),
);
});
it('should migrate an aliased clusterer in a TypeScript file', async () => {
writeFile(
'/my-comp.ts',
`
import {Component} from '@angular/core';
import {MapMarkerClusterer as MyClusterer, MapMarker} from '@angular/google-maps';
@Component({
template: '<map-marker-clusterer><map-marker/></map-marker-clusterer>',
imports: [MyClusterer, MapMarker]
})
export class MyComp {}
`,
);
await runMigration();
const content = tree.readContent('/my-comp.ts');
expect(stripWhitespace(content)).toBe(
stripWhitespace(`
import {Component} from '@angular/core';
import {DeprecatedMapMarkerClusterer as MyClusterer, MapMarker} from '@angular/google-maps';
@Component({
template: '<deprecated-map-marker-clusterer><map-marker/></deprecated-map-marker-clusterer>',
imports: [MyClusterer, MapMarker]
})
export class MyComp {}
`),
);
});
it('should migrate a re-exported clusterer', async () => {
writeFile(
'/index.ts',
`
export {MapMarkerClusterer} from '@angular/google-maps';
export {MapMarkerClusterer as AliasedMapMarkerClusterer} from '@angular/google-maps';
`,
);
await runMigration();
const content = tree.readContent('/index.ts');
expect(stripWhitespace(content)).toBe(
stripWhitespace(`
export {DeprecatedMapMarkerClusterer as MapMarkerClusterer} from '@angular/google-maps';
export {DeprecatedMapMarkerClusterer as AliasedMapMarkerClusterer} from '@angular/google-maps';
`),
);
});
it('should not migrate an import outside of the Angular module', async () => {
writeFile(
'/my-comp.ts',
`
import {Component} from '@angular/core';
import {MapMarkerClusterer} from '@not-angular/google-maps';
@Component({
template: '',
imports: [MapMarkerClusterer]
})
export class MyComp {}
`,
);
await runMigration();
const content = tree.readContent('/my-comp.ts');
expect(stripWhitespace(content)).toBe(
stripWhitespace(`
import {Component} from '@angular/core';
import {MapMarkerClusterer} from '@not-angular/google-maps';
@Component({
template: '',
imports: [MapMarkerClusterer]
})
export class MyComp {}
`),
);
});
});
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 5995,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/schematics/ng-update/v19-ng-update.spec.ts"
}
|
components/src/google-maps/schematics/ng-update/BUILD.bazel_0_1972
|
load("//tools:defaults.bzl", "esbuild", "jasmine_node_test", "spec_bundle", "ts_library")
## THIS ONE IS ESM
# By default everything is ESM
# ESBUild needs ESM for bundling. Cannot reliably use CJS as input.
ts_library(
name = "ng_update_lib",
srcs = glob(
["**/*.ts"],
exclude = ["**/*.spec.ts"],
),
# Schematics can not yet run in ESM module. For now we continue to use CommonJS.
# TODO(ESM): remove this once the Angular CLI supports ESM schematics.
devmode_module = "commonjs",
deps = [
"@npm//@angular-devkit/core",
"@npm//@angular-devkit/schematics",
"@npm//@schematics/angular",
"@npm//@types/node",
"@npm//typescript",
],
)
esbuild(
name = "ng_update_index",
entry_point = ":index.ts",
external = [
"@schematics/angular",
"@angular-devkit/schematics",
"@angular-devkit/core",
"typescript",
],
# TODO: Switch to ESM when Angular CLI supports it.
format = "cjs",
output = "index_bundled.js",
platform = "node",
target = "es2015",
visibility = ["//src/google-maps/schematics:__pkg__"],
deps = [":ng_update_lib"],
)
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.spec.ts"]),
deps = [
":ng_update_lib",
"@npm//@angular-devkit/core",
"@npm//@angular-devkit/schematics",
"@npm//@bazel/runfiles",
"@npm//@types/jasmine",
"@npm//@types/node",
"@npm//@types/shelljs",
],
)
spec_bundle(
name = "spec_bundle",
external = [
"*/paths.js",
"shelljs",
"@angular-devkit/core/node",
],
platform = "cjs-legacy",
target = "es2020",
deps = [":test_lib"],
)
jasmine_node_test(
name = "test",
data = [
":ng_update_index",
"//src/google-maps/schematics:schematics_assets",
"@npm//shelljs",
],
deps = [
":spec_bundle",
],
)
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 1972,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/schematics/ng-update/BUILD.bazel"
}
|
components/src/google-maps/schematics/ng-update/index.ts_0_4690
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Path} from '@angular-devkit/core';
import {Rule, Tree} from '@angular-devkit/schematics';
import ts from 'typescript';
/** Tag name of the clusterer component. */
const TAG_NAME = 'map-marker-clusterer';
/** Module from which the clusterer is being imported. */
const MODULE_NAME = '@angular/google-maps';
/** Old name of the clusterer class. */
const CLASS_NAME = 'MapMarkerClusterer';
/** New name of the clusterer class. */
const DEPRECATED_CLASS_NAME = 'DeprecatedMapMarkerClusterer';
/** Entry point for the migration schematics with target of Angular Material v19 */
export function updateToV19(): Rule {
return tree => {
tree.visit(path => {
if (path.endsWith('.html')) {
const content = tree.readText(path);
if (content.includes('<' + TAG_NAME)) {
tree.overwrite(path, migrateHtml(content));
}
} else if (path.endsWith('.ts') && !path.endsWith('.d.ts')) {
migrateTypeScript(path, tree);
}
});
};
}
/** Migrates an HTML template from the old tag name to the new one. */
function migrateHtml(content: string): string {
return content
.replace(/<map-marker-clusterer/g, '<deprecated-map-marker-clusterer')
.replace(/<\/map-marker-clusterer/g, '</deprecated-map-marker-clusterer');
}
/** Migrates a TypeScript file from the old tag and class names to the new ones. */
function migrateTypeScript(path: Path, tree: Tree) {
const content = tree.readText(path);
// Exit early if none of the symbols we're looking for are mentioned.
if (
!content.includes('<' + TAG_NAME) &&
!content.includes(MODULE_NAME) &&
!content.includes(CLASS_NAME)
) {
return;
}
const sourceFile = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, true);
const toMigrate = findTypeScriptNodesToMigrate(sourceFile);
if (toMigrate.length === 0) {
return;
}
const printer = ts.createPrinter();
const update = tree.beginUpdate(path);
for (const node of toMigrate) {
let replacement: ts.Node;
if (ts.isStringLiteralLike(node)) {
// Strings should be migrated as if they're HTML.
if (ts.isStringLiteral(node)) {
replacement = ts.factory.createStringLiteral(
migrateHtml(node.text),
node.getText()[0] === `'`,
);
} else {
replacement = ts.factory.createNoSubstitutionTemplateLiteral(migrateHtml(node.text));
}
} else {
// Imports/exports should preserve the old name, but import the clusterer using the new one.
const propertyName = ts.factory.createIdentifier(DEPRECATED_CLASS_NAME);
const name = node.name as ts.Identifier;
replacement = ts.isImportSpecifier(node)
? ts.factory.updateImportSpecifier(node, node.isTypeOnly, propertyName, name)
: ts.factory.updateExportSpecifier(node, node.isTypeOnly, propertyName, name);
}
update
.remove(node.getStart(), node.getWidth())
.insertLeft(
node.getStart(),
printer.printNode(ts.EmitHint.Unspecified, replacement, sourceFile),
);
}
tree.commitUpdate(update);
}
/** Finds the TypeScript nodes that need to be migrated from a specific file. */
function findTypeScriptNodesToMigrate(sourceFile: ts.SourceFile) {
const results: (ts.StringLiteralLike | ts.ImportSpecifier | ts.ExportSpecifier)[] = [];
sourceFile.forEachChild(function walk(node) {
// Most likely a template using the clusterer.
if (ts.isStringLiteral(node) && node.text.includes('<' + TAG_NAME)) {
results.push(node);
} else if (
// Import/export referencing the clusterer.
(ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) &&
node.moduleSpecifier &&
ts.isStringLiteralLike(node.moduleSpecifier) &&
node.moduleSpecifier.text === MODULE_NAME
) {
const bindings = ts.isImportDeclaration(node)
? node.importClause?.namedBindings
: node.exportClause;
if (bindings && (ts.isNamedImports(bindings) || ts.isNamedExports(bindings))) {
bindings.elements.forEach(element => {
const symbolName = element.propertyName || element.name;
if (ts.isIdentifier(symbolName) && symbolName.text === CLASS_NAME) {
results.push(element);
}
});
}
} else {
node.forEachChild(walk);
}
});
// Sort the results in reverse order to make applying the updates easier.
return results.sort((a, b) => b.getStart() - a.getStart());
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 4690,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/schematics/ng-update/index.ts"
}
|
components/src/google-maps/schematics/ng-add/index.ts_0_455
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Rule} from '@angular-devkit/schematics';
export default function (): Rule {
// Noop schematic so the CLI doesn't throw if users try to `ng add` this package.
// Also allows us to add more functionality in the future.
return () => {};
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 455,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/schematics/ng-add/index.ts"
}
|
components/src/google-maps/map-polygon/map-polygon.spec.ts_0_5866
|
import {Component, ViewChild} from '@angular/core';
import {TestBed, fakeAsync, flush} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {DEFAULT_OPTIONS, GoogleMap} from '../google-map/google-map';
import {
createMapConstructorSpy,
createMapSpy,
createPolygonConstructorSpy,
createPolygonSpy,
} from '../testing/fake-google-map-utils';
import {MapPolygon} from './map-polygon';
describe('MapPolygon', () => {
let mapSpy: jasmine.SpyObj<google.maps.Map>;
let polygonPath: google.maps.LatLngLiteral[];
let polygonOptions: google.maps.PolygonOptions;
beforeEach(() => {
polygonPath = [
{lat: 25, lng: 26},
{lat: 26, lng: 27},
{lat: 30, lng: 34},
];
polygonOptions = {paths: polygonPath, strokeColor: 'grey', strokeOpacity: 0.8};
});
beforeEach(() => {
mapSpy = createMapSpy(DEFAULT_OPTIONS);
createMapConstructorSpy(mapSpy);
});
afterEach(() => {
(window.google as any) = undefined;
});
it('initializes a Google Map Polygon', fakeAsync(() => {
const polygonSpy = createPolygonSpy({});
const polygonConstructorSpy = createPolygonConstructorSpy(polygonSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(polygonConstructorSpy).toHaveBeenCalledWith({paths: undefined});
expect(polygonSpy.setMap).toHaveBeenCalledWith(mapSpy);
}));
it('sets path from input', fakeAsync(() => {
const paths: google.maps.LatLngLiteral[] = [{lat: 3, lng: 5}];
const options: google.maps.PolygonOptions = {paths};
const polygonSpy = createPolygonSpy(options);
const polygonConstructorSpy = createPolygonConstructorSpy(polygonSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.paths = paths;
fixture.detectChanges();
flush();
expect(polygonConstructorSpy).toHaveBeenCalledWith(options);
}));
it('gives precedence to path input over options', fakeAsync(() => {
const paths: google.maps.LatLngLiteral[] = [{lat: 3, lng: 5}];
const expectedOptions: google.maps.PolygonOptions = {...polygonOptions, paths};
const polygonSpy = createPolygonSpy(expectedOptions);
const polygonConstructorSpy = createPolygonConstructorSpy(polygonSpy);
const fixture = TestBed.createComponent(TestApp);
fixture.componentInstance.options = polygonOptions;
fixture.componentInstance.paths = paths;
fixture.detectChanges();
flush();
expect(polygonConstructorSpy).toHaveBeenCalledWith(expectedOptions);
}));
it('exposes methods that provide information about the Polygon', fakeAsync(() => {
const polygonSpy = createPolygonSpy(polygonOptions);
createPolygonConstructorSpy(polygonSpy);
const fixture = TestBed.createComponent(TestApp);
const polygonComponent = fixture.debugElement
.query(By.directive(MapPolygon))!
.injector.get<MapPolygon>(MapPolygon);
fixture.detectChanges();
flush();
polygonSpy.getDraggable.and.returnValue(true);
expect(polygonComponent.getDraggable()).toBe(true);
polygonSpy.getEditable.and.returnValue(true);
expect(polygonComponent.getEditable()).toBe(true);
polygonComponent.getPath();
expect(polygonSpy.getPath).toHaveBeenCalled();
polygonComponent.getPaths();
expect(polygonSpy.getPaths).toHaveBeenCalled();
polygonSpy.getVisible.and.returnValue(true);
expect(polygonComponent.getVisible()).toBe(true);
}));
it('initializes Polygon event handlers', fakeAsync(() => {
const polygonSpy = createPolygonSpy(polygonOptions);
createPolygonConstructorSpy(polygonSpy);
const addSpy = polygonSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).toHaveBeenCalledWith('click', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dblclick', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('drag', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragend', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('dragstart', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mousedown', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mousemove', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseout', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseover', jasmine.any(Function));
expect(addSpy).not.toHaveBeenCalledWith('mouseup', jasmine.any(Function));
expect(addSpy).toHaveBeenCalledWith('rightclick', jasmine.any(Function));
}));
it('should be able to add an event listener after init', fakeAsync(() => {
const polygonSpy = createPolygonSpy(polygonOptions);
createPolygonConstructorSpy(polygonSpy);
const addSpy = polygonSpy.addListener;
const fixture = TestBed.createComponent(TestApp);
fixture.detectChanges();
flush();
expect(addSpy).not.toHaveBeenCalledWith('dragend', jasmine.any(Function));
// Pick an event that isn't bound in the template.
const subscription = fixture.componentInstance.polygon.polygonDragend.subscribe();
fixture.detectChanges();
expect(addSpy).toHaveBeenCalledWith('dragend', jasmine.any(Function));
subscription.unsubscribe();
}));
});
@Component({
selector: 'test-app',
template: `
<google-map>
<map-polygon
[options]="options"
[paths]="paths"
(polygonClick)="handleClick()"
(polygonRightclick)="handleRightclick()">
</map-polygon>
</google-map>
`,
standalone: true,
imports: [GoogleMap, MapPolygon],
})
class TestApp {
@ViewChild(MapPolygon) polygon: MapPolygon;
options?: google.maps.PolygonOptions;
paths?: google.maps.LatLngLiteral[];
handleClick() {}
handleRightclick() {}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 5866,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-polygon/map-polygon.spec.ts"
}
|
components/src/google-maps/map-polygon/map-polygon.ts_0_9065
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Workaround for: https://github.com/bazelbuild/rules_nodejs/issues/1265
/// <reference types="google.maps" preserve="true" />
import {
Directive,
Input,
OnDestroy,
OnInit,
Output,
NgZone,
inject,
EventEmitter,
} from '@angular/core';
import {BehaviorSubject, combineLatest, Observable, Subject} from 'rxjs';
import {map, take, takeUntil} from 'rxjs/operators';
import {GoogleMap} from '../google-map/google-map';
import {MapEventManager} from '../map-event-manager';
/**
* Angular component that renders a Google Maps Polygon via the Google Maps JavaScript API.
*
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon
*/
@Directive({
selector: 'map-polygon',
exportAs: 'mapPolygon',
})
export class MapPolygon implements OnInit, OnDestroy {
private readonly _map = inject(GoogleMap);
private readonly _ngZone = inject(NgZone);
private _eventManager = new MapEventManager(inject(NgZone));
private readonly _options = new BehaviorSubject<google.maps.PolygonOptions>({});
private readonly _paths = new BehaviorSubject<
| google.maps.MVCArray<google.maps.MVCArray<google.maps.LatLng>>
| google.maps.MVCArray<google.maps.LatLng>
| google.maps.LatLng[]
| google.maps.LatLngLiteral[]
| undefined
>(undefined);
private readonly _destroyed = new Subject<void>();
/**
* The underlying google.maps.Polygon object.
*
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon
*/
polygon?: google.maps.Polygon;
@Input()
set options(options: google.maps.PolygonOptions) {
this._options.next(options || {});
}
@Input()
set paths(
paths:
| google.maps.MVCArray<google.maps.MVCArray<google.maps.LatLng>>
| google.maps.MVCArray<google.maps.LatLng>
| google.maps.LatLng[]
| google.maps.LatLngLiteral[],
) {
this._paths.next(paths);
}
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.click
*/
@Output() readonly polygonClick: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('click');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.dblclick
*/
@Output() readonly polygonDblclick: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('dblclick');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.drag
*/
@Output() readonly polygonDrag: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('drag');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.dragend
*/
@Output() readonly polygonDragend: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragend');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.dragstart
*/
@Output() readonly polygonDragstart: Observable<google.maps.MapMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.MapMouseEvent>('dragstart');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.mousedown
*/
@Output() readonly polygonMousedown: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('mousedown');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.mousemove
*/
@Output() readonly polygonMousemove: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('mousemove');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.mouseout
*/
@Output() readonly polygonMouseout: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('mouseout');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.mouseover
*/
@Output() readonly polygonMouseover: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('mouseover');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.mouseup
*/
@Output() readonly polygonMouseup: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('mouseup');
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.rightclick
*/
@Output() readonly polygonRightclick: Observable<google.maps.PolyMouseEvent> =
this._eventManager.getLazyEmitter<google.maps.PolyMouseEvent>('rightclick');
/** Event emitted when the polygon is initialized. */
@Output() readonly polygonInitialized: EventEmitter<google.maps.Polygon> =
new EventEmitter<google.maps.Polygon>();
constructor(...args: unknown[]);
constructor() {}
ngOnInit() {
if (this._map._isBrowser) {
this._combineOptions()
.pipe(take(1))
.subscribe(options => {
if (google.maps.Polygon && this._map.googleMap) {
this._initialize(this._map.googleMap, google.maps.Polygon, options);
} else {
this._ngZone.runOutsideAngular(() => {
Promise.all([this._map._resolveMap(), google.maps.importLibrary('maps')]).then(
([map, lib]) => {
this._initialize(map, (lib as google.maps.MapsLibrary).Polygon, options);
},
);
});
}
});
}
}
private _initialize(
map: google.maps.Map,
polygonConstructor: typeof google.maps.Polygon,
options: google.maps.PolygonOptions,
) {
// Create the object outside the zone so its events don't trigger change detection.
// We'll bring it back in inside the `MapEventManager` only for the events that the
// user has subscribed to.
this._ngZone.runOutsideAngular(() => {
this.polygon = new polygonConstructor(options);
this._assertInitialized();
this.polygon.setMap(map);
this._eventManager.setTarget(this.polygon);
this.polygonInitialized.emit(this.polygon);
this._watchForOptionsChanges();
this._watchForPathChanges();
});
}
ngOnDestroy() {
this._eventManager.destroy();
this._destroyed.next();
this._destroyed.complete();
this.polygon?.setMap(null);
}
/**
* See
* developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.getDraggable
*/
getDraggable(): boolean {
this._assertInitialized();
return this.polygon.getDraggable();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.getEditable
*/
getEditable(): boolean {
this._assertInitialized();
return this.polygon.getEditable();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.getPath
*/
getPath(): google.maps.MVCArray<google.maps.LatLng> {
this._assertInitialized();
return this.polygon.getPath();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.getPaths
*/
getPaths(): google.maps.MVCArray<google.maps.MVCArray<google.maps.LatLng>> {
this._assertInitialized();
return this.polygon.getPaths();
}
/**
* See developers.google.com/maps/documentation/javascript/reference/polygon#Polygon.getVisible
*/
getVisible(): boolean {
this._assertInitialized();
return this.polygon.getVisible();
}
private _combineOptions(): Observable<google.maps.PolygonOptions> {
return combineLatest([this._options, this._paths]).pipe(
map(([options, paths]) => {
const combinedOptions: google.maps.PolygonOptions = {
...options,
paths: paths || options.paths,
};
return combinedOptions;
}),
);
}
private _watchForOptionsChanges() {
this._options.pipe(takeUntil(this._destroyed)).subscribe(options => {
this._assertInitialized();
this.polygon.setOptions(options);
});
}
private _watchForPathChanges() {
this._paths.pipe(takeUntil(this._destroyed)).subscribe(paths => {
if (paths) {
this._assertInitialized();
this.polygon.setPaths(paths);
}
});
}
private _assertInitialized(): asserts this is {polygon: google.maps.Polygon} {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (!this.polygon) {
throw Error(
'Cannot interact with a Google Map Polygon before it has been ' +
'initialized. Please wait for the Polygon to load before trying to interact with it.',
);
}
}
}
}
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 9065,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-polygon/map-polygon.ts"
}
|
components/src/google-maps/map-polygon/README.md_0_896
|
# MapPolygon
The `MapPolygon` component wraps the [`google.maps.Polygon` class](https://developers.google.com/maps/documentation/javascript/reference/polygon#Polygon) from the Google Maps JavaScript API.
## Example
```typescript
// google-maps-demo.component.ts
import {Component} from '@angular/core';
import {GoogleMap, MapPolygon} from '@angular/google-maps';
@Component({
selector: 'google-map-demo',
templateUrl: 'google-map-demo.html',
imports: [GoogleMap, MapPolygon],
})
export class GoogleMapDemo {
center: google.maps.LatLngLiteral = {lat: 24, lng: 12};
zoom = 4;
vertices: google.maps.LatLngLiteral[] = [
{lat: 13, lng: 13},
{lat: -13, lng: 0},
{lat: 13, lng: -13},
];
}
```
```html
<!-- google-maps-demo.component.html -->
<google-map height="400px" width="750px" [center]="center" [zoom]="zoom">
<map-polygon [paths]="vertices" />
</google-map>
```
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 896,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/google-maps/map-polygon/README.md"
}
|
components/src/material-experimental/_index.scss_0_394
|
// Component themes
@forward './column-resize/column-resize-theme' as column-resize-* show column-resize-color,
column-resize-typography, column-resize-density, column-resize-theme;
@forward './popover-edit/popover-edit-theme' as popover-edit-* show popover-edit-color,
popover-edit-typography, popover-edit-density, popover-edit-theme;
// Additional public APIs for individual components
|
{
"commit_id": "ea0d1ba7b",
"end_byte": 394,
"start_byte": 0,
"url": "https://github.com/angular/components/blob/main/src/material-experimental/_index.scss"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.