Add following JavaScript in the head section of the page to access the Google maps API.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&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. <script>
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("canvas_maps"), mapOptions);
}
function codeAddress() {
var address = document.getElementById('<%= hdnAddress.ClientID %>').value;
//alert(address);
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
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);
Following "div" element is added on the page to display the map on the webpage. <div id="canvas_maps" style="width: 300px; height: 300px;"></div>
An ASP.NET hidden control "hdnAddress" 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.
The output on the browser will be