angular - 如何在 Angular 中使用 google 距离矩阵 API

标签 angular google-maps google-distancematrix-api

我正在尝试使用谷歌距离矩阵 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/

相关文章:

javascript - 为什么自定义事件不需要与 xxx.target.value 一起使用”

javascript - 密码 react 形式的自定义验证器并确认密码匹配将未定义的参数获取到 Angular 4

iOS:Google Maps API - 禁用信息窗口点击事件

android - 无法使用 Google Distance Matrix API Android 将距离变量传递给另一个 Activity

angularjs - Angular 2 获取 JSON 数组中单个条目的值

javascript - 使用 Firestore 查询发送值

Android 替代 iOS Google map API GMSGeometryOffset

php - 如果页面上存在 JavaScript 错误,谷歌地图是否无法加载?

ios - 无法从Google距离矩阵API获得响应

javascript - 使用谷歌距离矩阵 API 计算距离,除了少数几个查询外,几乎所有查询都运行良好