Saturday, December 3, 2011

ASP.net - Google Map Version 3 in ASP.net

Google Map Version 3 API is especially designed to be faster and more applicable to mobile devices, as well as traditional desktop browser applications.


In this article i will show how to bind google map in asp.net project and some basic feature of google map.


Good News for web developer there is no more API registration key needed for Version 3.0.
Thanks to Google Corporation.


Step 1
Download JQuery Script from the following Link
JQuery 1.7.1


Step 2
Create a Web application and give the solution name as SolGoogleMap


Step 3
First we need to create a page,it is look like this
<body>
    <form id="form1" runat="server">
    <div>
        
       <table border="0" cellpadding="5"  cellspacing="5" width="100%" align="center">
            <tr>
                <td style="width:60%">
                    <asp:TextBox ID="txtAddress" runat="server" Height="32px" Width="530px"></asp:TextBox>
                </td>
                <td style="width:40%">
                    <asp:Button ID="btnSearch" runat="server" Text="Search Map" Height="32px" Width="200px"/>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="height:100%">
                   <div id="GoogleMapCanvas" style="height:510px;"></div>
                </td>
            </tr>
       </table>

    </div>
    </form>
</body>


Click on Image for better view


Step 4
Add jQuery file Reference inside the head tag of the page,it is look like this
<script language="javascript" type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>

Step 5
We need to add Google Map V3 API reference in head tag,it is look like this
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places&language=en-AU"></script>

Step 6
Bind Address to the textbox control,we can use Google API to have an autocomplete for address,it is look like this
<%--The Following Script to bind google places(address) to the textbox (AutoCompleteTextbox) --%>
    <script type="text/javascript">

        $(document).ready(function () {

            var autocomplete = new google.maps.places.Autocomplete($("#txtAddress")[0], {});

            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var place = autocomplete.getPlace();
            });


        }
        );
        
    </script>

My Home Town Address

Click on Image for better view


Step 7
Now Initialize Google Map on body onload event,it is look like this.
First write script to intialize google map.
<script type="text/javascript">

        var geocoder;
        var map;

        function InitializeGoogleMap() {

            try {

                geocoder = new google.maps.Geocoder();
                // Location of the Mumbai,Thane
                var LatitudeLongitude = new google.maps.LatLng(19.1969813, 72.9962491);
                var GoogleMapOptions = {
                    zoom: 10,
                    center: LatitudeLongitude,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                }
                map = new google.maps.Map($("#GoogleMapCanvas")[0], GoogleMapOptions);


            }
            catch (E) {
                alert(E.Message);
            }

        }
    
    </script>


Then call InitializeGoogleMap function on body onload event,it is look like this
<body onload="InitializeGoogleMap(); return false">


Location of Mumbai-Thane

Click on Image for better view


Step 8
Add a Marker and Info Window on Google Map,it is look like this
function AddMarkerWithInfoWindow() {
            try {

                var Address = $("#txtAddress").val();

                // Add Marker
                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
                        });

                        // Open Info Window
                        var infowindow = new google.maps.InfoWindow(
                        {
                            content: $("#txtAddress").val()
                        }
                        );
                        google.maps.event.addListener(Marker, 'click', function () {
                            infowindow.open(map, Marker);
                        });

                    } else {
                        alert("Geocode was not successful for the following reason: " + status);
                    }
                });

            }
            catch (E) {
                alert(E.Message);
            }
        }

Call AddMarkerWithInfoWindow function on btnsearch onclientclick event,it is look like this
<asp:Button ID="btnSearch" runat="server" Text="Search Map" Height="32px" Width="200px" OnClientClick="AddMarkerWithInfoWindow(); return false" />

Full Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Google Map Version 3 in ASP.net</title>

    <script language="javascript" type="text/javascript" src="Scripts/jquery-1.7.1.min.js"></script>

    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&libraries=places&language=en-AU"></script>

     <%--The Following Script to bind google places(address) to the textbox (AutoCompleteTextbox) --%>
    <script type="text/javascript">

        $(document).ready(function () {

            var autocomplete = new google.maps.places.Autocomplete($("#txtAddress")[0], {});

            google.maps.event.addListener(autocomplete, 'place_changed', function () {
                var place = autocomplete.getPlace();
            });


        }
        );
        
    </script>

    <script type="text/javascript">

        var geocoder;
        var map;

        function InitializeGoogleMap() {

            try {

                geocoder = new google.maps.Geocoder();
                // Location of the Mumbai,Thane
                var LatitudeLongitude = new google.maps.LatLng(19.1969813, 72.9962491);
                var GoogleMapOptions = {
                    zoom: 10,
                    center: LatitudeLongitude,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                }
                map = new google.maps.Map($("#GoogleMapCanvas")[0], GoogleMapOptions);


            }
            catch (E) {
                alert(E.Message);
            }

        }

        function AddMarkerWithInfoWindow() {
            try {

                var Address = $("#txtAddress").val();

                // Add Marker
                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
                        });

                        // Open Info Window
                        var infowindow = new google.maps.InfoWindow(
                        {
                            content: $("#txtAddress").val()
                        }
                        );
                        google.maps.event.addListener(Marker, 'click', function () {
                            infowindow.open(map, Marker);
                        });

                    } else {
                        alert("Geocode was not successful for the following reason: " + status);
                    }
                });

            }
            catch (E) {
                alert(E.Message);
            }
        }
    </script>

</head>
<body onload="InitializeGoogleMap(); return false">
    <form id="form1" runat="server">
    <div>
     <table border="0" cellpadding="5"  cellspacing="5" width="100%" align="center">
            <tr>
                <td style="width:60%">
                    <asp:TextBox ID="txtAddress" runat="server" Height="32px" Width="530px"></asp:TextBox>
                </td>
                <td style="width:40%">
                    <asp:Button ID="btnSearch" runat="server" Text="Search Map" Height="32px" Width="200px" OnClientClick="AddMarkerWithInfoWindow(); return false" />
                </td>
            </tr>
            <tr>
                <td colspan="2" style="height:100%">
                   <div id="GoogleMapCanvas" style="height:510px;"></div>
                </td>
            </tr>
       </table>
    </div>
    </form>
</body>
</html>


Run the Project.


Output
1. Initialize Google Map


Click on Image for better view


2. Auto-Complete Suggestion


Click on Image for better view


3. Add Marker


Click on Image for better view


4. Open Info Window When User Click on Marker


Click on Image for better view


Download
Download Source Code

9 comments:

  1. Hey......Kishor
    Nice Code man.........

    you are genius Programmer.
    Thanks for Sharing Code...

    ReplyDelete
  2. Hmm Hey Kishor

    Thanks for the codes...
    But not sure why doesn't work?? They have problem with this line of code

    "var autocomplete = new google.maps.places.AutoComplete($("#CurrentLocationBox")[0], {});"

    ReplyDelete
  3. Did you add JQuery and Google Map API Reference in head Tag????

    ReplyDelete
    Replies
    1. Yup, I've added both. But some how there is something wrong when i try to declare the value "google.maps.places.Autocomplete".. They said it is a null value

      PS
      Sorry for my bad English

      Delete
    2. Sorry for late reply..
      it's OK brother..even my english is not so ok.

      can you send your solution copy to my email id.
      kishor.naik011.net@gmail.com
      Please send me your solution copy as soon as possible.

      Delete
    3. I run this solution on three different browser(IE9,Mozila8,Google Chrome),it worked fine.

      Did you download Source code from this article????
      Did you run this downloaded source code???

      Which browser you are using for this solution?????

      Delete
  4. Hi,

    Excellent, I insert the code in my project in a new page and it works fine. Thanks for your post. Have You another example for google maps? I have to set manually a marker and get long lat to store in a BD. and then I want to put markers from my BD on the map. I mean, any clue to do this? thanks

    ReplyDelete
    Replies
    1. http://kishor-naik-dotnet.blogspot.in/2012/11/aspnet-google-map-v3-directions-in.html

      Delete