Getting started - How to use google maps api with angular-cli

I recently started working with ng2. So I created a project using angular-cli, then realized that I needed third-party modules. For example, Google maps api, lodash, jquery ... etc. I know the basics of Typescript, but how to use these modules in an Angular2 application? In addition, I want to use only the library, for example, Google maps api, and not any existing ng2 module / component that someone else made ontop Google maps api for the sake of training.

Previously, only with JS I would include a js file and refer to the api documentation to find out which methods are referencing and building my application. Now with Angular2, what steps should I take to do the same?

From my research, it looks like I first installed the necessary script type files. so for google maps i did npm install --save @types/google-maps . Now, do I need to import this module into my angular application by including it in app.module.ts? In the import array? Or is it now available worldwide?

One source mentioned installing it with npm and in my angular-cli.json, including a link to this library in an array of scripts. So:

 "scripts": ['./node_modules/googlemaps/googemaps.min.js'], 

What method to use when installing google maps api? I would think Typescript might be the way to go, since the rest of the angular application will be written to Typescript.

Now in my app.component.ts, I want to create a simple map using the installed Typescript. How can I do it? Google Maps api is said to create a new instance of such a map.

 var map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, scrollwheel: false, zoom: 8 }); 

How do I do this with the Typescript version of Googlemaps I just installed?

Will the Googlemaps Typescript version have all the same methods as the original API? Is there a documentation site in the scripts of popular JS libraries that I can link to?

+5
source share
1 answer

The agm project, denoted by @Steve G., provides a good starting point, but for some reason (for example, to manage your own request policy) you might want to create your own typed wrapper. Here's how I did it with Angular Cli:

First step:

 npm i --save @types/googlemaps 

Second, add types to tsconfig.app.json :

 "types": ["googlemaps"] 

Finally write typescript:

 //nothing to import here //Replace this by anything without an ID_KEY const getScriptSrc = (callbackName) => { return `https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=${callbackName}`; } export class GMapService { private map: google.maps.Map; private geocoder: google.maps.Geocoder; private scriptLoadingPromise: Promise<void>; constructor() { //Loading script this.loadScriptLoadingPromise(); //Loading other components this.onReady().then(() => { this.geocoder = new google.maps.Geocoder(); }); } onReady(): Promise<void> { return this.scriptLoadingPromise; } initMap(mapHtmlElement: HTMLElement, options: google.maps.MapOptions): Promise<google.maps.Map> { return this.onReady().then(() => { return this.map = new google.maps.Map(mapHtmlElement, options); }); } private loadScriptLoadingPromise() { const script = window.document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.defer = true; const callbackName: string = 'UNIQUE_NAME_HERE'; script.src = getScriptSrc(callbackName); this.scriptLoadingPromise = new Promise<void>((resolve: Function, reject: Function) => { (<any>window)[callbackName] = () => { resolve(); }; script.onerror = (error: Event) => { reject(error); }; }); window.document.body.appendChild(script); } /** Exemple of wrapped to promise API */ geocode(address: string | google.maps.GeocoderRequest): Promise<google.maps.GeocoderResult[]> { return this.onReady().then(() => { this.geocoder.geocode(typeof address == "google.maps.GeocoderRequest" ? address: {address: address}, (results: google.maps.GeocoderResult[], status: google.maps.GeocoderStatus) => { if(status == google.maps.GeocoderStatus.OK) { return results; } else { throw new Error(status.toString()); } }); }); }); } 

So, your map component will look like this:

 @Component({ selector: 'app-gmap-wrapper', template: '<div #map style="width:400px; height:300px">loading...</div>' }) export class GMapWrapperComponent implements OnInit { @ViewChild('map') mapRef: ElementRef; constructor(private gmapService: GMapService) { } ngOnInit() { this.gmapService.initMap(this.mapRef.nativeElement, { center: {lat: 1234.1234, lng: 1234.1234}, scrollwheel: true, zoom: 8 }); } } 

This code should be better without the google.maps namespace in the prefix of all types. Maybe any suggestion?

+9
source

Source: https://habr.com/ru/post/1265500/


All Articles