简体   繁体   中英

Get distance from google maps API in Angular service?

I am trying to run JS version of the google maps API, because the regular API gives me a CORS issue. I am trying to find the distance and time between two destination. How do I get the data back from a service I create?

My service looks like this.

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class GMapsService {

  constructor(private http: Http) { }

  getData() {
    return //the data back.
  }
}

https://jsfiddle.net/65nuyn4b This jsfiddle link shows how to get it done. But this is just plain JS, and I need to run it from a service, so I am confused how to include the script tag which is shown in the link, and how will it return everything back to any component where I will be subscribing to this function. Did I miss anything? I am new to Angular.

if your getData() function returns Observable data, for example return this.http.get("some url"); then you can get the data back in another component:

import {GMapsService} from './serviceFileName';
export class YourComponent {
// inject your service
constructor(private myService: GMapsService) {

}

aFunction() {
this.myService.getData().subscribe((data: any) => {
  //process the returned data;
}, err => {
  console.error('GMapsService getData() fail');
});

}

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