问题
I get Direction between two points using this reference https://www.npmjs.com/package/agm-direction Now I want to get/calculate distance between two location and I'm Confusing how's do it.
In my Module
AgmCoreModule.forRoot({
apiKey: 'My API Key....',
libraries: ['geometry']
})
In my Component
getDirection() {
this.origin = { lat: this.pick_latitude, lng: this.pick_longitude }
this.destination = { lat: this.drop_latitude, lng: this.drop_longitude }
}
My Question : How I get distance between two point when I use above reference to get direction path ? Please give me suggestion ( Google map API etc). I'm using Angular 6
回答1:
You need to use 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);
}
In your app.module.ts
AgmCoreModule.forRoot({
apiKey: 'YOUR API KEY',
libraries: ['geometry']
}),
回答2:
You can do a straight line distance with maths, you don't need to use the Google API and use up any "credit" doing it.
Here's a lat/long to lat/long function I wrote for use in Angular 6+:
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; }
If you take out the "miles to metres" multiple, the answer is in miles. You only need the Google API for ROAD distances and that's not done with the MAP API which AGM uses, instead you need the ROUTE API from Google. I have not yet seen an Angular component for the ROUTE API; most people just write a service with the API calls.
来源:https://stackoverflow.com/questions/52871488/angular-6-how-to-get-distance-between-two-location-agm