【发布时间】:2013-11-20 15:54:28
【问题描述】:
我目前正在尝试在我的 asp.net 项目中实现 GeoLocation。该代码将使用地理位置获取用户的位置并更新纬度和经度标签。一旦更新了经度标签,它就会触发一个 C# 事件,该事件将根据这些值执行操作。
唯一的问题是,这似乎发生得太快了——我不知道为什么!我也有点卡在设备上进行测试,但这是另一回事。长话短说,在移动设备上,页面会询问我是否要授予它访问我的位置的权限,但在执行此操作时,页面会在后台刷新。
代码是:
<asp:TextBox ID="lblLat" runat="server" BorderColor="White" BorderStyle="None" ForeColor="Black" Width="100px"></asp:TextBox>
<asp:TextBox ID="lblLon" runat="server" BorderColor="White" BorderStyle="None" ForeColor="Black" Width="100px" OnTextChanged="btnByProximity_Click"></asp:TextBox>
<button id="btnProximity" onclick="GetLocation()" runat="server" style="width: 30%">Proximity</button>
<script type="text/javascript">
function GetLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(ShowPosition, ShowError);
}
else { alert("Geolocation is not supported by this browser."); }
}
function ShowPosition(position)
{
document.getElementById("lblLat").value = position.coords.latitude;
document.getElementById("lblLon").value = position.coords.longitude;
//document.getElementById("lblChange").value = document.getElementById("lblChange").value + 1
}
function ShowError(error)
{
if (error.code == 1)
{
alert("User denied the request for Geolocation.")
}
else if (error.code == 2)
{
alert("Location information is unavailable.")
}
else if (error.code == 3)
{
alert("The request to get user location timed out.")
}
else
{
alert("An unknown error occurred.")
}
}
</script>
在顶部,我们有两个纬度和经度标签,lblLat 和 lblLon。当 lblLon 改变时,我们触发 btnByProximity_Click 事件。我们的 btnProximity 调用 GetLocation 事件,该事件应该获取位置并更新 lblLat 和 lblLon。
【问题讨论】:
-
您正在混合服务器端和客户端事件,我认为这永远不会奏效。确切的期望行为是什么?实际上,我认为您不需要您的
OnTextChanged事件(这可能导致 PostBack 因此页面刷新)。如果您的客户端操作需要更新服务器端的内容,AJAX 可能会有所帮助... -
所需的行为是获取纬度和经度,放入它们各自的标签中以便可以使用它们,并且以某种方式触发 c# 事件。在 OnTextChanged 上做是我能想到的唯一方法。
标签: c# javascript asp.net geolocation