首页 > 解决方案 > 谷歌地图地理编码器没有给我结果

问题描述

我正在尝试使用 JS 地理编码 API。我收到一个错误:

Failed to load resource: net::ERR_BLOCKED_BY_CLIENT

但是,我的 api 密钥已激活。

我正在尝试以下事情。

在 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>

在 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 始终为 ''。

谢谢

标签: javascripthtmlgoogle-mapsgeocoding

解决方案


你的电话是异步的。您应该移动这部分代码:

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

在传递给geocoder.geocode 它的回调内部应该是这样的

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);
                }
            }
        }
    });
}

推荐阅读