我目前正试图在我的asp.net项目中实现GeoLocation。该代码将使用地理位置获取用户的位置并更新纬度和经度标签。一旦经度标签更新了,它就会触发一个C#事件,它将根据这些值执行操作。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上做它是我能想到的唯一方法。 – user1560834