C# .NET - to use google map in c# - Asked By Prat Mandav on 26-Aug-11 04:37 AM

http://ranahareesh.practo.com/

can u tell how to get the following functionalities in goole map

please tell if u know
Asked By Prat Mandav on 26-Aug-11 04:44 AM
but bro i ma talking about the locating method ................
dipa ahuja replied to Prat Mandav on 26-Aug-11 04:46 AM

Ever wanted to add a Google Map to your site but only had 15 minutes to spare? Now you can add a map and still have time to brag to your mates and bask in the worship that (inevitably) comes afterward.

Basically, the guys over at http://subgurim.net/ have already done all the hard work in writing the .Net wrapper for Google Maps. Problem is, the examples on their site are mostly in spanish & its a bit difficult to find out exactly what is needed to get everything working.

But all this is cutting into your bragging time - so lets get started!

1. Get a Google Maps API key from here:
http://www.google.com/apis/maps/

2. Download the SubGurim wrapper dll from here:
http://en.googlemaps.subgurim.net/descargar.aspx

3. Unzip it, and put it in your \bin directory

4. Add it to your toolbox by
Tools -> Choose Toolbox Items -> Browse -> Select the .dll file -> OK
GMap will now be in the ‘Standard’ area of your Toolbox.

5. Add a new webpage.

6. Drag the GMap from the toolbox onto the page. A new instance of the GMap will appear on the page, with the name ‘GMap1′

7. Add the following lines to your web.config file:

 

<appSettings>

  <add key="googlemaps.subgurim.net" value="YourGoogleMapsAPIKeyHere" />

  </appSettings>

 

8. Add the following code to your Page.Load

protected void Page_Load(object sender, EventArgs e)

{

  string sStreetAddress = null;

  string sMapKey = ConfigurationManager.AppSettings("googlemaps.subgurim.net");

  Subgurim.Controles.GeoCode GeoCode = default(Subgurim.Controles.GeoCode);

 

  sStreetAddress = "100 Russell St. Melbourne. VIC. 3000. Australia";

  GeoCode = GMap1.geoCodeRequest(sStreetAddress, sMapKey);

  Subgurim.Controles.GLatLng gLatLng = new Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat, GeoCode.Placemark.coordinates.lng);

 

  GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal);

  Subgurim.Controles.GMarker oMarker = new Subgurim.Controles.GMarker(gLatLng);

  GMap1.addGMarker(oMarker);

}

 

Jitendra Faye replied to Prat Mandav on 26-Aug-11 04:46 AM
Follow these steps-

Step 1. Get a Google Maps API key

In order to use Google Maps on your site, you need to register for a free Google Maps API key from here: http://www.google.com/apis/maps/

 

Step 2. Download the SubGurim Google Maps wrapper dll

This one is the best Google Maps wrapper I have found so far http://en.googlemaps.subgurim.net/descargar.aspx.  It is a commercial product (from $10), or you can put up with the overlayed text in the free versions.

Download the gmaps.dll file and add it to your \bin directory.


Step 3. Set up your aspx page

In your aspx page, add a few text boxes to gather the address details.  You can simply use one textbox, or split the address to enable validation for suburbs, countries, etc.  I haven't included any form validation in my example.

<p style="text-align:right; margin-right:300px">
    Street Address:
    <asp:textbox ID="txtStreetAddress" runat="server" Width="150px" /><br />
    Suburb:
    <asp:textbox ID="txtSuburb" runat="server" Width="150px" /><br />
    Country:
    <asp:textbox ID="txtCountry" runat="server" Width="150px" /><br /><br />
    <asp:Button Text="Show Map" ID="lnkShowMap" runat="server" />
</p>

You need to add your Google API key to your web.config file like so:

<appSettings>
    <add key="googlemaps.subgurim.net" value="YourGoogleMapsAPIKeyHere" />
</appSettings>

And finally, you need to register the SubGurim wrapper at the top of your page (or in your web.config if you have a number of pages that display maps):

<%@ Register Assembly="GMaps" Namespace="Subgurim.Controles" TagPrefix="cc1" %>


Step 4: Add code to display the map

Finally, add code that collates your address fields and calls the Google Maps wrapper.

Protected Sub lnkShowMap_Click(ByVal sender As Object, ByVal e As System.EventArgs)
    Handles lnkShowMap.Click
    Dim strFullAddress As String
    Dim sMapKey As String =
    ConfigurationManager.AppSettings("googlemaps.subgurim.net")
    Dim GeoCode As Subgurim.Controles.GeoCode

    ' Combine our address fields to create the full address.  The street,
    ' suburb and country should be seperated by  periods (.)
    strFullAddress = txtStreetAddress.Text & ". " & txtSuburb.Text
    & ". " & txtCountry.Text

    ' Work out the longitude and latitude
    GeoCode = GMap1.geoCodeRequest(strFullAddress, sMapKey)
    Dim gLatLng As New Subgurim.Controles.GLatLng(GeoCode.Placemark.coordinates.lat,
    GeoCode.Placemark.coordinates.lng)
    ' Display the map
    GMap1.setCenter(gLatLng, 16, Subgurim.Controles.GMapType.GTypes.Normal)
    Dim oMarker As New Subgurim.Controles.GMarker(gLatLng)
    GMap1.addGMarker(oMarker)
End Sub

Hope this will help you.


Sreekumar P replied to Prat Mandav on 26-Aug-11 05:04 AM
Hi,

Getting Google Maps API Key

The first important step of getting started with the Google Maps API is obtaining the Google Maps API Key. Don’t worry it is free of charge and you receive the key immediately after filling in a form http://code.google.com/apis/maps/signup.html.

Creating a Simple Map

Okay, now it’s the right time to open Visual Studio and create a new web site.

Then, add the following code to the <head> tag:


<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=<YOUR_API_KEY>&sensor=false"
        type="text/javascript"></script>
<script type="text/javascript">
    function initialize() {
        if (GBrowserIsCompatible()) {
            var map = new GMap2(document.getElementById("map"));
            map.setCenter(new GLatLng(51.5, -0.1), 10);
            map.setUIToDefault();
        }
    }

Don’t forget to change <YOUR_API_KEY> to an appropriate value. As you can see we have just one function called initialize() that creates a new instance of the map object. We also pass the object – a div – that will be a map container. Then, we invoke the setCenter() method that receives two arguments –coordinates and a zoom level. The setUIToDefault() method just adds the UI manipulators, if you remove or comment that line, you will receive a bare map without any UI controls.

Also, you need to add some code that will run the initialize() function and the HTML code for the map container.

<body onload="initialize()" onunload="GUnload()">
    <form id="form1" runat="server">
        <div id="map" style="width: 500px; height: 500px"></div>
    </form>
</body>

The code is pretty self-explanatory, it just adds the handlers for the onLoad and onUnLoad events of the page and also we put a div that will contain the map, you can adjust its width and height in order to get a bigger or a smaller map.

After compiling this page you should see a map similar to this one:

image

Finding a place by its address

Well, it was pretty simple, but in real life project you usually have to find a place on the maps by its address. This is also possible with the Google Maps API. All you have to do is to make use of the GClientGeocoder class and its method called getLatLang() that accepts two parameters:

  • address – the address to look for
  • function – a callback function with one parameter point that posses the coordinates of the found place

So, if we want to find a house where Sherlock Holmes lived we have to write the following code:

<script type="text/javascript">
        var map;
        var geocoder;
        function initialize() {
            if (GBrowserIsCompatible()) {
                map = new GMap2(document.getElementById("map"));
                map.setCenter(new GLatLng(51.5, -0.1), 10);
                map.setUIToDefault();

                geocoder = new GClientGeocoder();

                showAddress("221B Baker Street, London, United Kingdom");
            }
        }
        function showAddress(address) {
            geocoder.getLatLng(
                address,
                function (point) {
                    if (!point) {
                        alert(address + " not found");
                    }
                    else {
                        map.setCenter(point, 15);
                        var marker = new GMarker(point);
                        map.addOverlay(marker);
                        marker.openInfoWindow(address);
                    }
                }
            );
        }
        </script>

Also, we create a map overlay that will contain the address information, for this purpose we create an instance of the GMarker class and use the openInfoWindow() method.

User Interaction with Map

Okay, but what if we want to let user enter an address in a form and find its on the map? No problems! Just add the necessary field and write an event-handler.

<script type="text/javascript">
        var map;
        var geocoder;
        function initialize() {
            if (GBrowserIsCompatible()) {
                map = new GMap2(document.getElementById("map"));
                map.setCenter(new GLatLng(51.5, -0.1), 10);
                map.setUIToDefault();

                geocoder = new GClientGeocoder();
            }
        }
        function showAddress() {
            var txtAddress = document.getElementById("<%=txtAddress.ClientID %>");
            var address = txtAddress.value;
            
            geocoder.getLatLng(
                address,
                function (point) {
                    if (!point) {
                        alert(address + " not found");
                    }
                    else {
                        map.setCenter(point, 15);
                        var marker = new GMarker(point);
                        map.addOverlay(marker);
                        marker.openInfoWindow(address);
                    }
                }
            );
        }
        </script>
</head>
<body onload="initialize()" onunload="GUnload()">
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="txtAddress" runat="server" />
            <input type="button" value="Find" onclick="showAddress();" />
        </div>
    
        <div id="map" style="width: 500px; height: 500px"></div>
    </form>
</body>

Letting Users to Manually Select a Place on the Map

Well, finding a place by its address is certainly cool, but we can add yet another level of interactivity to our map. Basically, we can let users to use manually choose a place on the map by just dragging a marker.

<script type="text/javascript">
        var map;
        var geocoder;
        function initialize() {
            if (GBrowserIsCompatible()) {
                map = new GMap2(document.getElementById("map"));
                var center = new GLatLng(51.5, -0.1);
                map.setCenter(center, 10);
                map.setUIToDefault();

                var marker = new GMarker(center, { draggable: true });
                map.addOverlay(marker);
                marker.openInfoWindow("Drag the marker to a specific position");

                GEvent.addListener(marker, "dragstart", function() {
                    map.closeInfoWindow();
                });

                GEvent.addListener(marker, "dragend", function() {
                    var hdnLat = document.getElementById("<%=hdnLat.ClientID %>");
                    var hdnLng = document.getElementById("<%=hdnLng.ClientID %>");

                    hdnLat.value = this.getLatLng().lat();
                    hdnLng.value = this.getLatLng().lng();

                    marker.openInfoWindow("New position has been set");
                });
            }
        }
        </script>
</head>
<body onload="initialize()" onunload="GUnload()">
    <form id="form1" runat="server">
        <asp:HiddenField ID="hdnLat" runat="server" />
        <asp:HiddenField ID="hdnLng" runat="server" />
        <div id="map" style="width: 500px; height: 500px"></div>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" 
            onclick="btnSubmit_Click" />
    </form>
</body>

If you look at the HTML code, then you will notice that we have added to hidden field that will contain the coordinates of a chosen place, so the first field is for keeping the latitude and the second one is for keeping the longitude. This time when creating a marker we set its options and one of the option is “draggable: true”, so it lets users to drag the marker over the map. Then, we should add event handlers, the main event is “dragend”. It occurs ever time a user place a marker on a new place. As a result, in its event handler we receive the coordinates of a new position and save them in the hidden fields.

Also, we wrote an event handler for the “dragstart” event, just to close the info window while dragging the marker.

In a real world application there would be some server-side code that would place the received coordinates into a database, but in this particular case, we will just output them:


protected void btnSubmit_Click(object sender, EventArgs e)
{
    Response.Write("Latitude: " + hdnLat.Value + " Longitude: " + hdnLng.Value);
}

Passing the Coordinates from Server-Side to Google Maps

Now, what if we have the coordinates stores somewhere in the database and want to point to that place on the map? Well, it’s still not difficult. We just have to pass the values from server-side to JavaScript.

<script type="text/javascript">
        var map;
        function initialize() {
            if (GBrowserIsCompatible()) {
                map = new GMap2(document.getElementById("map"));
                
                var lat = <asp:Literal ID="ltrLat" runat="server" />;
                var lng = <asp:Literal ID="ltrLng" runat="server" />;
                
                var center = new GLatLng(lat, lng);
                
                map.setCenter(center, 10);
                map.setUIToDefault();
                
                var marker = new GMarker(center);
                map.addOverlay(marker);
                marker.openInfoWindow("Here");
            }
        }
        </script>

The easiest way to achieve this is to use the ASP.NET Literal controls that doesn’t generate any tags around their values.

Since, those Literal controls are outside of the form tag, we have to use the FindControl() method to access them in code-behind:

protected void Page_Load(object sender, EventArgs e)
{
    Literal ltrLat = (Literal)FindControl("ltrLat");
    Literal ltrLng = (Literal)FindControl("ltrLng");
    
    ltrLat.Text = "51";
    ltrLng.Text = "0";
}

Conclusion

In this tutorial we have covered the basics of working with the Google Maps API. We have learnt how to add a map on a page, how to use geo coding for finding a place by its address on the map. We have also got to know how we can let users interact with a map by dragging a marker and how to receive the marker coordinates and store them on server-side. Finally, we have learnt how to pass the coordinates stored on server-side to the Google Maps API and point to that place on a map.

Also, in this tutorial version 2 of the API was covered, however the 3rd version is currently in Google Labs.

Reena Jain replied to Prat Mandav on 26-Aug-11 05:34 AM
You can use the Google Maps Javascript API: Look http://code.google.com/apis/maps/documentation/v3/introduction.html for the documentation on that.

You need to specify the js file location in the Script tag, and provide the place co-ordinates in the LatLng function.
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  function initialize()
  {
var latlng = new google.maps.LatLng(10.44,23.35);
var myOptions = { zoom: 9, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("theGoogleMap"), myOptions);
  }
</script>
</head>
<body onload="initialize()">
   <div id="theGoogleMap"></div>
</body>

Or you could use the Google map ASP.Net server control that is well-explained http://dotnet.sys-con.com/node/171162. And output would be like below:


the documentatain of the api can be found http://www.google.com/apis/maps/documentation/.
Anoop S replied to Prat Mandav on 26-Aug-11 08:11 AM

In this article will explain how we can show multiple locations binding from code behind dynamically (database or any data source).  Couple of moths ago in Asp.Net forum I have posted an article using Google Map Version 2.0
. Version two was kind of messy Java Script code but now in Version 3.0 Google made it very simple.

http://deepumi.files.wordpress.com/2010/03/googlemap3.png

Refer this for more details and code

http://deepumi.wordpress.com/2010/03/28/google-map-3-with-multiple-locations-in-asp-net-c/

Radhika roy replied to Prat Mandav on 27-Aug-11 06:41 AM

I found this http://dotnet.sys-con.com/read/171162.htm recently which I thought was pretty cool. It describes how to build and use an ASP.NET Server Control that makes Google Map integration easy within ASP.NET applications:

refer the link also
http://weblogs.asp.net/scottgu/archive/2006/01/22/436166.aspx
http://www.mikeborozdin.com/post/Working-with-Google-Maps-API-in-ASPNET.aspx

Hope this will help you.