在谷歌地图上工作,能够显示地图,我想显示当前位置但不显示
export class AppComponent {
title = '';
ngOnInit() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
console.log(p.coords.latitude);
console.log(p.coords.longitude);
var geocoder = new google.maps.Geocoder();
if (geocoder) {
geocoder.geocode({ 'latLng': LatLng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
this.title = results[0].formatted_address;
console.log(this.title);
}
else {
console.log("Geocoding failed: " + status);
}
});
}
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
}
在这里“this.title”,我正在获取当前位置
HTML代码
<h1> The Title is: {{title}}</h1>
在控制台中我可以看到标题值,为什么它没有绑定在 html 中?
您正在使用变量title
声明范围内AppComponent
类,在回调函数的作用域里面geocode
。您必须使用其原始范围来访问标题。
诀窍是存储this
到一个变量中,在本例中是范围应用组件
export class AppComponent {
title = '';
var self = this;
......
}
然后在任何回调函数中使用它。在你的例子中,它是里面的回调函数geocode call
geocoder.geocode({ 'latLng': LatLng}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results[0].formatted_address);
self.title = results[0].formatted_address; //Here we are using self, as the original context of title
console.log(this.title);
}
else {
console.log("Geocoding failed: " + status);
}
});
另一个问题中也提供了答案this 变为 null https://stackoverflow.com/a/47766040/8438534
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)