带有 TypeScript 谷歌地理编码服务的 Angular 2 HTTP GET

Saj*_*ran 4 google-maps geocoding angular

我是 angular2 的新手,并试图使用该位置找到坐标(纬度,经度)。

这是我的代码,

地理服务.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class GeoService {
    constructor(private http: Http) { }
    getLocation(term: string) {
       return this.http.get('http://maps.google.com/maps/api/geocode/json?address=' + term + 'CA&sensor=false').map
       ((response) => response.json());
    }
// tslint:disable-next-line:eofline
}
Run Code Online (Sandbox Code Playgroud)

应用程序组件.html

<!DOCTYPE  HTML>
<h1> {{title}} </h1>
 <input type="text" [(ngModel)]="location" />
<button (click)="findLocation($event)">Find location</button>   
 <sebm-google-map 
      [latitude]="lat"
      [longitude]="lng"
      [zoom]="zoom"
      [disableDefaultUI]="false"
      [zoomControl]="false"
      (mapClick)="mapClicked($event)">
     <sebm-google-map-marker
          *ngFor="let m of markers; let i = index"
          (markerClick)="clickedMarker(m.label, i)"
          [latitude]="m.lat"
          [longitude]="m.lng"
          [label]="m.label"
          [markerDraggable]="m.draggable"
          (dragEnd)="markerDragEnd(m, $event)">
         <sebm-google-map-info-window>
          <strong>InfoWindow content</strong>
        </sebm-google-map-info-window>
      </sebm-google-map-marker>
      <sebm-google-map-circle [latitude]="lat + 0.3" [longitude]="lng" 
          [radius]="5000"
          [fillColor]="'red'"
          [circleDraggable]="true"
          [editable]="true">
      </sebm-google-map-circle>
</sebm-google-map>
Run Code Online (Sandbox Code Playgroud)

app.component.ts

import { Component } from '@angular/core';
import { GeoService } from './GeoService';

@Component({
  selector: 'my-app',
  moduleId: module.id,
  templateUrl: `./app.component.html`,
  styleUrls: ['/app.componenet.css'],
  providers :[GeoService]
})
export class AppComponent {
  title = 'Angular2 google map test';
  lat: number = 51.673858;
  lng: number = 7.815982;
  zoom: number = 8;

  markers: marker[] = [
    {
      lat: 51.673858,
      lng: 7.815982,
      label: 'A',
      draggable: true
    },
    {
      lat: 51.373858,
      lng: 7.215982,
      label: 'B',
      draggable: false
    },
    {
      lat: 51.723858,
      lng: 7.895982,
      label: 'C',
      draggable: true
    }
  ];

  location: string;

  findLocation(): void {
    this.result=  this.geoService.getLocation(this.location);
  }
  constructor(private geoService: GeoService) {
  }
  clickedMarker(label: string, index: number) {
  }
  mapClicked($event: MouseEvent) {
  }
  markerDragEnd(m: marker, $event: MouseEvent) {
    console.log('dragEnd', m, $event);
  }

}
// tslint:disable-next-line:class-name
interface marker {
  lat: number;
  lng: number;
  label?: string;
  draggable: boolean;
}
Run Code Online (Sandbox Code Playgroud)

如何在 app.component.ts 中获取结果?

 findLocation(): void {
    this.result=  this.geoService.getLocation(this.location);
  }
Run Code Online (Sandbox Code Playgroud)

小智 5

希望你不会仍然停留在这个问题上。虽然这可能不再对您有帮助,但希望它会对其他人有所帮助。这是我刚才所做的。首先将 getLocation 函数更改为此。这是针对当前的 Angular2 版本。

getLocation(term: string):Promise<any> {
   return this.http.get('http://maps.google.com/maps/api/geocode/json?address=' + term + 'CA&sensor=false')
        .toPromise()
        .then((response) => Promise.resolve(response.json()));
        .catch((error) => Promise.resolve(error.json()));
}
Run Code Online (Sandbox Code Playgroud)

然后在 app.component.ts 中,将其更改为这个。

findLocation(): void {
    this.geoService.getLocation(this.location)
        .then((response) => this.result = response.results[0])
        .catch((error) => console.error(error));
}
Run Code Online (Sandbox Code Playgroud)

我添加了一些错误控制,因为这总是很好。我在响应中返回了一个结果数组,因此如果返回的地址不止一个,请向用户说明他们想要哪个地址。