首页 > 解决方案 > Angular 6如何获取两个位置AGM之间的距离

问题描述

我使用此参考https://www.npmjs.com/package/agm-direction获得两点之间的方向 现在我想获取/计算两个位置之间的距离,但我很困惑如何做到这一点。

我的模块中

AgmCoreModule.forRoot({
  apiKey: 'My API Key....',
  libraries: ['geometry']
})

我的组件中

getDirection() {
   this.origin = { lat: this.pick_latitude, lng: this.pick_longitude }
   this.destination = { lat: this.drop_latitude, lng: this.drop_longitude }
}

我的问题:当我使用上述参考来获取方向路径时,如何获得两点之间的距离?请给我建议(谷歌地图 API 等)。我正在使用 Angular 6

标签: angulargoogle-mapsdistance

解决方案


您需要使用 Google Geometry API

https://developers.google.com/maps/documentation/javascript/geometry

import {} from '@types/googlemaps';
import { AgmCoreModule, MapsAPILoader } from "@agm/core";

calculateDistance() {
    const mexicoCity = new google.maps.LatLng(19.432608, -99.133209.);
    const jacksonville = new google.maps.LatLng(40.730610, -73.935242.);
    const distance = google.maps.geometry.spherical.computeDistanceBetween(nyc, london);
  }

对于 Angular 6+

要添加的类型允许 Angular 使用 Google 地图类型。在您的终端运行:

npm i -D @types/googlemaps

是时候告诉 Angular 我们已经准备好使用 Google 地图类型了。打开您的 tsconfig.app.jsontsconfig.spec.json并将 googlemaps 添加到 compilerOptions 对象内的 types 数组。

注意:我只把它放在tsconfig.app.json一些人遇到问题的文件中,并且必须将它添加到我上面提到的两个文件中。

   "compilerOptions": {
    "outDir": "./out-tsc/app",
    "types": ["googlemaps"]
   },

或者

注意@Abdelsalam Shahlol 评论:

对于 Angular 6+,你不能这样做 import {} from '@types/googlemaps'; 而是将其放在 TS 文件的顶部(第一行)。/// /node_modules/@types/googlemaps/index.d.ts"/>

在你的 app.module.ts

AgmCoreModule.forRoot({
  apiKey: 'YOUR API KEY',
  libraries: ['geometry']
}),

推荐阅读