Angular 2 TypeScript使用Google Geocode服务进行HTTP GET请求

4

我是新手Angular2,尝试使用位置来查找坐标(纬度,经度)。

这是我的代码:

GeoService.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
}

app.component.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>

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;
}

如何在 app.component.ts 中获取结果?
 findLocation(): void {
    this.result=  this.geoService.getLocation(this.location);
  }

在您的地理编码URL中,CA参数用于什么?我在文档中找不到它。此外,我发现传感器参数不再需要。 - salsadeanguila
2个回答

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

然后在 app.component.ts 中将其更改为以下内容。

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

我添加了一些错误控制,因为这总是一件好事。并且我在响应中返回了结果数组,以便如果返回超过一个地址,则与用户澄清他们想要哪个地址。


@BrianAllanWest 我从未使用observable构建过这个。在我的实现中,我使用了一个名为findLocation的参数进行一些计算,因此我使用了Promise来获取结果。虽然使用observable也可以,只需删除所有与promise相关的代码并更改Promise.resolve行即可。 - user3700940

2

使用angular 7.1.4 httpclient。getLocation返回observable。

location.service.ts已更名为GeoService.ts

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Observable } from "rxjs";

@Injectable({
  providedIn: "root"
})
export class LocationService {
  constructor(private http: HttpClient) {}

  getLocation(term: string): Observable<any> {
    return this.http.get(
      "http://maps.google.com/maps/api/geocode/json?address=" +
        term +
        "CA&sensor=false&key=API_KEY"
    );
  }
}

location.component.ts

/// <reference types="@types/googlemaps" />
import { Component, OnInit, AfterContentInit, ViewChild } from "@angular/core";
import { LocationService } from "../location.service";

declare let google: any;

@Component({
  selector: "app-location",
  templateUrl: "./location.component.html",
  styleUrls: ["./location.component.scss"],
  providers: [LocationService]
})
export class LocationComponent implements OnInit {
  @ViewChild("gmap") gmapElement: any;
  map: google.maps.Map;

  latitude: number;
  longitude: number;
  marker: google.maps.Marker;

  locationStr: string;
  public result: any;

  countMarkers = 0;

  constructor(public geoService: LocationService) {}

  ngOnInit() {
    this.setCurrentPosition();
    // tslint:disable-next-line:prefer-const
    let mapProp = {
      center: new google.maps.LatLng(0, 0),
      zoom: 18,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      disableDefaultUI: true
    };
    this.map = new google.maps.Map(this.gmapElement.nativeElement, mapProp);
  }

  setCenter(e: any) {
    e.preventDefault();
    this.map.setCenter(new google.maps.LatLng(this.latitude, this.longitude));
  }

  setCurrentPosition() {
    navigator.geolocation.getCurrentPosition(position => {
      console.log("Set position", position.coords);
      this.latitude = position.coords.latitude;
      this.longitude = position.coords.longitude;
      this.map.setCenter(new google.maps.LatLng(this.latitude, this.longitude));

      const location = new google.maps.LatLng(this.latitude, this.longitude);
      this.map.panTo(location);

      if (!this.marker) {
        this.marker = new google.maps.Marker({
          position: location,
          map: this.map,
          draggable: false,
          title: "You Loation!"
        });
        this.marker.setLabel("You");
        this.marker.setMap(this.map);
      } else {
        this.marker.setPosition(location);
      }
    });
  }

  setMarker(label = ".") {
    const location = new google.maps.LatLng(this.latitude, this.longitude);
    this.map.panTo(location);

    if (!this.marker) {
      this.marker = new google.maps.Marker({
        position: location,
        map: this.map,
        draggable: false,
        title: "You Loation!"
      });
      this.marker.setLabel(label);
      this.marker.setMap(this.map);
    } else {
      this.marker.setLabel(label);
      this.marker.setPosition(location);
    }
  }

  addMarker(label = "") {
    const location = new google.maps.LatLng(this.latitude, this.longitude);
    // this.map.panTo(location);

    const newMarker = new google.maps.Marker({
      position: location,
      map: this.map,
      draggable: false,
      title: "You Loation!"
    });
    this.countMarkers++;
    label = this.countMarkers.toString();
    newMarker.setLabel(label);
    newMarker.setMap(this.map);
  }

  findLocation(): void {
    this.geoService
      .getLocation(this.locationStr)
      .subscribe(
        (data: any) => (
          (this.result = data.results[0].geometry.location),
          console.log(data.results[0].geometry.location),
          (this.latitude = data.results[0].geometry.location.lat),
          (this.longitude = data.results[0].geometry.location.lng),
          this.map.setCenter(
            new google.maps.LatLng(this.latitude, this.longitude)
          ),
          this.addMarker()
        ),
        (err: any) => console.log(err),
        () => console.log("All done getting location.")
      );
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接