我正在使用google.maps.geocoder在我的angular应用程序中的一个modal组件上获取一个位置请求。问题是,当我发出请求并从中获取位置时,要在我的UI上显示标记,它并没有显示得那么快。请求立即发生,但我必须等待15-20秒,直到位置显示在我的UI上。如果我在这15秒之前单击组件上的任何位置,那么标记就会在我单击时立即显示,在此之后,如果我发出更多的位置请求,它就会立即显示它们。所以只有第一次我必须等待几秒钟,我的UI才会显示更改。请帮助我理解为什么会发生这种情况以及如何解决它。
下面是地理编码器请求函数:
googleMapsFindLocation() {
const address = this.locationName;
let geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, (results, status) => {
if (status == 'OK') {
const mapCustomObj = new MapCustomObj();
const marker = {
position: { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() },
info:
'<h2>' + results[0].formatted_address + '</h2></br>'
};
mapCustomObj.marker = marker;
this.location.name = results[0].formatted_address;
this.showOnMap(mapCustomObj, results[0].geometry.viewport);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
对于显示,我使用的是angular google maps组件[https://github.com/angular/components]
简单的解决方案是使用
geocoder.geocode({ 'address': address }, (results, status) => {
setTimeout(() => {
if (status == 'OK') {
const mapCustomObj = new MapCustomObj();
const marker = {
position: { lat: results[0].geometry.location.lat(), lng: results[0].geometry.location.lng() },
info:
'<h2>' + results[0].formatted_address + '</h2></br>'
};
mapCustomObj.marker = marker;
this.location.name = results[0].formatted_address;
this.showOnMap(mapCustomObj, results[0].geometry.viewport);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
}, 0);
});