我使用的是使用角2的反向地理编码,它工作得很好,但我无法使用服务(setter和getter)设置值(即城市名称)。
import { ShareService } from './services/ShareService';
class ConferenceApp {
constructor(public shareService: ShareService){
this.getGeoLocation();
}
public getGeoLocation(){
if (navigator.geolocation) {
var options = {
enableHighAccuracy: true
};
navigator.geolocation.getCurrentPosition(position=> {
this.lat = position.coords.latitude;
this.long = position.coords.longitude;
let geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(this.lat, this.long);
let request = {
latLng: latlng
};
geocoder.geocode(request, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0] != null) {
let city = results[0].address_components[results[0].address_components.length-4].short_name;
this.shareService.setLocationDetails(city);
} else {
alert("No address available");
}
}
});
}, error => {
console.log(error);
}, options);
}
}
}如果我试图设置使用服务,this.shareService.setLocationDetails(city);我是错误地说,
app.ts:303 Uncaught TypeError: Cannot read property 'shareService' of undefined服务:
locationObj: any;
setLocationDetails(locationObj){
this.locationObj = locationObj;
}
getLocationDetails(){
return this.locationObj;
}发布于 2016-10-08 05:11:06
我觉得一切都很好。但是,我建议您使用arrowfunction**()=>**,如下所示,
// Removed function keyword and added arrow function
geocoder.geocode(request, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0] != null) {
let city = results[0].address_components[results[0]
.address_components.length-4].short_name;
this.shareService.setLocationDetails(city);
} else {
alert("No address available");
}
}
});发布于 2018-05-08 12:46:54
geocoder.geocode(request,(结果,status) => {.}在“ results ”上显示了一个错误,说明{'latLng‘:latlng}与结果类型不对应。
解决方案:
var geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(this.eventLat, this.eventLng);
let request = {
location: latlng
};
geocoder.geocode(request, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
console.log(results[1].formatted_address);
} else {
console.log('Location not found');
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});发布于 2019-06-13 19:02:47
我没有足够的声誉来评论:-(所以我将回答Usman Iqbal的问题作为一个答案。也许一些管理员可以将其转换为评论。
隐式回调函数创建一个名为闭包的结构:一个包含实际函数及其创建上下文的对象。该上下文包含函数创建时“围绕”回调的所有变量及其值。闭包不包含上下文的this值,因为它本身就是一个对象,在执行回调时具有自己的this。
为了使创建上下文的this直接可用,箭头按照定义处理this,使其不是闭包的this,而是创建上下文的this。如果没有箭头函数,您可以通过显式地将周围的this复制到闭包的上下文中来实现相同的目标:
let self = this; // this of the creation context
geocoder.geocode(request, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0] != null) {
...
// access the surrounding this via self
self.shareService.setLocationDetails(city);
}
...
}
});https://stackoverflow.com/questions/39928472
复制相似问题