我正在尝试使用谷歌距离矩阵 API。 https://developers.google.com/maps/documentation/distance-matrix/start 。 我有从当前位置(原点纬度和经度)获取的必要请求参数,当我单击标记时(我得到目的地纬度和经度)。现在我尝试调用服务文件中的API,它无法正常工作。
以下是服务代码: 下面是sendQuery对象中传递的请求参数。
apiKeyToPass: "this will be apikey"
srcDestinationLat: 29.9809683
srcDestinationLng: 31.3377553
srcOriginLat: 11.127122499999999
srcOriginLng: 78.6568942
我传递的是 apikey 来代替 apikey。 如何在下面的 URL 中传递上述 sendQuery 参数,以便获得所需的响应。
getDistanceMatrix(sendQuery): Observable<any> {
return this.http.get('https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins={{srcOriginLat}},{{srcOriginLng}}&destinations={{srcDestinationLat}},{{srcDestinationLng}}&key=apikey')
.map((response: Response) => {
return response.json();
})
.catch(this.handleError);
}
当我执行上面的代码时,代码运行到异常循环而不是进入响应循环。
最佳答案
@agm/core的版本是1.0.0,您还必须安装@types/googlemaps。接下来,您需要导入
import {} from 'googlemaps';
进入你的组件。
您可能会看到如下错误:node_modules/@types/googlemaps/index.d.ts' 不是模块。 要纠正此错误,只需在 src 目录中创建一个名为 index.d.ts 的文件并添加以下行:
declare module 'googlemaps';
要使用距离矩阵服务,请使用组件中的下一个:
public getDistance(origin: LatLng, destination: LatLng) {
const matrix = new google.maps.DistanceMatrixService();
return new Promise((resolve, reject)=>{
matrix.getDistanceMatrix({
origins: [new google.maps.LatLng(origin.lat, origin.lng)],
destinations: [new google.maps.LatLng(destination.lat,destination.lng)],
travelMode: google.maps.TravelMode.DRIVING,
},
function(response, status) {
if (status === 'OK'){
resolve(response)
} else {
reject(response);
}
});
});
}
关于angular - 如何在 Angular 中使用 google 距离矩阵 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52418307/