Angular 6 如何获取两个位置 AGM 之间的距离

Angular 6 How to Get Distance between two location AGM

我使用此参考 https://www.npmjs.com/package/agm-direction 在两点之间得到 方向 现在我想 get/calculate 距离 两个位置之间的距离,我很困惑该怎么做。

我的模块

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 }
}

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

你需要使用Google几何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);
  }

对于Angular6+

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

npm i -D @types/googlemaps

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

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

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

关于@Abdelsalam Shahlol 评论的注释:

For Angular 6+, you can't do this import {} from '@types/googlemaps'; Instead place this in top (first line) of the TS file. /// /node_modules/@types/googlemaps/index.d.ts"/>

在你的app.module.ts

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

你可以用数学计算直线距离,你不需要使用 Google API 并用尽任何 "credit" 做它。

这是我为 Angular 6+ 编写的 lat/long 到 lat/long 函数:

  asTheCrowFlies(x1: number, y1: number, x2: number, y2: number) {
var result = 0;
const RADIANS: number = 180 / 3.14159265;
const METRES_IN_MILE: number = 1609.34;

if (x1 == x2 && y1 == y2) {
  result = 0;

} else {
  // Calculating Distance between Points
  var lt1 = x1 / RADIANS;
  var lg1 = y1 / RADIANS;
  var lt2 = x2 / RADIANS;
  var lg2 = y2 / RADIANS;

  // radius of earth in miles (3,958.8) * metres in a mile * position on surface of sphere...
  result = (3958.8 * METRES_IN_MILE) * Math.acos(Math.sin(lt1) * Math.sin(lt2) + Math.cos(lt1) * Math.cos(lt2) * Math.cos(lg2 - lg1));
}
return result; }

如果你去掉 "miles to metres" 的倍数,答案就是英里。对于 ROAD 距离,您只需要 Google API,而 AGM 使用的 MAP API 无法做到这一点,您需要来自 Google 的 ROUTE API。我还没有看到 ROUTE API 的 Angular 组件;大多数人只是用 API 调用编写服务。