首页 > 解决方案 > 在 JavaScript 中从 Geocoding Google-Api 向表中添加地址

问题描述

我正在尝试制作家长控制系统,该系统允许家长在 WebService 中跟踪他的孩子位置历史记录。

我有将位置发送到 Google Firebase 中的实时数据库的移动应用程序。这个位置(纬度和经度)从 Firebase 发送到我的 Javascript 代码,我想将它们放在我的 HTML 中的表格中。我不想把经度和纬度放在表中,但我想根据这个位置保存地址。这就是我使用 Google Geolocations API 的原因。问题是,当我在要放入表中的变量中设置此地址时,此变量似乎未定义。我认为这个变量的范围可能有问题,但我无法管理。在此先感谢您的帮助。我把我的JS代码放在下面:

var longitude;
var latitude;
var address;

//GETING DATA FROM FIREBASE
$(document).ready(function(){
    var rootRef = firebase.database().ref().child("locations");
    rootRef.on("child_added", snap => {
        time = snap.child("time").val();
        longitude = snap.child("longitude").val();
        latitude = snap.child("latitude").val();

        latitude = parseFloat(latitude);
        longitude = parseFloat(longitude);

        //CONVERTING LATITUDE AND LONGITUDE INTO ADDRESS

        var geocoder = new google.maps.Geocoder();
        var location = new google.maps.LatLng(latitude, longitude);
        geocoder.geocode({'latLng': location}, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                address = results[0].formatted_address;
                //HERE ADDRESS IS DISPLAYING GOOD
            }
        });

        //PUT ADDRESS INTO TABLE (THERE IS PROBLEM - ADDRESS IS Undefined)

        $("#table_body").append("<tr><td>" + time + "</td><td>" + address + "</td><td>");
    })
})

标签: javascriptgoogle-mapsgoogle-maps-api-3

解决方案


尝试jQuery.append()在条件表达式内部移动:

coder.geocode({'latLng': location}, function (results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    var tempAddress = results[0].formatted_address;
    $("#table_body").append("<tr><td>" + time + "</td><td>" + tempAddress + "</td><td>");
  }
});

推荐阅读