我正在使用离子2 /角度2和谷歌地图。
我有一个班级
import {Page, Platform} from 'ionic-angular';
import {Geolocation} from 'ionic-native';
import {Http, Response} from '@angular/http';
@Page({
templateUrl: 'build/pages/mapPage/mapPage.html',
})
export class MapPage {
date: String = new Date().toISOString();
address: any = 'Pick a place';
constructor(private platform: Platform, private http: Http) {
this.platform = platform;
this.initializeMap();
}
initializeMap() {
let HTTPP = this.http;
this.platform.ready().then(() => {
var myLatLng = {};
var image = 'custom/img/map-marker-small.png';
Geolocation.getCurrentPosition().then(pos => {
myLatLng = { lat: pos.coords.latitude, lng: pos.coords.longitude };
})
.then(() => {
var minZoomLevel = 17;
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: minZoomLevel,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
});
var getAddress = function (lat, lng) {
let mapUrl = 'https://maps.googleapis.com/maps/api/geocode/json?latlng=' + lat + ',' + lng + '&key=XXXXXXXXX'; // URL to web API
let address = "";
return HTTPP.get(mapUrl)
.toPromise()
.then(data => {
let data2 = data.json().results;
data2[0]['address_components'].forEach(add => {
address += add.long_name + ", ";
});
return address;
});
}
marker.addListener('dragend', function (event) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
console.log("lat: " + lat + ", lng: " + lng);
getAddress(lat, lng)
.then(function(address){
console.log(address); //WORKS CORRECTLY
//but can't access `this` here.
//this.address = address //THIS IS WHAT I WANT
return address;
})
});
});
}
}
我想要完成的是获取已拖动到坐标的标记的地址并将其显示给前端的用户
<ion-navbar *navbar>
<ion-title>
Map Example
</ion-title>
</ion-navbar>
<ion-content class="home">
<div id="map_canvas" style="height: 60%"></div>
<ion-item>
<ion-label>Date</ion-label>
<ion-datetime displayFormat="DDD MMM DD, h:mm A" pickerFormat="DDD DD MMM h mm A" [(ngModel)]="date"></ion-datetime>
</ion-item>
<ion-item>
{{address}}
</ion-item>
</ion-content>
拖动标记后,我已成功获取坐标并成功获取地址字符串。但是this
运算符在标记的dragend事件的事件侦听器函数中不可用。
我如何将this.address
等同于我在事件监听器中的地址?
我试图通过this
对let self = this;
进行一般性的参考,然后在函数中使用self.address = address
,希望它能反映在视图中。但它没有用。
我想要做的就是当用户将标记拖动到新位置时在前端显示地址。
任何帮助将不胜感激!!
答案 0 :(得分:3)
更改
function (event) {
到
(event) => {
保留this
另见https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Functions/Arrow_functions
答案 1 :(得分:2)
有两个地方丢失了上下文:dragend
事件处理程序和then
回调函数。对它们使用箭头函数,这将保留词法范围:
marker.addListener('dragend', event => {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
getAddress(lat, lng)
.then(address => this.address = address);
});