asyn c функция для геокодирования адреса перед рисованием карты - PullRequest
1 голос
/ 16 июня 2020

Я пытаюсь показать карту Google api места, адрес которого у меня есть.

, поэтому я пытаюсь геокодировать этот адрес для карты, но у меня проблемы с async / обещанием

вот мой код:

function geocode(address) {
            geocoder = new google.maps.Geocoder()
            if (geocoder) {
                 return geocoder.geocode( { 'address': address }, 
                    (results, status) => {
                        if (status == google.maps.GeocoderStatus.OK) {
                            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
                                console.log("geocode : "+ results[0].geometry.location)
                                return(results[0].geometry.location);
                            } else {
                                console.log("GEOCODER: No results found");
                            }
                        } else {
                            console.log("GEOCODER: Geocode was not successful for the following reason: " + status);
                        }
                    }
                ).then( function(result) {return result})
            }
            }   


         const el = $('#map');
            const address = el.data('address');
            const title = el.data('title');
            const geocoded = geocode(address).then( function(result) {return result});
            console.log("map: " + geocoded);
            const position = {lat: geocoded.lat(), lng: geocoded.lng()}

            const map = new google.maps.Map(el[0], {
                center: position,
                zoom: 15,
                zoomControl: true,
                mapTypeControl: false,
                scaleControl: true,
                streetViewControl: true,
                rotateControl: true,
                fullscreenControl: true
            });

            const marker = new google.maps.Marker({
                map: map,
                position: position,
                title: title,
                icon: {
                    url: Images.marker,
                    scaledSize: new google.maps.Size(40, 48),
                }
            });

1 Ответ

2 голосов
/ 16 июня 2020

Вам просто нужно сделать все, что находится внутри then. geocoded будет обещанием вместо желаемого результата, поскольку он асинхронный c и не был разрешен.

function geocode(address) {
  geocoder = new google.maps.Geocoder()
  return new Promise((res, rej) => {
    if (geocoder) {
      geocoder.geocode({ 'address': address },
        (results, status) => {
          if (status == google.maps.GeocoderStatus.OK) {
            if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
              console.log("geocode : " + results[0].geometry.location)
              res(results[0].geometry.location);
            } else {
              console.log("GEOCODER: No results found");
              rej(null);
            }
          } else {
            console.log("GEOCODER: Geocode was not successful for the following reason: " + status);
            rej(null);
          }
        }
      )
    } else {
      rej(null)
    }
  }
  )
}


const el = $("#map");
const address = el.data("address");
const title = el.data("title");

//Do other stuff inside then
geocode(address).then(function (geocoded) {
  console.log("map: " + geocoded);
  const position = { lat: geocoded.lat(), lng: geocoded.lng() };

  const map = new google.maps.Map(el[0], {
    center: position,
    zoom: 15,
    zoomControl: true,
    mapTypeControl: false,
    scaleControl: true,
    streetViewControl: true,
    rotateControl: true,
    fullscreenControl: true,
  });

  const marker = new google.maps.Marker({
    map: map,
    position: position,
    title: title,
    icon: {
      url: Images.marker,
      scaledSize: new google.maps.Size(40, 48),
    },
  });
}).catch(e => {
  console.log(e)
})

Надеюсь, это поможет!

...