jQuery Latest CDN Links

Implement Google Places (Address) AutoComplete TextBox in ASP.Net using C# and VB.Net

Implement Google Places (Address) AutoComplete TextBox in ASP.Net using C# and VB.Net


In this article I will explain with an example, how to implement Google Places (Address) AutoComplete TextBox in ASP.Net using C# and VB.Net.


HTML Markup
<table border="0" cellpadding="5" cellspacing="0">
    <tr>
        <td>Location</td>
        <td><asp:TextBox ID="txtLocation" runat="server" Width="200" /></td>
    </tr>
    <tr>
        <td>Address</td>
        <td><asp:TextBox ID="txtAddress" runat="server" Width="200" /></td>
    </tr>
    <tr>
        <td>Latitude</td>
        <td><asp:TextBox ID="txtLatitude" runat="server" Width="200" /></td>
    </tr>
    <tr>
        <td>Longitude</td>
        <td><asp:TextBox ID="txtLongitude" runat="server" Width="200" /></td>
    </tr>
    <tr>
        <td></td>
        <td><asp:Button Text="Submit" runat="server" OnClick = "OnSubmit" /></td>
    </tr>
</table>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places&key=<API Key>"></script>
<script type="text/javascript">
    google.maps.event.addDomListener(window, 'load', function () {
        var places = new google.maps.places.Autocomplete(document.getElementById('<%=txtLocation.ClientID %>'));
        google.maps.event.addListener(places, 'place_changed', function () {
            var place = places.getPlace();
            document.getElementById('<%=txtAddress.ClientID %>').value = place.formatted_address;
            document.getElementById('<%=txtLatitude.ClientID %>').value = place.geometry.location.lat();
            document.getElementById('<%=txtLongitude.ClientID %>').value = place.geometry.location.lng();
        });
    });
</script>
C#
protected void OnSubmit(object sender, EventArgs e)
{
    string message = "Address: " + txtAddress.Text;
    message += "\\nLatitude: " + txtLatitude.Text;
    message += "\\nLongitude: " + txtLongitude.Text;
    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('" + message + "');", true);
}
VB.Net
Protected Sub OnSubmit(ByVal sender As Object, ByVal e As EventArgs)
    Dim message As String = "Address: " & txtAddress.Text
    message &= "\nLatitude: " & txtLatitude.Text
    message &= "\nLongitude: " & txtLongitude.Text
    ClientScript.RegisterStartupScript(Me.GetType, "alert", "alert('" & message & "');", True)
End Sub
======================================================================

Comments