Вернуть координаты адреса в переменную google maps api 3
Пытаюсь получить координаты места через сервис geocoder Вот стандартная функция их документации гугла
function geocode(request) {
clear();
geocoder
.geocode(request)
.then((result) => {
const { results } = result;
map.setCenter(results[0].geometry.location);
marker.setPosition(results[0].geometry.location);
marker.setMap(map);
responseDiv.style.display = "block";
response.innerText = JSON.stringify(result, null, 2);
return results;
})
.catch((e) => {
alert("Geocode was not successful for the following reason: " + e);
});
}
Вот мой код
function initMap() {
var toAddress = "$toaddr";
const center_region = new google.maps.LatLng($center_map);
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
const geocoder = new google.maps.Geocoder();
const map = new google.maps.Map(document.getElementById("map"), {
zoom: $zoom_map,
center: center_region,
});
directionsRenderer.setMap(map);
var newCoord = geocode(geocoder, { address: toAddress });
console.log(newCoord);
}
function geocode(geocoder, request) {
geocoder.geocode(request)
.then((result) => {
const { results } = result;
return results[0].geometry.location;
})
.catch((e) => {
console.log("Geocode was not successful for the following reason: " + e);
});
}
Почему в переменной newCoord underfined. Если выводить значения в самой функции geocode то все работает, но не пойму почему результат работы функции underfined. Документация https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple?hl=ru#maps_geocoding_simple-javascript