入门 - 如何使用谷歌地图api与角-cli [英] Getting started - How to use Google maps api with angular-cli

查看:124
本文介绍了入门 - 如何使用谷歌地图api与角-cli的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用ng2。所以我使用angular-cli创建了一个项目,然后我意识到我需要一些第三方模块。比如谷歌地图api,lodash,jquery等等。我知道Typescript的基础知识,但是如何在Angular2应用程序中使用这些模块?此外,我只想使用库,例如​​谷歌地图api,而不是任何现有的谷歌地图api上的其他ng2模块/组件。 - 为了学习。



以前,只有JS,我会包含js文件并引用api文档,以了解引用和构建我的应用的方法。现在有了Angular2,我应该采取什么措施来做同样的事情?



从我的研究看来,我首先安装了所需的类型脚本文件。
因此对于Google地图我做了 npm install --save @ types / google-maps
现在,我是否需要通过将其包含在app.module.ts中将该模块导入到我的角度应用程序中?在进口数组?或者是现在全球可用?



一个来源提到用npm安装它,并在我的angular-cli.json中包括脚本数组中对该库的引用。像这样:

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

在安装google maps api时使用哪种方法?我认为Typescript可能是要走的路,因为Angular应用程序的其余部分将用Typescript编写。



现在在我的app.component.ts中,我想使用我安装的打字稿创建一个简单的地图。我会怎么做?谷歌地图api说,像这样创建一个新的地图实例。

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

我如何使用我刚刚安装的Google地图的打字稿版本来做到这一点?



打印稿版本的Google地图是否具有与原始API完全相同的方法?是否有流行的JS库的打字稿有一个我可以参考的文档站点?

agm 项目指出的@Steve G.给出一个好的起点,但由于某种原因(比如管理你自己的请求策略),你可能想要制作你自己的打包包装。
在这里,我如何用Angular Cli做到这一点:

第一步:

  npm i --save @ types / googlemaps 

其次将这些类型添加到 tsconfig.app.json

 types:[googlemaps ] 

最后编写你的脚本:

  //这里没有任何东西可以导入

//将其替换为没有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;
私有地理编码器:google.maps.Geocoder;
private scriptLoadingPromise:Promise< void> ;;

构造函数(){
//加载脚本
this.loadScriptLoadingPromise();
//加载其他组件
this.onReady()。then(()=> {
this.geocoder = new google.maps.Geocoder();
}) ;
}

onReady():Promise< void> {
返回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); $(< any>窗口)[callbackName] =()=> {resolve((解析:函数,拒绝:函数)=> {
this.scriptLoadingPromise = new Promise& );};

script.onerror =(error:Event)=> {reject(error);};
});
window.document.body.appendChild(script);
}
$ b $ **包装到承诺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结果;
} else {
throw new Error(status.toString());
}
});
});
});




$ p
$ b

所以你的地图组件看起来像这样: p>

  @Component({
selector:'app-gmap-wrapper',
template:'< div #map style =width:400px; height:300px> loading ...< / div>'
})
export class GMapWrapperComponent implements OnInit {
@ViewChild('map ')mapRef:ElementRef;

构造函数(private gmapService:GMapService){}
$ b $ ngOnInit(){
this.gmapService.initMap(this.mapRef.nativeElement,{
center:{lat:1234.1234,lng:1234.1234},
scrollwheel:true,
zoom:8
});




$ b

如果没有名称空间<$ c,这段代码应该更好一些$ c> google.maps 所有类型的前缀。也许有任何建议?


I recently got started with ng2. So I created a project using angular-cli, then I realized I need some third party modules. Such as Google maps api, lodash, jquery...etc. I know the basics of Typescript, but how do I use these modules in an Angular2 app? Also, I want to use just the library, for example Google maps api, not any existing ng2 module/component someone else made ontop of the Google maps api - For the sake of learning.

Previously, with just JS I would include the js file and reference the api documentation to know which methods to reference and build my app. Now with Angular2, what steps should I take to do the same?

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

One source mentioned installing it with npm and in my angular-cli.json including a reference to that library in the scripts array. like so:

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

Which method to use in installing the google maps api? I would think Typescript might be the way to go since the rest of the Angular app is going to be written in Typescript.

Now in my app.component.ts, I want to create a simple map using the typescript I installed. How would I do so? The google maps api says to create a new instance of the map like so.

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

How would I do that with the typescript version of Googlemaps I just installed?

Would a typescript version of Googlemaps have all the same methods as the original API? Do typescripts of popular JS libraries have a documentation site I can reference?

解决方案

The agm project pointed by @Steve G. give a good starting point, but for some reason (like manage your own request policy) you may want to make your own typed wrapper. Here how I did it with Angular Cli :

First step :

npm i --save @types/googlemaps

Secondly add the types to your tsconfig.app.json :

"types": ["googlemaps"]

Finally write your 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());
            }
      });
    });
  });

}

And 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 namespace google.maps in prefix of all types. Maybe any suggestion ?

这篇关于入门 - 如何使用谷歌地图api与角-cli的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆