jquery - 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);
但我不想使用警报
我该如何解决这个问题?
谢谢
解决方案
抛出错误的代码行试图访问一个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>
推荐阅读
- typescript - 如何在打字稿中指定以下类型?
- elasticsearch - filebeat:创建模板时出错:字段包含键
- javascript - 在不知道密钥的情况下从 Firebase 中移除一个孩子
- azure-active-directory - 代表用户调用 MS Graph API 时未找到租户“xxx”
- powershell - 使用正则表达式匹配 Powershell 中的路径
- applescript - 进程未在后台运行
- webserver - 500 lighttpd 中的内部服务器,同时调用用“C”编写的 CGI
- function - 使用 geofirestore 在云功能中通知附近的用户
- asp.net-core - .NETCore PasswordHasher.HashPassword 不使用 TUser 用户,但为什么包含在方法签名中?
- c# - C# 我想将文本框的值与组合框中的所有项目进行比较。单击按钮时出现异常