GeoLocation,然后是C#事件-如何实现



我目前正试图在我的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事件。我们的btnPximity调用GetLocation事件,该事件应该获取位置并更新lblLat和lblLon。

这篇文章虽然没有直接关系,但可能对你有用:

navigator.geolocation.getCurrentPosition有时工作,有时不工作;t

引用可能与您相关的部分:

'[…]getCurrentPosition的默认超时为无限(!)。这意味着,如果getCurrentPosition挂在后端的某个位置,则永远不会调用错误处理程序

所以请记住这一点。

关于C#部分,我不知道你是否已经启动并运行了它,所以有很多方法可以做到这一点。例如,对处理程序页面的AJAX调用。或者,如果您使用的是JQuery,则使用$.Get调用。或者将值存储在隐藏字段中,然后在代码后台捕获这些值。

最新更新