【问题标题】:How to get place details from gmaps api. jsonp error如何从 gmaps api 获取地点详细信息。 jsonp错误
【发布时间】:2018-07-25 00:38:22
【问题描述】:

https://developers.google.com/places/web-service/details

我收到 CORS 错误。好的,我尝试在角度中使用 jsonp 并得到另一个错误。

Uncaught SyntaxError: Unexpected token :

我认为是因为 gmaps api 不支持 jsonp。 Querying Google Places API using jQuery

但是如何通过angular从 API 获取地点详细信息?

代码

const params = new URLSearchParams();
params.append('key', 'MYAPIKEY');
params.append('placeid', placeId);
params.append('callback', 'JSONP_CALLBACK');
const url = 'https://maps.googleapis.com/maps/api/place/details/json';
return this.jsonp.get(url, {search: params});

getPlaceDetails(placeId: string) {
const httpParams = new HttpParams()
    .append('key', 'MYAPIKEY')
    .append('placeid', placeId);

const url = 'https://maps.googleapis.com/maps/api/place/details/json';
return this.http.get<PlaceDetail>(url, {params: httpParams}).map(c => c.result);
}

如果我使用 cors chrome 扩展,第二种方法有效

【问题讨论】:

    标签: javascript angular google-maps typescript jsonp


    【解决方案1】:

    如果你使用新的 Http Client,试试这个:

    return this.http.get<PlaceDetail>(url, {params: httpParams, observe: 'response'}).map(c => {
      console.log(c);
      return c.result;
    });
    

    这将允许您查看包含在 _body 字段中的响应,并从中执行一些操作。

    【讨论】:

    • 我会得到No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:5555' is therefore not allowed access.
    • 然后解决您的 CORS 问题。 A lot of SOF questions are about that.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 1970-01-01
    • 1970-01-01
    • 2012-12-26
    • 2012-06-20
    • 2016-03-20
    • 2014-10-15
    相关资源
    最近更新 更多