Friday, October 19, 2012

Google Maps Control for ASP.Net - Part 1

Google Maps Control for ASP.Net - Part 1

Free Open source Control

Google Map Control for ASP.Net

Download Source Download source - 295kb

Introduction
Most of us are familiar with google map. Google has provided a very reach APIs to use it in our own application. But we need some short of javascript knowledge in order to use it. I don't know about others, but for me it was a little difficult to use javascript along with google apis in ASP.Net pages, specifically if you want to use server side functions to draw google map dynamically. For example, in my case I wanted to pull latitude longitude information from a SQL Server database and then use them to insert pushpins on google map. If you are familiar with Ajax framework, you know the answer. You will have to call asp.net server side function from javascript and use retrieved data to draw a google map. How simple is that? :). Atleast not for me. So I have decided to write a user control which can take care of javascript part and allows me to concentrate on serverside functions.

Features

Enables you to draw google map. No javascript knowledge required. Just drag and drop control on your page.
  • Ajax calls to retrieve server side data.
  • Enables you to change pushpin postions on the fly. No need to refresh full map.
  • Enables you to change pushpin icons, positions from asp.net code behind.
  • Pushpin click and drag event support in asp.net code.
  • Map click event support in asp.net code.
  • Directions support. Allows you to draw route between multiple addresses
  • Polylines and Polygons support.
  • Geocoding support i.e. Find latitude longitude from specified address and create pushpin on that location.
  • When pushpins are changing positions, automatic boundary reset and zoom support to display all pushpins. i.e. useful in real time vehicle tracking
  • Optimized to give you best performance. i.e. only those pushpin data will be retrieved from server that are changed.

How to use

In this part of article, I don't want you to explain how I created this control. Instead I want you to start using it. To view documentation for source code visit following article.
Google Maps Control for ASP.Net - Part 2

Requirements

  • Visual Studio 2005 or higher
  • Microsot ASP.Net Ajax framework. You can download it from here.
  • Internet Explorer 7.0 or Mozilla Firefox 2.x.
    (Note: It may work on other browsers. I have tested on IE and Firefox only.)
Follow below steps in order to use it in your ASP.Net website.
  • Download source from link provided on top of the page. Extract it somewhere on your harddrive.
  • Open extracted folder as a website in Visual Studio and run it. When you run this website, you will be able to navigate few samples pages.
  • To use this control in your application, copy following files to your ASP.Net application in same structure as shown below.

    Copy files

Adding Google Map control to your webpage

  • Open page where you want to insert Google Map.
  • Drag GoogleMapForASPNet.ascx control to your page.

    Drag Map Control

    You won't be able to see Google Map in design view. Instead, you should see Script Manager as part of this control.
  • At this point you can run your application and you should be able to see a blank Google Map on your page as shown below.

    Initial Blank Map
Let's add few pushpins on this map. For that you will have to add some code in Page_Load() event of your page.

Passing parameters to Google Map control

  • You must specify Google Map API Key for this component. You can obtain this key from http://code.google.com/apis/maps/signup.html.
    1.if (!IsPostBack)
    2.{
    3.GoogleMapForASPNet1.GoogleMapObject.APIKey = "";
    Note that inialization code for map should go inside if (!IsPostBack) block.
  • Optionally you can specify which version of Google maps API to use. You can get more information about Google Maps API version here.
    1.GoogleMapForASPNet1.GoogleMapObject.APIVersion = "2";
  • Specify width and height for map. You can specify either in pixels or in percentage relative to it's container.
    1.GoogleMapForASPNet1.GoogleMapObject.Width = "800px";
    2.GoogleMapForASPNet1.GoogleMapObject.Height = "600px";
  • Specify zoom level. Default is 3.
    1.GoogleMapForASPNet1.GoogleMapObject.ZoomLevel = 14;
  • Specify Center Point for map. Map will be centered on this point.
    1.GoogleMapForASPNet1.GoogleMapObject.CenterPoint
    2.= new GooglePoint("CenterPoint", 43.66619, -79.44268);
  • Add pushpins for map. This can be done by initializing GooglePoint type object. In constructor of GooglePoint, First argument is ID of this pushpin. It must be unique for each pin. Second and third arguments are latitude and longitude.
    1.GoogleMapForASPNet1.GoogleMapObject.Points.Add(
    2.new GooglePoint("1", 43.65669, -79.45278));
    Alternatively you can also do it like below,
    1.GooglePoint GP = new GooglePoint();
    2.GP.ID = "1";
    3.GP.Latitude = 43.65669;
    4.GP.Longitude = -79.43270;
    5.GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP);
    You can add as many pushpins as you wish. Now run website again and you should see pushpins on map.

    Add pushpins

Assigning custom icon to pushpins

  • You can assign your own icons with google map control. For that first copy your icons in some directory under root directory of your website. You can assign icon to a pushpin as below,
    1.GP.IconImage = "icons/pushpin-blue.png";
    Note that path to image is relative to root folder. You should have icons (or whichever) directory in root folder of your website.
  • You can add description of a pushpin which will pop up when user clicks a pushpin.
    1.GP.InfoHTML = "This is Pushpin-1";
    Marker Popup
  • You can format InfoHTML property using standard HTML tags.
    example,
    1.GP.InfoHTML = "This is <font color='red'>Pushpin-1</font>";

  • Marker Popup Formatting


Up to this point, I have explained you basics of using Google Map control. Now let's implement some advanced functionality. Let's say we want to move pushpins when user do some action. For example when a user clicks on a button. For that, follow below steps.

Creating Interactive Map

You can create interactive map using Google Map control. You can move pushpins when user clicks on a button. Here is how you can do it.
  • Insert standard asp.net button on your web page. Write following code in click event of this button.
    1.protected void Button1_Click(object sender, EventArgs e)
    2.{
    3.GoogleMapForASPNet1.GoogleMapObject.Points["1"].Latitude += 0.003;
    4.GoogleMapForASPNet1.GoogleMapObject.Points["1"].Longitude += 0.003;
    5.}
    We are incrementing Latitude and Longitude value for Pushpin-1 here. Note that I am using ID(In above code "1") of pushpin to set new Latitude and Longitude.
  • Run your application and click on Button. You will note that whole page get's refreshed (or postback). To stop it from posting back, you need to wrap this button with an Ajax Update panel. Go to Visual Studio toolbox and drag Ajax Updatepanel control on your page.

    Add UpdatePanel
  • Move your button inside this update panel.
    Add UpdatePanel
  • Now run website again and click on button. You should notice that now page is not posting back and Pushpin moves on map.


Auto refreshing map and GPS Navigation

You can use Ajax Framewor's timer control in similar way as button control (I have explained above). On Timer_Tick() event you can specify new latitude longitude for all pushpins. This way Map will move all pushpins automatically after specified time delay. You can hook up any GPS service with this control to create GPS Navigation system.

Creating Polylines with Google Map control

Create Polyline
  • Create points for polyline,
    01.//Define Points for polygon
    02.GooglePoint GP1 = new GooglePoint();
    03.GP1.ID = "GP1";
    04.GP1.Latitude = 43.66675;
    05.GP1.Longitude = -79.4042;
    06. 
    07.GooglePoint GP2 = new GooglePoint();
    08.GP2.ID = "GP2";
    09.GP2.Latitude = 43.67072;
    10.GP2.Longitude = -79.38677;
    11..
    12..//Define GP3,GP4,GP5,GP6 and GP7 in similar way
    13..
    14.GooglePoint GP7 = new GooglePoint();
    15.GP7.ID = "GP7";
    16.GP7.Latitude = 43.66656;
    17.GP7.Longitude = -79.40445;
  • Create polyline between points GP1, GP2 and GP3
    01.//Create Polygon using above points
    02.GooglePolygon PG1 = new GooglePolygon();
    03.PG1.ID = "PG1";
    04.//Give Hex code for line color
    05.PG1.FillColor = "#0000FF";
    06.PG1.FillOpacity = 0.4;
    07.//Stroke is outer border of polygon.
    08.PG1.StrokeColor = "#0000FF";
    09.PG1.StrokeOpacity = 1;
    10.PG1.StrokeWeight = 2;
    11.//Add points to polygon
    12.PG1.Points.Add(GP1);
    13.PG1.Points.Add(GP2);
    14.PG1.Points.Add(GP3);
    15.PG1.Points.Add(GP4);
    16.PG1.Points.Add(GP5);
    17.PG1.Points.Add(GP6);
    18.PG1.Points.Add(GP7);
  • Add Polyline to Google Map control,
    1.GoogleMapForASPNet1.GoogleMapObject.Polygons.Add(PG1);

Traffic Overlays

Go through samples provided in download. I have explained all sort of circumtances in which you may want to use google map control. If you have any questions, feel free to ask.

In Part 2, I have explained souce code of Google Map user control and how to customize it for your own use.
Google Maps Control for ASP.Net - Part 2

Special Notes

I have published this article on www.codeproject.com as well. Here is the link to this article.

Version 1.8 (November 30, 2011)
Following minor change is done in this version
  • Added OnZoomChanged() event. It will allow user to get current zoom level in ASP.Net code.
  • Added MapWithZoomLevels.aspx sample.
Version 1.7 (March 20, 2011)
Following changes are done in this version.
  • Changed default value of AutomaticBoundaryAndZoom to false. This will disable recentering and automatic zoom by default. Many people were not able to do this before. See example MapWithAutoMovingPushpinsAndDynamicBoundaries.aspx.
  • New event MapClicked() added to control. See example MapClickEvent.aspx.
  • New event OnPushpinClick() added to control. See example PushpinsClickEvent.aspx.
  • New event OnPushpinDrag() added to control. See example PushpinsDragEvent.aspx.
  • Removed GoogleObject.Directions.FromAddress and GoogleObject.Directions.ToAddress properties. Instead added GoogleObject.Directions.Addresses property. This will allow users to draw direction from more than two addresses. See example MapWithDirections.aspx.
  • Changed name of ShowDirection property to ShowDirectionInstructions to be more clear.
  • Added property as GoogleObject.Directions.HideMarkers. This property controls direction markers(pushpins) visibility. It will allow user to draw a route between multiple addresses with just a polyline (without default pushpins that are displayed when directions are drawn). See example MapWithDirections.aspx.
  • Added property as GoogleObject.Directions.PolylineColor. This property controls color of direction line. See example MapWithDirections.aspx.
  • Added property as GoogleObject.Directions.PolylineWidth. This property controls width of direction line. See example MapWithDirections.aspx.
  • Added property as GoogleObject.Directions.PolylineColor. This property controls opacity of direction line. See example MapWithDirections.aspx.
Version 1.6 (September 3, 2009)
It has been a long time since I updated this control. I got many requests for driving directions implementation, so I decided to release a new version. Following changes are done in this version.Here is how you can implement directions using new version.
1.GoogleMapForASPNet1.GoogleMapObject.ShowDirections = true;
2.//Provide addresses or postal code in following lines
3.GoogleMapForASPNet1.GoogleMapObject.Directions.FromAddress = txtFrom.Text;
4.GoogleMapForASPNet1.GoogleMapObject.Directions.ToAddress = txtTo.Text;
I guess it's pretty straight forward to understand. One more property is added as Directions in main control. You need to set ShowDirections=true and addresses in ToAddress and FromAddress. Download Source also provides a direction sample code.
Special thanks to Vincent Blain who has provided source code for direction implementation.

Version 1.5
Following changes are done in this version.
  • In previous versions javascript functions were embedded in GoogleMapForASPNet.ascx source. In this version javascript functions are separated in GoogleMapAPIWrapper.js file. This is done so that javascript source can be cached locally on client machine.
  • Now you can change shadow image of a marker. Following new properties are added.
    IconShadowImage - Defines which image should be used for shadow. Image path should be given relative to root folder.
  • 1.GP1.IconImage = "icons/pushpin-blue.png";
    2.GP1.IconShadowImage = "icons/pushpin-blue-shadow.png";
    IconShadowWidth - shadow width
    IconShadowHeight - shadow height

    Usually you don't need to provide IconShadowWidth and IconShadowHeight property values because this control tries to find height and width of image automatically.

  • Icon and InfoWindow Anchor properties are now supported.
    IconAnchor_posX - This defines Icons anchor position from left.
    IconAnchor_posY - This defines Icons anchor position from top.
    InfoWindowAnchor_posX - This defines Info Window(balloon)'s anchor position from left.
    InfoWindowAnchor_posY - This defines Info Window(balloon)'s anchor position from top.

    For more information on Anchors, visit following article.
    Making your own custom markers
  • Source Code documentation for this control is released alongwith this version. Click on following link to view this documentation,
    Google Maps Control for ASP.Net - Part 2

Version 1.4

Following changes are done in this version.
  • Geocoding is now supported in this version. You can find Latitude and Longitude value based on an Address. Here is how to do it
    01.GooglePoint GP = new GooglePoint();
    02.GP.Address = txtAddress.Text;
    03.//GeocodeAddress() function will geocode address and set Latitude and Longitude of GP(GooglePoint) to it's respected value.
    04.if (GP.GeocodeAddress(txtAPIKey.Text))
    05.{
    06.//Get Latitude value in a variable
    07.double Latitude = GP.Latitude;
    08.//Get Longitude value in a variable
    09.double Longitude = GP.Longitude;
    10.GoogleMapForASPNet1.GoogleMapObject.Points.Add(GP);
    11.}
    12.else
    13.{
    14.lblError.Text = "Unable to geocode this address.";
    15.}
    Download source and see samples for detailed implementation.
  • Automatic boundary is now set by default. i.e.,if pushpins are moving continuously on map and they go outside map boundaries, map will reset it's bounds to accomodate pushpins.
    You can disable automatic boundaries using following code.
    1.GoogleMapForASPNet1.GoogleMapObject.AutomaticBoundaryAndZoom = false;
  • Now you can recenter map to a new position. This was a bug in previous versions. See sample code below for new implementation,
    1.protected void btnRecenter_Click(object sender, EventArgs e)
    2.GooglePoint GP = new GooglePoint();
    3.GP.Latitude = 43.66619;
    4.GP.Longitude = -79.44268;
    5.GP.InfoHTML = "This is a new center point";
    6.GoogleMapForASPNet1.GoogleMapObject.CenterPoint = GP;
    7.GoogleMapForASPNet1.GoogleMapObject.RecenterMap = true;
    8.}
  • A bug related to Visual Studio 2008 is fixed. Old version was getting stuck in design view. This version should work fine.
  • control in GoogleMapControl.ascx is replaced with control. This allows users to place control on web page itself and thus allowing them to use Ajax controls before Google Map Control.
  • A small bug related to Satellite or Hybrid View is fixed. You can set Satellite View programatically as below,
    1.GoogleMapForASPNet1.GoogleMapObject.MapType = GoogleMapType.SATELLITE_MAP;
    or

    1.GoogleMapForASPNet1.GoogleMapObject.MapType = GoogleMapType.HYBRID_MAP;
    or
    1.GoogleMapForASPNet1.GoogleMapObject.MapType = GoogleMapType.NORMAL_MAP;

    Version 1.3

    Following changes are done in this version.
  • Added a new property called RecenterMap. When it's set to true map will be re-centered and zoomed to default level on postback.
  • Now you can add Tooltip for markers.
    Marker Tooltip
  • Draggable pushpins are now supported.
    Draggable pushpins

Version 1.2

Following changes are done in this version.
  • A minor bug related to Polygons is fixed
  • Now you can enable or disable Traffic overlays.
    Traffic Overlays

Version 1.1

Following features are added in this version.
  • Now you can draw polylines and polygons with this control
    Draw Polyline
    Draw Polygon

  • A new property GoogleMapObject.APIVersion is added with this control. This will allow users to use any version of Google Maps API. Default version is 2.

1 comment:

  1. Hello and thanks a lot for your work, I use it on my project and it's cool!
    I just have an issue : sometimes (not everytime) a click on map causes a 404, do you have any clue about this ?

    ReplyDelete