JQuery - 未捕获的类型错误:无法读取 Google 地理编码中未定义的属性“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);

但我不想使用警报

如何解决这个问题?

谢谢

解决方法

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

从您声明的 alert() 的上下文来看,您似乎正在尝试在 #myaddress 元素中设置值。因此,使用 jQuery 对象的 val() 方法设置目标 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>