Click here to Skip to main content
Click here to Skip to main content

Google Maps API V3 for ASP.NET

By , 30 Dec 2011
 

Introduction

Google Maps provides a flexible way to integrate maps to provide directions, location information, and any other kind of stuff provided by the Google Maps API in your web application. Although there are some articles in CP explaining about maps, in my article I am going to provide information about the latest Google Maps API V3 version. In this article, we will see some of the common techniques that are used with Google Maps. In order to work with the code sample explained below, you need to have some basic knowledge about JavaScript and C#.

Your First Google Maps Map

In the earlier versions of the Google Maps API, as a developer we need to register the web application with Google and we were supposed to get an API key. However with the release of the new version, key registration has been eliminated for a few days for now, but recently, Google has come up with some kind of traffic limitations and we are supposed to register the application with an API Key. You can get more information about the usage of the API and the terms at this link: http://code.google.com/apis/maps/documentation/javascript/usage.html#usage_limits. Now we will start our work and create a simple Google Maps map that can be integrated into our site. The following script is used to connect to the Google Maps API:

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>

In order to create a simple Google Map map, you can use the following JavaScript code:

function InitializeMap() 
{
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map"), myOptions);
}
window.onload = InitializeMap;

FirstGoogleMap

Google Maps Options

In the above example, we used the Map class which takes options and an HTML ID as parameters. Now moving further, we will look at the map options:

function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var options =
    {
        zoom: 3,
        center: new google.maps.LatLng(37.09, -95.71),
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: true,
        mapTypeControlOptions:
        {
            style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
            poistion: google.maps.ControlPosition.TOP_RIGHT,
            mapTypeIds: [google.maps.MapTypeId.ROADMAP, 
              google.maps.MapTypeId.TERRAIN, 
              google.maps.MapTypeId.HYBRID, 
              google.maps.MapTypeId.SATELLITE]
        },
        navigationControl: true,
        navigationControlOptions:
        {
            style: google.maps.NavigationControlStyle.ZOOM_PAN
        },
        scaleControl: true,
        disableDoubleClickZoom: true,
        draggable: false,
        streetViewControl: true,
        draggableCursor: 'move'
    };
    var map = new google.maps.Map(document.getElementById("map"), options);
}
window.onload = initialize;

In the above example, all the properties of Map have been used. You can set the map options depending on your requirements.

MapOptions

The properties of the Map class are summarized in the following table:

Property Class
MapTypeControl:true/false mapTypeControlOptions
Property Constants/Values
style
DEFAULT<br />
HORIZONTAL_BAR<br />
DROPDOWN_MENU
position
BOTTOM<br />
BOTTOM_LEFT<br />
BOTTOM_RIGHT <br />
LEFT<br />
RIGHT<br />
TOP<br />
TOP_LEFT<br />
TOP_RIGHT
mapTypeIds
ROADMAP<br />
SATELLITE<br />
Hybrid<br />
Terrain
navigationControl:true/false navigationControlOptions
Property Constants/Values
Position
BOTTOM<br />
BOTTOM_LEFT<br />
BOTTOM_RIGHT<br />
LEFT<br />
RIGHT<br />
TOP<br />
TOP_LEFT<br />
TOP_RIGHT T
style
DEFAULT<br />
SMALL<br />
ANDROID
scaleControl:true/false scaleControlOptions: scalecontroloptions has the same properties as navigation control options (position, style) and behavior is also the same.
disableDoubleClickZoom: true/false
scrollwheel: true/false
draggable: true/false
streetViewControl: true/false

Map Marker

The Marker class provides you with an option to display a marker to the user for a given location. Use of the marker is a very general task that we will use often in our application. The following example shows you how to create a simple marker.

var marker = new google.maps.Marker
(
    {
        position: new google.maps.LatLng(-34.397, 150.644),
        map: map,
        title: 'Click me'
    }
);

Marker

Info Window

With the marker displayed on the map, you create an onclick event which provides the user with a popup window showing the information about the place. You can create an info window as shown below:

var infowindow = new google.maps.InfoWindow({
    content: 'Location info:
    Country Name:
    LatLng:'
});
google.maps.event.addListener(marker, 'click', function () {
    // Calling the open method of the infoWindow 
    infowindow.open(map, marker);
});

Combining them:

var map;
function initialize() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map"), myOptions);
    var marker = new google.maps.Marker
    (
        {
            position: new google.maps.LatLng(-34.397, 150.644),
            map: map,
            title: 'Click me'
        }
    );
    var infowindow = new google.maps.InfoWindow({
        content: 'Location info:<br/>Country Name:<br/>LatLng:'
    });
    google.maps.event.addListener(marker, 'click', function () {
        // Calling the open method of the infoWindow 
        infowindow.open(map, marker);
    });
}
window.onload = initialize;

With this complete, you are going to create a map and then locate the region of the user, load the map with a marker and the info window.

InfoWindow

Multiple Markers

In some cases, if you want to handle multiple markers, you achieve this like the following:

function markicons() {
   InitializeMap();

        var ltlng = [];

        ltlng.push(new google.maps.LatLng(17.22, 78.28));
        ltlng.push(new google.maps.LatLng(13.5, 79.2));
        ltlng.push(new google.maps.LatLng(15.24, 77.16));

        map.setCenter(ltlng[0]);
        for (var i = 0; i <= ltlng.length; i++) {
            marker = new google.maps.Marker({
                map: map,
                position: ltlng[i]
            });

            (function (i, marker) {

                google.maps.event.addListener(marker, 'click', function () {

                    if (!infowindow) {
                        infowindow = new google.maps.InfoWindow();
                    }

                    infowindow.setContent("Message" + i);

                    infowindow.open(map, marker);

                });

            })(i, marker);

        }
}

mulitplemarkers

Directions

One of the most useful features of the Google Maps API is it can be used to provide directions for any given location(s). The following code is used to accomplish this task:

var directionsDisplay;
var directionsService = new google.maps.DirectionsService();

function InitializeMap() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions =
    {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map"), myOptions);

    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById('directionpanel'));

    var control = document.getElementById('control');
    control.style.display = 'block';


}
    function calcRoute() {

    var start = document.getElementById('startvalue').value;
    var end = document.getElementById('endvalue').value;
    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });

}

function Button1_onclick() {
    calcRoute();
}

window.onload = InitializeMap;

Directions

Layers

The Google Maps API provides you with multiple layer options of which one is bicycle. By using the bicycle layer, you can show bicycle paths for a particular location on the map to users. The following code snippet allows you to add a bicycle layer to a map.

var map 
function InitializeMap() {
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
   map = new google.maps.Map(document.getElementById("map"), myOptions);
}
window.onload = InitializeMap;
var bikeLayer = new google.maps.BicyclingLayer();
bikeLayer.setMap(map);

Gecoding

So far we have learned the basic concepts of creating Google maps and displaying information about a location to the user. Now we will see how we can calculate/find a location specified by the user. Geocoding is nothing but the process of finding out the latitude and longitude for a given region. The following API code shows you how to find the latitude and longitude for a location.

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);
    }
});

Geocoding C#

The same calculation can also be performed by using C#:

public static Coordinate GetCoordinates(string region)
{
    using (var client = new WebClient())
    {

        string uri = "http://maps.google.com/maps/geo?q='" + region + 
          "'&output=csv&key=ABQIAAAAzr2EBOXUKnm_jVnk0OJI7xSosDVG8KKPE1" + 
          "-m51RBrvYughuyMxQ-i1QfUnH94QxWIa6N4U6MouMmBA";

        string[] geocodeInfo = client.DownloadString(uri).Split(',');

        return new Coordinate(Convert.ToDouble(geocodeInfo[2]), 
                   Convert.ToDouble(geocodeInfo[3]));
    }
}

public struct Coordinate
{
    private double lat;
    private double lng;

    public Coordinate(double latitude, double longitude)
    {
        lat = latitude;
        lng = longitude;

    }

    public double Latitude { get { return lat; } set { lat = value; } }
    public double Longitude { get { return lng; } set { lng = value; } }

}

Reverse Geocoding

As the name indicates, it is the reverse process of geocoding; that is depending on the latitude and longitude, we can find the location name. This can be achieved using the following code:

var map;
var geocoder;
function InitializeMap() {

    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions =
    {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true
    };
    map = new google.maps.Map(document.getElementById("map"), myOptions);
}

function FindLocaiton() {
    geocoder = new google.maps.Geocoder();
    InitializeMap();

    var address = document.getElementById("addressinput").value;
    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
            });
            if (results[0].formatted_address) {
                region = results[0].formatted_address + '<br/>';
            }
            var infowindow = new google.maps.InfoWindow({
                content: 'Location info:<br/>Country Name:' + region + 
                '<br/>LatLng:' + results[0].geometry.location + ''
            });
            google.maps.event.addListener(marker, 'click', function () {
                // Calling the open method of the infoWindow 
                infowindow.open(map, marker);
            });

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

Reverse Geocoding in C#

The following C# code shows you the reverse geocoding technique:

static string baseUri = 
  "http://maps.googleapis.com/maps/api/geocode/xml?latlng={0},{1}&sensor=false";
string location = string.Empty;

public static void RetrieveFormatedAddress(string lat, string lng)
{
    string requestUri = string.Format(baseUri, lat, lng);

    using (WebClient wc = new WebClient())
    {
        string result = wc.DownloadString(requestUri);
        var xmlElm = XElement.Parse(result);
        var status = (from elm in xmlElm.Descendants() where 
            elm.Name == "status" select elm).FirstOrDefault();
        if (status.Value.ToLower() == "ok")
        {
            var res = (from elm in xmlElm.Descendants() where 
                elm.Name == "formatted_address" select elm).FirstOrDefault();
            requestUri = res.Value;
        }
    }
}

Conclusion

In this article, I have tried to explain some of the basic and most frequently used tasks of the Google Maps API V3. Hope this article will help you in completing your tasks. Further, there are lot more things in the API which I have not discussed and I would try to include them in my future updates of this article. Any comments and feedback are always welcome.

External Resources

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

S V Saichandra
Software Developer
India India
Member
S V Sai Chandra is a Software Engineer from Hyderabad Deccan. He started Embedded Programing in his college days and now he is a Web Developer by Profession. He Loves coding and his passion is always been towards Microsoft Technologies. Apart from coding his other hobbies include reading books, painting and hang out with friends is his most favorite past time hobby.
He blogs at
http://technowallet.blogspot.com
Technical Skills:
C#,Ado.Net,Asp.Net,Sql Server,JavaScript,XML,Web services.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberalcitect13 Feb '13 - 9:21 
i try it and i was found it very good job.
QuestionQuestion on google mapmemberalcitect13 Feb '13 - 9:20 
hi thanks for this very good and big job.
i have one question about this.
can i convert the javascript on "function InitializeMap()"
to VB.net??
 
thanks again
QuestionHow to search Near by Places using Google API in .netmemberMember 438680722 Jan '13 - 20:20 
Like Theaters in Mumbai
GeneralHow to search generic locations using Google with MarkermemberMember 438680722 Jan '13 - 20:14 
e.g Hospitals in Pune
 
Result should be : Jahagir
Sanchati
Sahyadri
Sasun
With Marker on Particular Location in using asp.net and Google API
QuestionFAQ: Using Google Maps & Places API Licensingmemberetechpulse8 Jan '13 - 19:47 
Q1. How to create an API console key to work with Places API?
Q2. How to use Client ID with the existing APIs?
Q3. How Generate valid signature using crypto key:?
 
visit http://www.etechpulse.com/2012/11/google-maps-places-api-license.html
GeneralMy vote of 5memberMaks_At3 Dec '12 - 20:42 
exactly what I was looking for
GeneralMy vote of 5memberMukul00322 Nov '12 - 1:10 
Super Explanation!!!
Very Easy to Understand....
Smile | :)
GeneralMy vote of 5membernaresh125221 Nov '12 - 22:05 
i was searching for this type of requirement from a long time..thank q mr.saichandra
GeneralMy vote of 5memberSenseicads9 Nov '12 - 23:25 
Excellent tutorial. It has helped me out a lot
GeneralMy vote of 5membersamu singh7 Nov '12 - 1:03 
This article is very helpful for me
QuestioncalcRoute() , what i have to do If i have multiple value expecting start and end value?memberChintsCoder24 Oct '12 - 20:59 
<pre lang="cs">function calcRoute() {
 
      var start = document.getElementById(&#39;startvalue&#39;).value;
      var end = document.getElementById(&#39;endvalue&#39;).value;
      var request = {
            origin: start,
            destination: end,
            travelMode: google.maps.DirectionsTravelMode.DRIVING
      };
      directionsService.route(request, function (response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                  directionsDisplay.setDirections(response);
            }
      });
 
}</pre>
GeneralMy vote of 5memberscott.leckie5 Oct '12 - 1:42 
Very informative, well written, and covers a lot of functionality. Thanks!
QuestionGeocoding in c#memberMember 94774772 Oct '12 - 4:31 
Hi in my website I want to show the google map according to the address entered in the textbox.
I tried using the code provided on codeProject for implementing geocoding in c# but, I can see that code is not taking the address input to display the desired location. I am just getting the Sydney map all the time. In the code I can see it calculates the Coordinates but that is never used to display the location. Please help me with the Code.
 
Thanks
GeneralMy vote of 5memberDinesh Ambaliya2 Oct '12 - 0:37 
This article helps me lots
GeneralMy vote of 5memberAbinash Bishoyi20 Aug '12 - 13:50 
Nice!!!
QuestionHow to add image to marker [modified]memberfootballpardeep10 Aug '12 - 10:37 
Can i add image to the window that comes after clicking the marker ,if yes , then how ? thanks

-- modified 10 Aug '12 - 16:55.
QuestionUsing Json google reverse geocodermemberdonpp4611 Jul '12 - 23:55 
Can you explain about the reverse geocoding using JSON insted of XML
QuestionGpoogle map registrationmemberwaldhin7 Jul '12 - 11:16 
Thanks for this great arrticle
Just wanna know if its required registration and do any payment with google maps for bussines use or we can just publish it to our website ?
Visual Basic .NETVisual Basic .NETVisual Basic .NETVisual Basic .NETVisual Basic .NETVisual Basic .NETVisual Basic .NETVisual Basic .NETVisual Basic .NETVisual Basic .NET

AnswerRe: Gpoogle map registrationmemberS V Saichandra8 Jul '12 - 21:43 
https://developers.google.com/maps/documentation/javascript/usage#usage_limits[^]
 
With reference to the above, the usage limit is free for 250 000 map loads per day.

GeneralMy vote of 5memberAndré Coimbra-Villela30 May '12 - 4:44 
Great work! Makes it look like so easy!!
thank`s a lot
QuestionMultiple Place directionsmembernipeshshah15 May '12 - 1:38 
thanks for sharing great code.
 
I have one question releated directions.
 
What to do to display multiple directions ?
 
your code for directions for two points is working fine.
 
Thanks in advance.
QuestionWhen I use this code in my aspx page it throw javascript errormemberankr02219 Apr '12 - 0:41 
hi,
I want to display route path on Google map where I am fetching lat/longs from my database. Everything is fine here but it throws the following error when i run the code:
 
Microsoft JScript runtime error: 'google.maps.MapTypeId.ROADMAP' is null or not an object
 
Thanks & regards,
Anand
GeneralMy vote of 5memberSachin_coder12 Jan '12 - 23:22 
very useful!!!
GeneralMy vote of 5memberTG_Cid3 Jan '12 - 4:19 
nice article, good job.
GeneralMy Vote of 5memberJim Garrison31 Dec '11 - 4:22 
Excellent article.
Questionlooks like great minds think alikememberjimibt20 Dec '11 - 0:21 
Using reverse geocoding to find an address[^]
 
lol - but nice additions here too...
Questionusing the Google APIs in a native (non web based) App.memberAkhilesh K Gupta15 Dec '11 - 19:27 
Hi Saichandra,
 
is it possible to use these JS based APIs in a non web based app - with all the features when we have here in web based app? would appreciate your early response...
 
Thanks,
- Akhilesh
AnswerRe: using the Google APIs in a native (non web based) App.memberS V Saichandra15 Dec '11 - 21:45 
Yes, we can use this api for desktop and mobile devices too.
Try this link:
http://code.google.com/apis/maps/documentation/javascript/[^]

GeneralMy vote of 5memberraju melveetilpurayil11 Dec '11 - 13:51 
well formatted and readable. you did it very well, because I am also planed to write an article about google map v3. when I saw your article, I stopped working on mine. Its really good one.
QuestionButton and text box inside infowindowmembertp20068 Dec '11 - 11:43 
Hi There,
 
Thanks for the article!
 
I would like to put "Go" button and a textbox inside the infowindow. There will be a get directions link inside infowindow which when clicked will display this textbox and "Go" button. When the button is clicked, it must display the directions in a panel along with directions on the map. How can we achieve this?
 
Thanks,
teepee
Questionhow to use with asp.net master pagememberMember 20681696 Dec '11 - 2:12 
How do we integrate google maps in asp.net website having master page
Jana

AnswerRe: how to use with asp.net master pagememberS V Saichandra6 Dec '11 - 2:39 
Try downloading the source code and check. The sample website consists of master page with google maps.

GeneralMy vote of 5memberitaitai5 Dec '11 - 21:16 
great great great
GeneralMy vote of 5memberomymma@hotmail.com5 Dec '11 - 20:02 
Very nice atricle
QuestionInfoWindow with scroll barsmemberCoding 1015 Dec '11 - 10:19 
I had an issue with scroll bars appearing in the infowindow popup in IE 8 and Firefox. I used the following code to resolve the issue.
 
google.maps.event.addListener(infowindow, 'domready', function() {
    // IE8 and Firefox display double scroll bars. the following will hide it.
    jQuery('#bubble').parent().parent().css('overflow', 'visible');
    jQuery('#bubble').parent().css('overflow', 'visible');
});

AnswerRe: InfoWindow with scroll barsmemberS V Saichandra5 Dec '11 - 23:51 
Use css styles for effective content in info window

GeneralThanks All .......!memberS V Saichandra30 Nov '11 - 7:23 
Thanks very one who read my articles posted comments. Your comments,suggestions and feedback helps me to come out with more articles.

GeneralMy vote of 5memberitaitai29 Nov '11 - 20:49 
great example
GeneralMy vote of 5memberMonjurul Habib29 Nov '11 - 20:16 
nice work.5
SuggestionThis is not related to ASP.NET please change titlememberklay29 Nov '11 - 17:45 
This is not related to ASP.NET please change title
GeneralRe: This is not related to ASP.NET please change titlememberS V Saichandra29 Nov '11 - 21:18 
I agree that code is completely in javascript but definitely this can be integrated in Asp.Net and the geocoding and reverse geocoding techniques are completely in c# .The example i have shown here are for the asp.net.

GeneralRe: This is not related to ASP.NET please change titlemember07navneet5 Dec '11 - 23:36 
Sir,
Sorry to bother you. But your help is needed in my posted question.
Regards,
07navneet
GeneralRe: This is not related to ASP.NET please change titlememberS V Saichandra5 Dec '11 - 23:46 
What is u r question.I have found four question in u r list

GeneralMy vote of 5memberJasmine250129 Nov '11 - 9:15 
I have read a lot of documentation about this API and had trouble understanding it, but your article is very clear and simple. I LIKE THAT Smile | :)
GeneralRe: My vote of 5memberS V Saichandra19 Apr '12 - 18:38 
thank Smile | :) you

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 30 Dec 2011
Article Copyright 2011 by S V Saichandra
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid