首页 > 解决方案 > JQuery - 未捕获的类型错误:无法读取谷歌地理编码中未定义的属性“1”

问题描述

我正在尝试在 Laravel-5.8 中使用反向地理编码

< script type = "text/javascript" >
  function GetAddress() {
    var lat = parseFloat(document.getElementById("txtLat").value);
    var lng = parseFloat(document.getElementById("txtLong").value);
    var latlng = new google.maps.LatLng(lat, lng);
    var geocoder = geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      'latLng': latlng
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          $("#myaddress").results[1].formatted_address;
        }
      }
    });
  } <
  /script>
<input type="button" value="Get Address" onclick="GetAddress()" />

<input type="hidden" id="txtLat" value="{{ $currentLocationFilter[0] ?? '' }}" readonly/>
<input type="hidden" id="txtLong" value="{{ $currentLocationFilter[1] ?? '' }}" disabled/>

<input type="text" id="myaddress" value="0" disabled>

GetAddress(),我想在 myaddress 中显示结果,但出现此错误:

未捕获的类型错误:无法读取未定义的属性“1”

它指向:

未捕获的类型错误:无法读取未定义的属性“1”

这有效:

alert("Location: " + results[1].formatted_address);

但我不想使用警报

我该如何解决这个问题?

谢谢

标签: jqueryreverse-geocoding

解决方案


抛出错误的代码行试图访问一个results不存在的 jQuery 对象的属性;因此你看到的错误。

alert()您所说的工作的上下文来看,您似乎正在尝试在#myaddress元素中设置值。因此,使用val()jQuery 对象的方法来设置目标input元素的值:

$("#myaddress").val(results[1].formatted_address);

这是一个完整的示例,删除了内联事件处理程序,因为它们不再是好的做法,不应该使用。

jQuery($ => {
  $('#get-address').on('click', () => {
    var lat = parseFloat($("#txtLat").val());
    var lng = parseFloat($("#txtLong").val());
    var latlng = new google.maps.LatLng(lat, lng);

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
      latLng latlng
    }, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          $("#myaddress").val(results[1].formatted_address);
        }
      }
    });
  });
});
<input type="button" value="Get Address" id="get-address" />
<input type="hidden" id="txtLat" value="{{ $currentLocationFilter[0] ?? '' }}" readonly/>
<input type="hidden" id="txtLong" value="{{ $currentLocationFilter[1] ?? '' }}" disabled/>
<input type="text" id="myaddress" value="0" disabled>

推荐阅读