Tuesday, 9 July 2013

How to Get Latitude And Longitude in asp.net

How to Get Latitude And Longitude in asp.net?
How to find latitude and longitude of address in asp.net?

Just follow the steps to get the latitude and longitude of a address in asp.net

Get Latitude and Longitude in c#

Step:1
Create a textbox and a button in aspx page
<asp:TextBox ID ="txt_Address" runat="server"></asp:TextBox>
<asp:Button ID="btn_Get" runat="server" onclick="btn_Get_Click" Text="Latitude/Longitude"></asp:Button>


Step-2:

Write the following code in c#

protected void btn_Get_Click (object sender,EventArgs e)
       {
           string latitude = string.Empty;
           string longitude = string.Empty;
           
           string url = "http://maps.googleapis.com/maps/api/geocode/xml?address="+txt_Address.Text+"&sensor=false";
                  
                   XmlDocument xDoc = new XmlDocument();
                   xDoc.Load(url);
                   if (xDoc != null)
                   {
                       latitude = xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat")!=null?xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lat").InnerText : "0.0";
                       longitude = xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng")!=null?xDoc.SelectSingleNode("/GeocodeResponse/result/geometry/location/lng").InnerText:"0.0";
                       
                   }
Response.Write("Latitude:"+latitude +",Longitude:"+longitude );
               
           }
           catch (Exception ex)
           { }
       }

Get Latitude and Longitude in Javascript
Step-1:
Create a textbox and a button

<asp:TextBox ID ="txt_Address" runat="server"></asp:TextBox>
<input type="button" id="btn_get" value="Latitude/Longitude"/>
Step-2:
Include jquery-1.9.1.js to your aspx page

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

Step-3:
Write Following javascript code

<script type="text/javascript">

$(document).ready(function(){
$('#btn_get').click(function(){
$.getJSON("http://maps.googleapis.com/maps/api/geocode/json?address="
+$('#<%= txt_Address.ClientID %>').val()+"&sensor=false",function(d){
var lt=d.results[0].geometry.location;
alert("Address:"+d.results[0].formatted_address+"\nLat:"+lt.lat+",Long:"+lt.lng);
});
});
});
</script>

See Demo Here
  Latitude/Longitude

No comments:

Post a Comment