Stack Exchange
Google maps geocoder doesn't give me results
I am trying to use JS geocoding api. I am getting an error:
Failed to load resource: net::ERR_BLOCKED_BY_CLIENT

However, my api key is activated.
I am trying the following things.
In HTML:
<script src="{% static 'moovit_script.js'%}"></script>

<script src="https://maps.googleapis.com/maps/api/js?key=mykey&libraries=places">
</script>
<div class="mv-wtp" id="mapa_moovit" data-to='' data-from='' data-from-lat-long='' data-lang="es">

    <script>
        set_moovitmap();
    </script>
</div>

In moovit_script.js:

function set_moovitmap() {
    var m = document.getElementById('mapa_moovit');
    const origin = window.opener.origin_ad;

    m.setAttribute("data-from-lat-long", window.opener.origin_coordinates);
    const lat = window.opener.latD;
    const lng = window.opener.lonD;
    const geocoder = new google.maps.Geocoder();

    const latlng = {
        lat: parseFloat(lat),
        lng: parseFloat(lng),
    };
    destination_address = '';
    // window.alert(latlng.lat);
    geocoder.geocode({ location: latlng }, (results, status) => {
        if (status === "OK") {
            if (results[0]) {
                destination_address = results[0].formatted_address;


            }
        }

    });
    window.alert(destination_address);
    m.setAttribute("data-from", origin);
    if (destination_address != '') {
        m.setAttribute("data-to", destination_address);
    }
}

destination_address is '' all times.
Thank you

Your call is async. You should move this part of the code:
window.alert(destination_address);
m.setAttribute("data-from", origin);
if (destination_address != '') {
    m.setAttribute("data-to", destination_address);
}

Inside of the callback passed to geocoder.geocode
It should be something like this
function set_moovitmap() {
    var m = document.getElementById("mapa_moovit");
    const origin = window.opener.origin_ad;

    m.setAttribute("data-from-lat-long", window.opener.origin_coordinates);
    const lat = window.opener.latD;
    const lng = window.opener.lonD;
    const geocoder = new google.maps.Geocoder();

    const latlng = {
        lat: parseFloat(lat),
        lng: parseFloat(lng),
    };

    geocoder.geocode({ location: latlng }, (results, status) => {
        if (status === "OK") {
            if (results[0]) {
                window.alert(destination_address);
                m.setAttribute("data-from", origin);
                if (destination_address != "") {
                    m.setAttribute("data-to", destination_address);
                }
            }
        }
    });
}


It gives me an error Failed to load resource: net::ERR_BLOCKED_BY_CLIENT
