简体   繁体   中英

get json content google maps angular2

this is a link to maps.googleapis.com. You get JSON information about the latitude and longitude in the url.

I need to read this JSON using Typescript and Angular2.

I tried a lot of different google suggestions and (among others) the following code (suggested by angular on this link ):

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

What do I have to do to read the JSON?

You should create a service that makes the http.get to get the data, similiar to :

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

You are using the wrong code in your extractData . As you can see in the JSON response:

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

it has results , not 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. 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!

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! :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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