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

时间:2018-10-18 09:56:36

标签: angular google-maps distance

使用此引用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 }
}

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

2 个答案:

答案 0 :(得分:4)

您需要使用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);
  }

在您的app.module.ts

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

答案 1 :(得分:0)

您可以使用数学进行直线距离运算,而无需使用Google API并用尽任何“学分”。

这是我在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; }

如果您将“英里转换为米”,则答案是以英里为单位。您只需要Google API即可获得ROAD距离,而AGM使用的MAP API则无法做到这一点,相反,您需要Google的ROUTE API。我还没有看到ROUTE API的Angular组件;大多数人只是使用API​​调用编写服务。