2013-11-20 133 views
0

我目前正试图在我的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。

+0

您正在混合服务器端和客户端事件,我认为这不会起作用。什么是确切的期望行为?其实我不认为你需要你的'OnTextChanged'事件(这可能导致PostBack因此刷新页面)。如果你的客户端动作需要更新服务器端的东西,AJAX可能会有所帮助...... –

+0

希望的行为是获取经度和纬度,放入它们各自的标签中,以便可以使用它们,并以某种方式解开c#事件。在OnTextChanged上做它是我能想到的唯一方法。 – user1560834

回答

0

这篇文章,虽然没有直接的关系,可能会出现一些使用您:

navigator.geolocation.getCurrentPosition sometimes works sometimes doesn't

报价,可能是与你有关的部分:

“[...]的getCurrentPosition的默认超时值是无限的(!)。这意味着如果getCurrentPosition挂在后端的某个地方,你的错误处理程序将永远不会被调用。

所以请记住这一点。

关于C#部分,我不知道你是否已经启动并运行,所以有很多方法可以做到这一点。例如,一个AJAX call to a handler page。或者,如果您使用的是JQuery,则可拨打$.Get。或者将值存储在隐藏字段中,稍后捕获代码隐藏的值。