Monday, November 15, 2010

Using Google Maps API in ASP.Net


In this article, I am explaining how to use Google Map API with ASP.Net. First you need to register with the Google Maps API here and get your key from Google.
Once you get the key. You can display Google Maps on you Website using the following script that you get from Google.
<head id="Head1" runat="server">
    <title>Google Maps Example</title>
     <script type="text/javascript"
        src="http://www.google.com/jsapi?key=xxxxxxx"></script>
     <script type="text/javascript">
      google.load("maps""2");
      // Call this function when the page has been loaded
      function initialize() {
        var map = new google.maps.Map2(document.getElementById("map"));
        map.setCenter(new google.maps.LatLng("<%=lat%>""<%=lon%>"), 5);
        var point = new GPoint("<%=lon%>""<%=lat%>");
        var marker = new GMarker(point);
        map.addOverlay(marker);
        map.addControl(new GLargeMapControl());
      }
      google.setOnLoadCallback(initialize);
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="map" style="width: 400px; height: 400px"></div>
    </div>
    </form>
</body>

As you can see I have placed the script in the Head section of the HTML page. The above script gives your location on the map based on latitude and longitude. The map is loaded in the div with id map
Now to get Latitude and Longitude we will take help of my previous article Find Visitor's Geographic Location using IP Address in ASP.Net. You’ll notice I have used to server variables lat (latitude) and lon (longitude) whose values come from server.
Based on the IP address the web service returns the latitude and longitude refer the XML below
  <?xml version="1.0" encoding="UTF-8" ?>
  <Response>
    <Status>true</Status>
    <Ip>122.169.8.137</Ip>
    <CountryCode>IN</CountryCode>
    <CountryName>India</CountryName>
    <RegionCode>16</RegionCode>
    <RegionName>Maharashtra</RegionName>
    <City>Bombay</City>
    <ZipCode />
    <Latitude>18.975</Latitude>
    <Longitude>72.8258</Longitude>
  </Response>


C#

protected string lat, lon;
protected void Page_Load(object sender, EventArgs e)
{
    string ipaddress;
    ipaddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (ipaddress == "" || ipaddress == null)
        ipaddress = Request.ServerVariables["REMOTE_ADDR"];
    DataTable dt = GetLocation(ipaddress);
    if (dt != null)
    {
        if (dt.Rows.Count > 0)
        {
            lat = dt.Rows[0]["Latitude"].ToString();
            lon = dt.Rows[0]["Longitude"].ToString(); 
        }
    }
}

private DataTable GetLocation(string ipaddress)
{
    //Create a WebRequest
    WebRequest rssReq = WebRequest.Create("http://freegeoip.appspot.com/xml/"
        + ipaddress);

    //Create a Proxy
    WebProxy px = new WebProxy("http://freegeoip.appspot.com/xml/"
        + ipaddress, true);

    //Assign the proxy to the WebRequest
    rssReq.Proxy = px;

    //Set the timeout in Seconds for the WebRequest
    rssReq.Timeout = 2000;
    try
    {
        //Get the WebResponse
        WebResponse rep = rssReq.GetResponse();

        //Read the Response in a XMLTextReader
        XmlTextReader xtr = new XmlTextReader(rep.GetResponseStream());

        //Create a new DataSet
        DataSet ds = new DataSet();

        //Read the Response into the DataSet
        ds.ReadXml(xtr);
        return ds.Tables[0];
    }
    catch
    {
        return null;
    }
}


VB.Net
Protected lat As String, lon As String
Protected Sub Page_Load(ByVal sender As ObjectByVal e As EventArgs)  Handles Me.Load
        Dim ipaddress As String
        ipaddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
        If ipaddress = "" OrElse ipaddress Is Nothing Then
            ipaddress = Request.ServerVariables("REMOTE_ADDR")
        End If
        Dim dt As DataTable = GetLocation(ipaddress)
        If dt IsNot Nothing Then
            If dt.Rows.Count > 0 Then
                lat = dt.Rows(0)("Latitude").ToString()
                lon = dt.Rows(0)("Longitude").ToString()
            End If
        End If
End Sub

Private Function GetLocation(ByVal ipaddress As StringAs DataTable
        'Create a WebRequest
        Dim rssReq As WebRequest = WebRequest. _
           Create("http://freegeoip.appspot.com/xml/" & ipaddress)

        'Create a Proxy
        Dim px As New WebProxy("http://freegeoip.appspot.com/xml/" _
        & ipaddress, True)

        'Assign the proxy to the WebRequest
        rssReq.Proxy = px

        'Set the timeout in Seconds for the WebRequest
        rssReq.Timeout = 2000
        Try
            'Get the WebResponse
            Dim rep As WebResponse = rssReq.GetResponse()

            'Read the Response in a XMLTextReader
            Dim xtr As New XmlTextReader(rep.GetResponseStream())

            'Create a new DataSet
            Dim ds As New DataSet()

            'Read the Response into the DataSet
            ds.ReadXml(xtr)
            Return ds.Tables(0)
        Catch
            Return Nothing
        End Try
End Function

As you can see in the above code snippet I get the latitude and longitude from the XML Response in the variables lat and lon which I’ll used to pass values to the JavaScript function of the Google API.
This completes the article. Download the sample source from the link below.
  GoogleMapsAPI.zip (4.26 kb)

4:32 AM by Dilip kakadiya · 0