首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JavaScript中通过地理编码Google-Api将地址添加到表中

在JavaScript中通过地理编码Google-Api将地址添加到表中
EN

Stack Overflow用户
提问于 2019-05-14 06:34:57
回答 2查看 226关注 0票数 1

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

我有移动应用程序,发送位置到实时数据库在谷歌Firebase。这些位置(纬度和经度)从Firebase发送到我的Javascript代码,在那里我想将它们放到HTML中的一个表中。我不想把经度和纬度放到表中,但是我想保存基于这个位置的地址。这就是我使用Google地理定位API的原因。问题是,当我在想要放入表中的变量中设置此地址时,此变量似乎是未定义的。我认为这个变量的作用域可能有问题,但我不能处理这个问题。提前感谢您的帮助。我把我的JS代码放在下面:

代码语言:javascript
复制
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>");
    })
})
EN

回答 2

Stack Overflow用户

发布于 2019-05-14 07:02:13

尝试将jQuery.append()移动到条件表达式中:

代码语言:javascript
复制
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>");
  }
});
票数 1
EN

Stack Overflow用户

发布于 2019-05-15 02:29:56

地理编码器是异步的。当数据可用时,需要在回调函数中使用数据。如果你想在回调例程中使用循环变量,你需要用函数闭包来捕获它们:

代码语言:javascript
复制
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 = item.time;
      longitude = item.longitude;
      latitude = item.latitude;

      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(time) {  // function closure on the "time" variable
        return 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)
          var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
          });
          bounds.extend(marker.getPosition());
          map.fitBounds(bounds);
          $("#table_body").append("<tr><td>" + time + "</td><td>" + address + "</td><td>");
        }
      }}(time)));
    })
  })
}

proof of concept fiddle

代码片段:

代码语言:javascript
复制
var testData = [{
    time: "2019-01-01 12:00:00",
    latitude: 40.7484405,
    longitude: -73.9856644
  },
  {
    time: "2019-01-01 12:10:00",
    latitude: 40.6892494,
    longitude: -74.0445004
  }
]

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {
      lat: -34.397,
      lng: 150.644
    }
  });
  var geocoder = new google.maps.Geocoder();

  var longitude;
  var latitude;
  var address;

  //GETING DATA FROM FIREBASE
  $(document).ready(function() {
    var bounds = new google.maps.LatLngBounds();
    testData.forEach(function(item, i) {
      time = item.time;
      longitude = item.longitude;
      latitude = item.latitude;

      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(time) {
        return 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)
          var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
          });
          bounds.extend(marker.getPosition());
          map.fitBounds(bounds);
          $("#table_body").append("<tr><td>" + time + "</td><td>" + address + "</td><td>");
        }
      }}(time)));
    })
  })
}

function geocodeAddress(geocoder, resultsMap) {
  var address = document.getElementById('address').value;
  geocoder.geocode({
    'address': address
  }, function(results, status) {
    if (status === 'OK') {
      resultsMap.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
        map: resultsMap,
        position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}
代码语言:javascript
复制
#map {
  height: 80%;
}

html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map"></div>
<div id="table">
  <table id="table_body">
  </table>
</div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56120680

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档