简体   繁体   English

获取JSON内容谷歌地图angular2

[英]get json content google maps angular2

this is a link to maps.googleapis.com. 是maps.googleapis.com的链接。 You get JSON information about the latitude and longitude in the url. 您会在网址中获取有关纬度和经度的JSON信息。

I need to read this JSON using Typescript and Angular2. 我需要使用Typescript和Angular2阅读此JSON。

I tried a lot of different google suggestions and (among others) the following code (suggested by angular on this link ): 我尝试了很多其他的google建议,以及(其中包括)以下代码(在此链接上由angular建议):

private extractData(res: Response) {
    let body = res.json();
    return body.data || {};
}
// this is fired when I click on my map, this.lat & this.lng are correctly filled
getLongLatClick($event: any) {
    this.lat = $event.coords.lat;
    this.lng = $event.coords.lng;
    this.url = 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+this.lat+','+this.lng+'';

    console.log(this.http.get(this.url).map(this.extractData));

But when I debug in chrome, the "extractData" methode doesn't run.. It seems that the googleapis link isn't JSON for some reason 但是当我在chrome中调试时,“ extractData”方法无法运行。.出于某种原因,似乎googleapis链接不是JSON

What do I have to do to read the JSON? 我必须怎么做才能读取JSON?

You should create a service that makes the http.get to get the data, similiar to : 您应该创建一个使http.get获得数据的服务类似于

import { Injectable }   from '@angular/core';
import {Headers, Response, Http, RequestOptions}  from "@angular/http";

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class DataService{

  private gmapsUrl: string = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=52.48278022207823,6.15234375';

  constructor(private http: Http) {};

  getAll() {
    return this.http.get(this.gmapsUrl).map((response: Response) => response.json());
  }

}

Cool, now you have a service that gets the data, which is also injectable . 太酷了,现在您有了可以获取数据的服务 ,该服务也是可注入的 You can inject this service into any consumers you wish and consume the data. 您可以将此服务注入到您希望使用的任何使用者中并使用数据。 That is similar to : 这类似于:

import {Component, OnInit, ElementRef}  from '@angular/core';
import {DataService}        from "path";

@Component ({
  moduleId: module.id,
  selector: 'custom',
  templateUrl: //your metadata,
  styleUrls: //your metadata
})

export class ConsumerComponent implements OnInit{

  gmapsData: any = [];      

  constructor(private dataService:Data) {}

  ngOnInit(): void {}

  private loadAllUsers() {
    this.dataService.getAll().subscribe(response=> {
      console.log(response.results); // 
      this.gmapsData = response;
    });

  }

}

Hope this helps -> This should give you a solid starting point. 希望对您有所帮助->这应该为您提供一个坚实的起点。

What I haven't actually checked is the mapping between the response of the dataService.getAll() inside the consumer to the actual component property gmapsData, but you should be able to infer how to store it from the console.log(response); 我实际上尚未检查的是使用者内部 dataService.getAll()的响应到实际组件属性gmapsData之间的映射,但是您应该能够从console.log(response)推断出如何存储它。

You are using the wrong code in your extractData . 您在extractData中使用了错误的代码。 As you can see in the JSON response: 如您在JSON响应中所见:

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "20",
               "short_name" : "20",
               "types" : [ "street_number" ]
            }
    .......

it has results , not data . 它有results ,而不是data

So it should be: 因此应该是:

private extractData(res: Response) {
    let body = res.json();
    return body.results || {};
}

So the following should work fine (using the static url in this example): 因此,以下命令应该可以正常工作(在此示例中使用静态网址):

this.http.get('http://maps.googleapis.com/maps/api/geocode/json?latlng=52.48278022207823,6.15234375')
  .map(this.extractData)
  .subscribe(data => console.log(data))

Remember to always subscribe to get your response. 切记始终subscribe以得到您的回应。 And do consider making a service where you do the http-calls and map and then in your component call that service method and subscribe the results! 并考虑在您进行http调用和map地方提供服务,然后在组件中调用该服务方法并订阅结果!

And it's good to check the network tab and see what the response looks like, and to see if you are getting a response at all. 最好检查一下网络标签,看看响应是什么样的,看看是否能收到响应。

Hope this helps! 希望这可以帮助! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM