简体   繁体   中英

How to use google Distance matrix API in Angular

I am trying to use the google Distance Matrix API. https://developers.google.com/maps/documentation/distance-matrix/start . I have the necessary request parameters that are got from current location(origin lat&lng) and when i click on marker( I get the destination lat&lng). Now I am trying to call the API in service file, it doesnt work properly.

Below is the service code: Below is the request parameters passed in sendQuery object.

apiKeyToPass: "this will be apikey"
srcDestinationLat: 29.9809683
srcDestinationLng: 31.3377553
srcOriginLat: 11.127122499999999
srcOriginLng: 78.6568942

In place of apikey I am passing the apikey. How to pass the above sendQuery parameters in the below URL so that I get the desired response.

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

When i execute the above code, the code runs into exceptions loop instead of entering into response loop.

The version of @agm/core is 1.0.0, You also have to install @types/googlemaps. Next, you need to import

import {} from 'googlemaps'; 

into your component.

You will probably see an error like: node_modules/@types/googlemaps/index.d.ts' is not a module. To correct this error, simply create a file called index.d.ts in the src directory and put the following line:

declare module 'googlemaps'; 

To use distance matrix service use the next in your component:

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

}

this work for me:

public getDistancia(origen: string, destino: string) {
    return new google.maps.DistanceMatrixService().getDistanceMatrix({'origins': [origen], 'destinations': [destino], travelMode: 'DRIVING'}, (results: any) => {
        console.log('resultados distancia (mts) -- ', results.rows[0].elements[0].distance.value)
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM