javascript - 谷歌地图地理编码器没有给我结果
问题描述
我正在尝试使用 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 始终为 ''。
谢谢
解决方案
你的电话是异步的。您应该移动这部分代码:
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);
}
}
}
});
}
推荐阅读
- fortran - 由 OMP 私有参数引起的崩溃
- javascript - 删除 node_module 文件夹和运行 npm uninstall 之间的区别
- javafx - JavaFX 嵌入式表 FXML 给出空指针异常
- android - 不能使用“int”或“Integer”?
- c - 将大端转换为中小端
- python - 使用一个 int 项创建 python 元组
- gpgpu - 您可以使用 Apple 的 Metal 进行通用 GPU 编程吗?
- cmake - 使用 CMake 的 Libpqxx 未定义引用
- discord - 如何让机器人更有效地回应提及
- wolfram-mathematica - 我将如何修改我的mathematica 模块以检测n 次多项式的所有最小值?