Google Maps in website with dynamic addresses from database.

| Monday, February 18, 2013
Add following javascript in the head section of the page to access the google maps API.
 <script src=";sensor=false"></script>  

Add following javascript code in the head section of the page to access the google api functions to display the map on the page.

     var geocoder;  
     var map;  
     function initialize() {  
       geocoder = new google.maps.Geocoder();  
       var latlng = new google.maps.LatLng(-34.397, 150.644);  
       var mapOptions = {  
         zoom: 8,  
         center: latlng,  
         mapTypeId: google.maps.MapTypeId.ROADMAP  
       map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);  
     function codeAddress() {  
       var address = document.getElementById('<%= hdnAddress.ClientID %>').value;  
       geocoder.geocode({ 'address': address }, function (results, status) {  
         if (status == google.maps.GeocoderStatus.OK) {  
           var marker = new google.maps.Marker({  
             map: map,  
             position: results[0].geometry.location  
         } else {  
           alert("Geocode was not successful for the following reason: " + status);  

Above functions can be called "onload" by adding the "onload" attribute to the body tag as follows

 <body onload='initialize();'>  

Also this javascript can be called from the server side by registering the script in "Page_Load" event of the class.

 ClientScript.RegisterStartupScript(GetType(), "show", "initialize();", true);  
 ClientScript.RegisterStartupScript(GetType(), "show1", "codeAddress();", true);  

An ASP.NET hidden control is used to store the address of the location obtained from the database. Value to "hdnAddress" can be assigned from server side or client side as per the functionality of the page.

Following "div" element is added on the page to display the map on the webpage.

 <div id="map_canvas" style="width: 285px; height: 275px;"></div>  

The output on the browser will be
Size of the div with id "map_canvas" can be altered by changing the "height" and "width" attributes of the div element.

Try and Enjoy Coding!

Note - Please provide your feedback and let me know if there is any problem with above code.


  1. how to get <%= hdnAddress.ClientID %> in our aspx page

    1. Hello Arvind, you just need to place Hidden control with id "hdnAddress" in the body of aspx page and javascript will automatically fetch the Client Id.


Next Prev