使用“position.coords.latitude”试图获取当前位置时,我得到了未定义

Posted

技术标签:

【中文标题】使用“position.coords.latitude”试图获取当前位置时,我得到了未定义【英文标题】:I get undefined when using "position.coords.latitude" to trying to get the current poistion 【发布时间】:2017-11-15 10:22:22 【问题描述】:

我是 Ionic2 的新手,我已经按照本教程进行操作,它运行良好 https://www.joshmorony.com/create-a-nearby-places-list-with-google-maps-in-ionic-2-part-1/,它列出了一些地方,然后计算这些地方与给定硬编码的地方之间的距离,我想要实现的是使用当前位置而不是代码中给出的位置,这是我到目前为止所取得的成就的屏幕截图screenshot of my application 这是我的位置提供者:

import  Injectable  from '@angular/core';
import  Http  from '@angular/http';
import 'rxjs/add/operator/map';
import Geolocation from '@ionic-native/geolocation';

/*
  Generated class for the LocationsProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class LocationsProvider 

    data: any;
    Currentlatitude: any;
    Currentlongitude: any;
   

    constructor(public http: Http, public geolocation: Geolocation) 
        console.log('Hello LocationsProvider Provider'); 
    

    load()     
        this.geolocation.watchPosition().subscribe((position) => 
            this.Currentlatitude = position.coords.latitude;
            this.Currentlongitude = position.coords.longitude;                 
        );

        if(this.data)
            return Promise.resolve(this.data);
        
 
        return new Promise(resolve =>      
            this.http.get('assets/data/locations.json').map(res => res.json()).subscribe(data =>      
                this.data = this.applyHaversine(data.locations);     
                this.data.sort((locationA, locationB) => 
                    return locationA.distance - locationB.distance;
                );     
                resolve(this.data);
            );     
        );     
    
 
    applyHaversine(locations)
    // this must change according to the device location
    /*

        let usersLocation = 
            lat: 40.713744, 
            lng: -74.009056
        ;  */

        console.log("this.Currentlatitude ",this.Currentlatitude);
 
        let usersLocation = 
            latitude: this.Currentlatitude,
            longitude: this.Currentlongitude
        ;

        console.log("usersLocation.latitude ",usersLocation.latitude);
        locations.map((location) => 
            let placeLocation = 
                latitude: location.latitude,
                longitude: location.longitude
            ;

            location.distance = this.getDistanceBetweenPoints(usersLocation, placeLocation, 'km').toFixed(2);               
        );

        return locations;
    
 
    getDistanceBetweenPoints(start, end, units)     
        let earthRadius = 
            miles: 3958.8,
            km: 6371
        ;
 
        let R = earthRadius[units || 'km'];
         
        let lat1 = start.latitude;
        
        let lon1 = start.longitude;
      
        let lat2 = end.latitude;
         
        let lon2 = end.longitude;
        console.log("lon1 ",lat1); // here it gives me undefined

        let dLat = this.toRad((lat2 - lat1));
         
        let dLon = this.toRad((lon2 - lon1));
         
        let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(this.toRad(lat1)) * Math.cos(this.toRad(lat2)) *
        Math.sin(dLon / 2) *
        Math.sin(dLon / 2);
        
        let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        let d = R * c;
         
        return d;     
    
 
    toRad(x)            
        return x * Math.PI / 180;
         

【问题讨论】:

【参考方案1】:

我想通了,我的问题是我在 Ionic 中使用 Promises 和 Observables 时不了解同步和异步任务,对于那些有同样问题的人,我建议本教程解释 https://www.joshmorony.com/dealing-with-asynchronous-code-in-ionic/ 。 至于我的程序的解决方案,我在这个问题Get current position in ionic2找到了解决方案@

【讨论】:

【参考方案2】:

我最近为我的应用程序制作了定位服务。我使用地理定位插件来获取我的当前位置,并使用谷歌地图中的distancematrix api 来获取地址(坐标或普通地址)之间的距离/时间

import  Query  from '../models/query';
import  Injectable  from '@angular/core';
import  Http  from '@angular/http';
import 'rxjs/add/operator/map';
import  Geolocation, Geoposition, Coordinates  from '@ionic-native/geolocation';
import  NativeGeocoder, NativeGeocoderReverseResult, NativeGeocoderForwardResult  from '@ionic-native/native-geocoder';

@Injectable()
export class LocationService 

  google_API_KEY: string = 'API_KEY_FROM_GOOGLE_GOES_HERE';
  currentLocation: Geoposition;

  constructor(public http: Http, private geolocation: Geolocation,
    private geocoder: NativeGeocoder) 
    // Set your current location here, or remove this and set it manually throughout the app
    this.setCurrentLocation();
  


  setCurrentLocation() 
    return this.geolocation.getCurrentPosition().then((resp) => 
      // Manipulate resp here if needed
      this.currentLocation = resp;
      console.log(JSON.stringify(this.currentLocation));
    ).catch((error) => 
      console.log('Error getting location', error);
    )
  

  getBetweenCoordsDetails(fromString: string, toString: string) 
    let query = new Query('https://maps.googleapis.com/maps/api/distancematrix/json');
    query.add('key', this.google_API_KEY);
    query.add('destinations', toString);
    query.add('origins', fromString);
    query.add('units', 'imperial');
    return this.http.get(query.toQuery())
      .do(resp => 
        let x = resp;
      , error => 
        let x = error;
      )

  

  getBetweenCoordAndHereDetails(toString: string) 
    let x = this.currentLocation.coords;
    return this.getBetweenCoordsDetails(this.currentLocation.coords.latitude + ',' + this.currentLocation.coords.longitude, toString);
  

  getCoordinatesFromAddress(address: string) 
    return this.geocoder.forwardGeocode(address);
  


【讨论】:

感谢您的回复,我会测试一下,然后标记您的答案。我的问候 我注意到您正在使用一个名为“查询”的模型,您能否提供示例代码,非常感谢

以上是关于使用“position.coords.latitude”试图获取当前位置时,我得到了未定义的主要内容,如果未能解决你的问题,请参考以下文章

第一篇 用于测试使用

在使用加载数据流步骤的猪中,使用(使用 PigStorage)和不使用它有啥区别?

今目标使用教程 今目标任务使用篇

Qt静态编译时使用OpenSSL有三种方式(不使用,动态使用,静态使用,默认是动态使用)

MySQL db 在按日期排序时使用“使用位置;使用临时;使用文件排序”

使用“使用严格”作为“使用强”的备份