我正在尝试使用地理定位获取值(纬度、经度)。我尝试在另一个页面中使用相同的 Javascript(我将在问题下发布),但此 Javascript 仅在单击按钮时触发,
关注 OnClientClick="call(); return false;"
<asp:Button ID="BTN_Register" runat="server" Text="Register" OnClientClick="call();return false;" CssClass="btn btn-theme-bg btn-3d btn-xs" OnClick="BTN_Register_Click" />
所以回到我的问题.. 我正在使用与我在另一个 WebForm 中相同的 Javascript 代码。它的过程是检索纬度和经度,然后将其解析为 2 个 asp:HiddenFields,然后使用代码隐藏 (aspx.cs) 将它们保存到数据库中,
resultRecord = al.createLogEntry(username, externalIP, Convert.ToDouble(latitudeTB.Value), Convert.ToDouble(longitudeTB.Value), "Pending");
现在在 HTML 端用不同的 WebForm 编写,
这些是我的代码,
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
<p class="text-success" runat="server" id="loginDetails"></p>
<p class="text-danger" runat="server" id="logoutDetails"></p>
<div>
<asp:HiddenField runat="server" ID="latitudeTB"/>
<asp:HiddenField runat="server" ID="longitudeTB"/>
<script type="text/javascript">
//GeoLocation Retrieval
var geo = document.getElementById("geolocationValue");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
document.getElementById("<%=latitudeTB.ClientID %>").value = lat;
document.getElementById("<%=longitudeTB.ClientID %>").value = lng;
});
} else {
geo.innerHTML = "Geolocation is not supported by this browser.";
}
}
function call() {
getLocation();
}
/*document.onreadystatechange = function (e) {
if (document.readyState === 'complete') {
//dom is ready, window.onload fires later
call();
}
};*/
/*$(window).load(function () {
call();
});*/
</script>
</div>
在 Page_Load 中,我使用这个 RegisterClientScriptBlock 实际上导致 HiddenFields 分别填充纬度和经度,然后使用我上面发布的其他 WebForm 中的相同方法保存到数据库中,
ScriptManager.RegisterClientScriptBlock(this, GetType(), "StartGeo", "call();", true);
Debug.WriteLine(latitudeTB.Value);
Debug.WriteLine(longitudeTB.Value);
我希望我的经度和纬度值在页面加载时出现,但似乎无济于事。我检查了 HiddenFields 的值,但我我什么也没得到。这意味着 HiddenFields 为空或为空?
我可以知道我该怎么做才能解决这个问题吗?
请感谢任何帮助..谢谢!
最佳答案
您输入了错误的变量。将“纬度”和“经度”更改为纬度和经度。检查下面的编辑代码。
var lat = position.coords.latitude;
var lng = position.coords.longitude;
document.getElementById("<%=latitudeTB.ClientID %>").value = lat;
document.getElementById("<%=longitudeTB.ClientID %>").value = lng;
您之前的代码是。
var lat = position.coords.latitude;
var lng = position.coords.longitude;
document.getElementById("<%=latitudeTB.ClientID %>").value = latitude;
document.getElementById("<%=longitudeTB.ClientID %>").value = longitude;
关于javascript - 使用 Javascript 获取空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45435457/