我可以用离子3获得我当前的位置吗?

时间:2018-02-04 15:45:07

标签: ionic-framework gps ionic3

这是使用我当前位置获取距离位置的功能

applyHaversine(locations) {

let usersLocation = {
  lat: 40.713744,
  lng: -74.009056
}; // before i have declared lat and lng.. and i want to this lat and lng can be filled by my current location 

locations.map((location) => {

  let placeLocation = {
    lat: location.latitude,
    lng: location.longitude
  };

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

return locations;
}

请提供此lat和lng的解决方案

4 个答案:

答案 0 :(得分:1)

您需要从ionic native安装并导入Geolocation

安装完成后,按以下方式导入:

import { Geolocation } from '@ionic-native/geolocation';

constructor(private geolocation: Geolocation) {
} // Add geolocation to your constructor



//Every time you enter the view, get the current location
//You need to call your logic after your lat and long have been set

ionViewWillEnter() {
   this.geolocation.getCurrentPosition().then((resp) => {
      usersLocation.lat = resp.coords.latitude;
      usersLocation.lng = resp.coords.longitude;
      //Call to your logic HERE
   }).catch((error) => {
      alert(error);
   });
}

答案 1 :(得分:0)

是的,在Ionic 3中,您可以使用一个名为Geolocation的本机插件。

这将是代码:

this.geolocation.getCurrentPosition().then((resp) => {
  usersLocation.lat = resp.coords.latitude;
  usersLocation.lng = resp.coords.longitude;
}).catch((error) => {
 console.log('Error getting location', error);
});

答案 2 :(得分:0)

@ChesterLaborde我非常困惑,我必须放置那些代码...我已经反复试过仍然错误

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


@Injectable()
export class LocationsProvider {

  data: any;

  constructor(public http: Http, public geolocation: Geolocation) {

  }

load() {
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) {

let usersLocation = {
  lat: 40.713744,
  lng: -74.009056
};


locations.map((location) => {

  let placeLocation = {
    lat: location.latitude,
    lng: location.longitude
  };

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

return locations;
}

getDistanceBetweenPoints(start, end, units) {

let earthRadius = {
  miles: 3958.8,
  km: 6371
};

let R = earthRadius[units || 'miles'];
let lat1 = start.lat;
let lon1 = start.lng;
let lat2 = end.lat;
let lon2 = end.lng;

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 
}

toRad(x) {
return x * Math.PI / 180;
  }
}

@ChesterLaborde我必须放置你的代码吗?

答案 3 :(得分:0)

非常简单地使用离子,首先安装cordova gps wrapper,然后将以下代码放在您需要访问位置的页面中:



import { Component } from '@angular/core';
import { NavController, IonicPage, ToastController, ViewController } from 'ionic-angular';
import { Geolocation ,GeolocationOptions ,Geoposition ,PositionError } from '@ionic-native/geolocation'; 


@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  private offlinemode: boolean = false;
  options : GeolocationOptions;
  currentPos : Geoposition;

  constructor(public navCtrl: NavController,
    public singletonProvider: SingletonauthProvider,
    public toastCtrl: ToastController, 
    private geolocation : Geolocation, 

  ) {

  }

  ionViewDidEnter(){
    this.viewCtrl.showBackButton(false);
    this.getUserPosition(); 
  }  

  getUserPosition(){
    this.options = {
        enableHighAccuracy : true
    };

    this.geolocation.getCurrentPosition(this.options).then((pos : Geoposition) => {

        this.currentPos = pos;      
        console.log(pos); // here is your current pos
       

    },(err : PositionError)=>{
        console.log("error : " + err.message);
        this.message("Could not detect your position");

    });
}