未加星标

Angular 2 + Google Maps Places Autocomplete

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二05 | 时间 2016 | 作者 红领巾 ] 0人收藏点击收藏

Angular 2 + Google Maps Places Autocomplete

In this brief tutorial I’ll show you to to quickly build an Angular 2 + Google Maps Places Autocomplete application. The Places Autocomplete by Google Maps is very helpful as it allows a user to search for an address or specific location. I’ll combine the Places Autocomplete API with a Google Map using the angular2-google-map module.

tl;dr

Check out the Plunker: https://plnkr.co/edit/LdKdSj?p=preview

Getting Started

The first thing to do is to install the angular2-google-maps module as well as the googlemaps TypeScript declaration file using Node Package Manager (npm):

$ npm install angular2-google-maps --save
$ npm install @types/googlemaps --save-dev

Next, modify your @NgModule decorator:

import { AgmCoreModule } from "angular2-google-maps/core";
@NgModule({
imports: [
AgmCoreModule.forRoot({
apiKey: "YOUR KEY GOES HERE",
libraries: ["places"]
}),
BrowserModule,
FormsModule,
ReactiveFormsModule
],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule() {}

To review the code above:

First, we import the AgmCoreModule class from the angular2-google-maps/core module. In our @NgModule imports property we use the AgmCoreModule.forRoot() method and specify the places library. You will notice that I am also using ReactiveFormsModule for Angular’s new model-driven forms. Create Template

For this tutorialI am going to set the styles and template properties in my @Component decorator configuration. I would suggest that you have an external Sass file and an external HTML template instead. Let’s take a look at the @Component configuration:

@Component({
selector: 'my-app',
styles: [`
.sebm-google-map-container {
height: 300px;
}
`],
template: `
<div class="container">
<h1>Angular 2 + Google Maps Places Autocomplete</h1>
<div class="form-group">
<input placeholder="search for location" autocorrect="off" autocapitalize="off" spellcheck="off" type="text" class="form-control" #search [formControl]="searchControl">
</div>
<sebm-google-map [latitude]="latitude" [longitude]="longitude" [scrollwheel]="false" [zoom]="zoom">
<sebm-google-map-marker [latitude]="latitude" [longitude]="longitude"></sebm-google-map-marker>
</sebm-google-map>
</div>
`
})
export class App implements OnInit {}

A couple of things to note:

Don’t forgetthat you must define a height for the map element . In this case, I am setting it to 300px. For the template, I am using some minimal Bootstrap CSS styling to make things look nice. My input element uses a local template variable named search . This is declared using the hash symbol ( # ), or I could have used the ref- prefix such as ref-search . My input element has one-way data binding for the FormControl directive to the searchControl publicly available variable in my controller. We’ll look at this in a moment. Next, I am implementing the sebm-google-map directive as per the documentation for the angular2-google-maps module . I am binding the latitude to a public variable in my controller named latitude , and I am doing the same thing for the longitude. I am also setting the scrollwheel optionto false. Then I bind the zoom valueto my zoom property in my controller. I have also included a marker that will use the same longitude and latitude as the center point for the map. Implement Controller

Next, we need to implement our controller. Let’s take a look at it:

import { OnInit, ViewChild } from [email protected]/core';
import { FormControl } from "@angular/forms";
import { MapsAPILoader } from 'angular2-google-maps/core';
export class App implements OnInit {
public latitude: number;
public longitude: number;
public searchControl: FormControl;
public zoom: number;
@ViewChild("search")
public searchElementRef: ElementRef;
constructor(
private mapsAPILoader: MapsAPILoader
) {}
ngOnInit() {
//set google maps defaults
this.zoom = 4;
this.latitude = 39.8282;
this.longitude = -98.5795;
//create search FormControl
this.searchControl = new FormControl();
//set current position
this.setCurrentPosition();
//load Places Autocomplete
this.mapsAPILoader.load().then(() => {
let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
types: ["address"]
});
autocomplete.addListener("place_changed", () => {
//get the place result
let place: google.maps.places.PlaceResult = autocomplete.getPlace();
//set latitude and longitude
this.latitude = place.geometry.location.lat();
this.longitude = place.geometry.location.lng();
});
});
}
private setCurrentPosition() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition((position) => {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
this.zoom = 12;
});
}
}
}

First, I import the necessary classes: OnInit , ViewChild , FormControl and MapsAPILoader .

Inside the classwe first define our public variables to store the latitude , longitude , zoom and our searchControl . Next, I am using the @ ViewChild decorator to get access to the DOM input element. The @ViewChild decorator accepts a single string that is the selector to the element or directive. In this case I am referencing the local template variable #search . It decorates the variable searchElementRef , which is an ElementRef to the search input.

Next, I use dependency injection (DI) to inject the MapsAPILoader dependency. We’ll use this later on in the ngOnInit() method to load the Google Places API. I use the private access notation to make this available privately within my class.

Now, in the ngOnInit() m

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: ReactBootstrapHTMLCSS
分页:12
转载请注明
本文标题:Angular 2 + Google Maps Places Autocomplete
本站链接:http://www.codesec.net/view/484697.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(28)