用户位置与当前位置的距离

时间:2017-01-01 12:38:09

标签: angular google-maps-api-3 ionic2

我是离子2的新用户,这是我的API用户列表,包含纬度和经度。我需要用谷歌地图API显示用户与当前位置的距离吗?如何在ts文件中使用以下地理位置代码?

JSON:

data":[  
      {  
         "id":"1",
         "name":"Adil",
         "latitude":"21.560362",
         "longitude":"39.134023"
      },
      {  
         "id":"2",
         "name":"John",
         "latitude":"22.560212",
         "longitude":"39.133765"
      },
      {  
         "id":"3",
         "name":"Muhammed",
         "latitude":"22.560212",
         "longitude":"39.133765"
      }
   ]

ts档案:

export class AboutPage {

    public items: any;

    constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http, public platform: Platform) {
        this.http = http;
        this.platform = platform;

        this.platform.ready().then(() => {
            this.http.get("PathToMyUsersApiFile").subscribe(data => {
                this.items = JSON.parse(data['_body']).data;
            }, error => {
                console.log(error);
            });

        });

    }

}

HTML:

<ion-list *ngFor="let item of items">
    <ion-item>
        <h2>{{item.name}}</h2>

<!-- distance from current location -->
        <p>{{item.distance}}</p>

    </ion-item>
</ion-list>

地理位置代码:

    Geolocation.getCurrentPosition().then((position) => {

        var currentLocation = {lat: position.coords.latitude, lng: position.coords.longitude};
        var usersLocation = []; // Users location

        var geocoder = new google.maps.Geocoder;
        var service = new google.maps.DistanceMatrixService;         
        service.getDistanceMatrix({
            origins: [origin1],
            destinations: usersLocation,
            travelMode: 'DRIVING',
            unitSystem: google.maps.UnitSystem.METRIC,
            avoidHighways: false,
            avoidTolls: false
        }, function(response, status) {
            if (status !== 'OK') {
                alert('Error was: ' + status);
            } else {
                var results = response.rows[0].elements;
                for (var j = 0; j < results.length; j++) {
                    console.log(results[j].distance.text + ' in ' + results[j].duration.text);
                }
            }
        });

    }, (err) => {
        console.log(err);
    });

1 个答案:

答案 0 :(得分:0)

constructor(private zone: NgZone) {

}

    this.platform.ready().then(() => {
        this.http.get("PathToMyUsersApiFile").subscribe(data => {
            this.items = JSON.parse(data['_body']).data;

Geolocation.getCurrentPosition().then((position) => {

    var currentLocation = {lat: position.coords.latitude, lng: position.coords.longitude};
    var usersLocation = []; // Users location

    var geocoder = new google.maps.Geocoder;
    var service = new google.maps.DistanceMatrixService; 
    service.getDistanceMatrix({
        origins: [origin1],
        destinations: usersLocation,
        travelMode: 'DRIVING',
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, (response, status) => {
        if (status !== 'OK') {
            alert('Error was: ' + status);
        } else {
            var results = response.rows[0].elements;
            this.zone.run(()=>{        
            for (var j = 0; j < results.length; j++) {
                this.items[j].distance=results[j].distance.text
            }
            })
        }
    });

}, (err) => {
    console.log(err);
});

        }, error => {
            console.log(error);
        });

    });

注意事项。

  1. 您没有在代码中设置原点
  2. 注意箭头功能的使用,以便this成为可能。(()=>{}
  3. 有很多方法可以重构代码。比如将逻辑移到service并将ObservablePromiseflatMap
  4. 合并

    希望有所帮助