Есть массив адресов. Мне нужно получить координаты этих адресов и отобразить их на карте. Я сделал это через цикл, по одному. Есть ли способ сделать это более элегантно, за 1 запрос?
const arrAddress = ["Avenida Diagonal 161-163, Barcelona, 8018, Spain", "MVia Antonello da Messina 45 Aci Castello, Catania, 95021, Italy" ]
const listCoords = [];
function initMap(){
map = new google.maps.Map(document.getElementById('map'), {});
arrAddress.forEach(item => {
geocodeAddress(item).then(results => {
const lat = results[0].geometry.location.lat();
const lng = results[0].geometry.location.lng();
listCoords.push(new google.maps.LatLng(lat, lng));
createMarker(results[0].geometry.location, map)
if(listCoords.length === arrAddress.length){
const bounds = extendBounds(listCoords);
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
}
})
})
}
function geocodeAddress(address) {
const geocoder = new google.maps.Geocoder();
return new Promise((resolve, reject)=>{
geocoder.geocode({'address': address}, function(results, status) {
if (status === 'OK') {
return resolve(results)
}
});
})
}
function createMarker(position, map){
const marker = new google.maps.Marker({
position: position,
map: map,
});
return marker;
}
function extendBounds(listCoords){
const bounds = new google.maps.LatLngBounds();
listCoords.forEach(item => {
bounds.extend(item)
})
return bounds;
}
Сборка персонального компьютера от Artline: умный выбор для современных пользователей