How can I create service return values of longitude and latitude from json?

139 Views Asked by At

How to create service return values of longitude and latitude from JSON?

I have the following URL:

http://192.168.7.xxx:9200/location/_doc/27737

This URL JSON below:

    {"_index":"location","_type":"_doc","_id":"27737","_version":1,"_seq_no":5577,"_primary_term":1,"found":true,"_source":{"Locid":27737,"GPS1":"25.0173, 121.462","GPS2":"25°01'02.2\"N 121°27'44.8\"E","CompanyID":1005070,"ads":"142 Sec. 1, HsIn Nan Rd cung Ko Dšst, New Taipei City, Taiwan","Crid":75,"con":"Taiwan","Ctid":5894,"Cn":"Zhonghe District","pushdate":"2019-12-26T03:38:20.883"}}  

I need to create service return two values from GPS1:

longitude: 25.0173,
latitude: 121.462

Based on Location Id parameter 27737.

So that I need to create service take location id parameters and return two values of GPS1 25.0173 and 25.0173

getDataService(locationid): Observable<any> {    
     const url = "http://192.168.7.xxx:9200/location/_doc/27737";    
       return this.httpClient.get(`${url} + locationid`);    
   }  

on ngOinInit Event

ngOnInit  
{  
call service here  
}  
2

There are 2 best solutions below

6
Ashish Modi On BEST ANSWER

Let's say you have the json returned in a variable called response. You could simply do

getDataService(locationid): Observable<any> {    
     const url = "http://192.168.7.xxx:9200/location/_doc/27737";    
       return this.httpClient.get(`${url} + locationid`)
          .then(response => {
             const [latitude, longitude] = response._source.GPS1.trim().split(",");
             return {latitude, longitude};
           });
   }  
5
Satvik Daga On

The following code will return an observable containing the latitude and longitude for the given locationId. The locationId needs to be passed in the url as shown below.

import { map } from 'rxjs/operators'; 
getDataService(locationId): Observable<any> {    
     const url = 'http://192.168.7.xxx:9200/location/_doc/' + locationId;    
     return this.httpClient.get(url).pipe(
       map(response => {
         const [longitude, latitude] = response._source.GPS1.split(",");
         return {latitude: latitude.trim(), longitude: longitude.trim()};
       })
     );
}  

Then call the service in ngOnInit and get the location's latitude and longitude.

latitude: number;
longitude: number;
constructor(private service: DataService) {}

ngOnInit() {
  const locationId = '27737';
  this.service.getDataService(locationId).subscribe((location) => {
    this.latitude = Number(location.latitude);
    this.longitude = Number(location.longitude);
  })
}