2
function initMap() {
  const map = new google.maps.Map(document.getElementById("map"), {
  zoom: 15,
  center: {lat: 24.149950, lng: 120.638610},
  mapId: '63d22d3ae6cf15ff'
  });

  console.log(getCoordinates("Bouverie Street"));
}

// geocoder
function getCoordinates(address) {
    const geocoder = new google.maps.Geocoder();
  geocoder.geocode({address: address}, (results, status) => {
    if (status === 'OK') {
        return results[0].geometry.location;
    } else {
        alert("Geocode error: " + status);
        console.log(("Geocode error: " + status));
    }
  });
}

On line 9 I'm trying to log the return object from getCoordinates(). However it shows up as undefined for some reason. I think the function works as intended as, if I added "console.log(results);" above the return statement, it logs the result object as intended.

if (status === 'OK') {
        return results[0].geometry.location;
    }

What am I doing wrong? Thanks in advance.

1 Answers1

1

There has occurred an asynchronous issue. To get rid of that(in this case, you're printing latitude and longitude) you can pass a callback parameter when you're calling getCoordinates function.

Here I'm going to use below script for the example:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&callback=initMap" defer></script>

So replace this with your own which will be like this:

<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" defer></script>

So here I'm going to pass a callback parameter to getCoordinates function which will print coordinates passed from getCoordinates in this way:

function initMap() {
    const map = new google.maps.Map(document.getElementById("map"), {
        zoom: 15,
        center: { lat: 24.149950, lng: 120.638610 },
        mapId: '63d22d3ae6cf15ff'
    });

    getCoordinates("Bouverie Street", printLocation);

}

function printLocation(location) {
    console.log("location");
    console.log(location.lat());
    console.log(location.lng());
}

// geocoder
function getCoordinates(address, myCallback) {
    const geocoder = new google.maps.Geocoder();
    geocoder.geocode({ address: address }, (results, status) => {
        if (status === 'OK') {
            myCallback(results[0].geometry.location);
        } else {
            console.warn = () => {}; // stop printing warnings
            console.log(("Geocode error: " + status));
        }
    });
}
#map {
    height: 400px;
    width: 100%;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&callback=initMap" defer></script>
<div id="map"></div>
Shahnawaz Hossan
  • 2,695
  • 2
  • 13
  • 24