天道酬勤

博观而约取,厚积而薄发!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Google Maps Control for ASP.Net - Part 1 (转载)

Posted on 2010-05-25 09:33  Happy Coding  阅读(1274)  评论(0编辑  收藏  举报

原文地址:http://www.shabdar.org/google-maps-user-control-for-ASP-Net-part1.html

 

Free Open source Control

Google Map Control for ASP.Net

Download Source Download source - 288kb

Version 1.6 (September 3, 2009)

It has been along time since I updated this control. I got many requests for drivingdirections implementation, so I decided to release a new version.Following changes are done in this version.Here is how you canimplement 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 previousversions javascript functions were embedded in GoogleMapForASPNet.ascxsource. In this version javascript functions are separated inGoogleMapAPIWrapper.js file. This is done so that javascript source canbe 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  

     

    Usuallyyou don't need to provide IconShadowWidth and IconShadowHeight propertyvalues because this control tries to find height and width of imageautomatically.

  • 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

     

  • SourceCode 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.

     

     

  • Automaticboundary is now set by default. i.e.,if pushpins are movingcontinuously on map and they go outside map boundaries, map will resetit'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 inGoogleMapControl.ascx is replaced with control. This allows users toplace control on web page itself and thus allowing them to use Ajaxcontrols 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

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

Introduction

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

Features

Enables you to draw google map. No javascript knowledge required. Just drag and drop control on your page.

  • Uses 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 on the fly.
  • 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 partof 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 sourcecode 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.
  • Openextracted folder as a website in Visual Studio and run it. When you runthis 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


Now wewill add reference to Ajax library. If you are already using Ajaxcontrols in your application, you can skip following 4 steps.

Adding Ajax Framework to your website

  • Right click on your website in solution explorer and click add reference.

     

    Add Reference to Ajax library

  • In AddReference window, select System.Web and System.Web.Extensions librariesand click OK. Note library versions (in below picture 1.0.61025.0. Youmay have another version. You can use any version).

     

    Add Reference to Ajax library

  • Go to your web.config file and add following lines between element.
    01.type="System.Web.Script.Services.ScriptHandlerFactory,
    02.System.Web.Extensions,  Version=1.0.61025.0,
    03.Culture=neutral,
    04.PublicKeyToken=31BF3856AD364E35"
    05.validate="false"/>
    06.     
    07.type="System.Web.Script.Services.ScriptHandlerFactory,
    08.System.Web.Extensions, Version=1.0.61025.0,
    09.Culture=neutral,
    10.PublicKeyToken=31BF3856AD364E35"
    11.validate="false"/>
    12.     
    13.type="System.Web.Handlers.ScriptResourceHandler,
    14.System.Web.Extensions, Version=1.0.61025.0,
    15.Culture=neutral,
    16.PublicKeyToken=31BF3856AD364E35"
    17.validate="false"/>
    18.    
    19.type="System.Web.Handlers.ScriptModule,
    20.System.Web.Extensions,
    21.Version=1.0.61025.0, Culture=neutral,
    22.PublicKeyToken=31BF3856AD364E35"/>

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 pushpinsfor map. This can be done by initializing GooglePoint type object. Inconstructor of GooglePoint, First argument is ID of this pushpin. Itmust be unique for each pin. Second and third arguments are latitudeand 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 canassign your own icons with google map control. For that first copy youricons in some directory under root directory of your website. You canassign icon to a pushpin as below,
    1.GP.IconImage = "icons/pushpin-blue.png";
    Note that pathto image is relative to root folder. You should have icons (orwhichever) 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 tothis point, I have explained you basics of using Google Map control.Now let's implement some advanced functionality. Let's say we want tomove pushpins when user do some action. For example when a user clickson a button. For that, follow below steps.

Creating Interactive Map

You cancreate interactive map using Google Map control. You can move pushpinswhen 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 areincrementing Latitude and Longitude value for Pushpin-1 here. Note thatI am using ID(In above code "1") of pushpin to set new Latitude andLongitude.

     

     

  • Run yourapplication and click on Button. You will note that whole page get'srefreshed (or postback). To stop it from posting back, you need to wrapthis button with an Ajax Update panel. Go to Visual Studio toolbox anddrag 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 useAjax Framewor's timer control in similar way as button control (I haveexplained above). On Timer_Tick() event you can specify new latitudelongitude for all pushpins. This way Map will move all pushpinsautomatically after specified time delay. You can hook up any GPSservice 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 throughsamples provided in download. I have explained all sort of circumtancesin which you may want to use google map control. If you have anyquestions, 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.

Google Maps Control for ASP.Net - Part 1