我正在使用 Google 地图库制作一个应用程序。我的问题是创建标记时出现无法解释的延迟,或者出现我看不到的异步问题。
解释 :
该代码沿着起点和终点之间的路线获取充电站位置,为获取返回的每个充电站创建 Google 标记(以 Json 格式),并将它们推送到数组中。稍后,它应该使用这些标记(此处未包括)来计算包含中途停留的路线。
问题是它在完成创建标记之前启动计算方法。
为了协调结果,我不会立即获取所有结果。相反,我做了一个循环来执行以下操作:
- 创建一条路线并从中提取编码的多段线(将在 URL 中使用)
- 获取结果
- 创建标记,将它们设置在地图上并将它们推送到数组上
- 登录控制台工作已完成(“EV 标记创建完成”)
然后它启动路线计算过程(这里替换为调用的警报“calculateAndDisplayRoute 方法”)
但实际上,循环完成并登录到控制台,但最后一个标记尚未创建,警报已启动,只有在此之后您才能看到标记出现在地图上。
您可以尝试以下代码片段:https://codepen.io/revilo85k/pen/wvowpab
这是有问题的代码(我必须在代码笔中添加更多代码才能使其正常工作):
chargingPointsMarkers = [];
markerArray = [];
async callbackHandler(startEndPointsArray, calculateAndDisplayRoute): Promise<void> {
await this.setChargingStationsMarkers();
calculateAndDisplayRoute();
}
function calculateAndDisplayRoute() {
alert('calculateAndDisplayRoute method called')
}
async function setChargingStationsMarkers() {
const polylineMarkersArray = await createMarkersArray();
console.log('Polyline Markers created', polylineMarkersArray);
const baseUrl = 'URL REMOVED';
for (let j = 0; j < polylineMarkersArray.length - 1; j++) {
const origin = polylineMarkersArray[j].getPosition();
const destination = polylineMarkersArray[j + 1].getPosition();
const route = await createRoute(origin, destination);
const encodedPolyline = route.overview_polyline;
const queryUrl = baseUrl + '&polyline='+ encodedPolyline + '&distance=50';
await fetch(queryUrl)
.then((response) => response.json())
.then( async (data) => await createChargerPointMarkers(data))
.then (() => {
const k = j + 1;
const l = polylineMarkersArray.length - 1;
if (j === polylineMarkersArray.length - 2) {
console.log('loop ' + k + ' of ' + l);
console.log('EV markers creation finished');
}else{
console.log('loop ' + k + ' of ' + l);
}
});
}
}
async createChargerPointMarkers(jsonChargingPoints): Promise<void> {
// Convert the Json response elements to Google Markers, places them on the Map and pushes them to an array.
for (const item of jsonChargingPoints) {
const LatLng = new google.maps.LatLng(parseFloat(item.AddressInfo.Latitude), parseFloat(item.AddressInfo.Longitude));
const marker = await new google.maps.Marker({
position: LatLng,
map: this.map,
draggable: false,
});
this.markerArray.push(marker);
this.chargingPointsMarkers.push(marker);
}
}
async createRoute(point1, point2): Promise<google.maps.DirectionsRoute> {
// Returns a Google DirectionsRoute object
const directionsService = new google.maps.DirectionsService();
const request = {
origin: point1,
destination: point2,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
return new Promise(resolve => directionsService.route(request,
(result, status) => {
if (status === 'OK') {
resolve(result.routes[0]);
} else {
window.alert('Directions request failed due to ' + status);
}
})
);
}