• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

GoogleMapsControlforASP.Net-Part2(转载)

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

Free Open source Control



Introduction

This is second part in two part series of my article Google Maps User Control for ASP.Net. In first part Google Maps Control for ASP.Net - Part 1 I have explained how to use this control in your ASP.Net application. In this part I am going to explain source code of this user control so that you can modify it for your own use.

Diagram

Diagram above shows working flow of this user control. I will explain you one by one each element in this diagram.

ASPX page with Google Map User Control

  • As I mentioned in part 1, we need to initialize few properties ofthis user control to make it work. These properties are initialized inPage_Load() event of ASPX page.
    01.protected void Page_Load(object sender, EventArgs e)
    02.    {
    03.        //Specify API key
    04.        GoogleMapForASPNet1.GoogleMapObject.APIKey =
    05.                    ConfigurationManager.AppSettings["GoogleAPIKey"];
    06. 
    07.        //Specify width and height for map.
    08.        GoogleMapForASPNet1.GoogleMapObject.Width = "800px";
    09.        // You can also specify percentage(e.g. 80%) here
    10.        GoogleMapForASPNet1.GoogleMapObject.Height = "600px";
    11. 
    12.        //Specify initial Zoom level.
    13.        GoogleMapForASPNet1.GoogleMapObject.ZoomLevel = 14;
    14. 
    15.        //Specify Center Point for map.
    16.        GoogleMapForASPNet1.GoogleMapObject.CenterPoint =
    17.                        new GooglePoint("1", 43.66619, -79.44268);
    18. 
    19.        //Add pushpins for map.
    20.        //This should be done with intialization of GooglePoint class.
    21.        //In constructor of GooglePoint, First argument is ID of this pushpin.
    22.        //It must be unique for each pin. Type is string.
    23.        //Second and third arguments are latitude and longitude.
    24.        GoogleMapForASPNet1.GoogleMapObject.Points.Add(
    25.                                new GooglePoint("1", 43.65669, -79.45278));
    26.      }
  • When you initialize these properties, they gets stored inGOOGLE_MAP_OBJECT session variable. Later on this session variable isaccessed by GService.asmx web service to draw google map.
  • Go to source of GoogleMapForASPNet.aspx.cs file. Check Page_Load() method.
    01.protected void Page_Load(object sender, EventArgs e)
    02.{
    03.    .
    04.    .
    05.    .
    06.    if (!IsPostBack)
    07.    {
    08.        Session["GOOGLE_MAP_OBJECT"] = GoogleMapObject;
    09.    }
    10.    else
    11.    {
    12.        GoogleMapObject = (GoogleObject)Session["GOOGLE_MAP_OBJECT"];
    13.        .
    14.        .
    15.        .

    As you can see, I am storing GoogleMapObject property in a sessionvariable if this is a first time load of page. If this is a post backthen I use existing session variable value and assign it toGoogleMapObject property.

User Control (GoogleMapForASPNet.ascx)

  • GoogleMapForASPNet.ascx file contains a &ltDIV> element withID=GoogleMap_Div. Google map is drawn on this &ltDIV> element
  • GoogleMapForASPNet.ascx is responsible for calling DrawGoogleMap()javascript function on page load. If you see source ofGoogleMapForASPNet.ascx.cs file, it contains following lines inPage_Load() event.
    1.Page.ClientScript.RegisterStartupScript(Page.GetType(), "onLoadCall", "
    2.                                            if (window.DrawGoogleMap) { DrawGoogleMap(); }
    3.                                            ");

    This causes DrawGoogleMap() function to get fired.

GoogleMapAPIWrapper.js

  • This javascript acts as a wrapper between ASP.Net calls and Google Maps Core API functions.
  • When DrawGoogleMap() function is called, it calls web service method GService.GetGoogleObject() to get session variable values.
  • Once different parameters are retrieved from session variable, itwill start calling Google Maps core API functions to draw a map.

Web Service (GService.asmx)

  • As I have mentioned before, GService.GetGoogleObject() andGService.GetGoogleObjectOptimized() are functions defined inGService.asmx file.
  • These functions retrieves Google Map parameters from session variable.

How to define a Web Service Method

  • This control uses Web Service Methods to get values from a sessionvariable. These methods are defined in Gservice.cs(GService.asmx codebehind) file.
  • Go to source of GService.cs file. Observe how GetGoogleObject() web method is defined.
    01.[WebMethod(EnableSession = true)]
    02.public GoogleObject GetGoogleObject()
    03.{
    04.    GoogleObject objGoogle = 
    05.        (GoogleObject)System.Web.HttpContext.Current.Session["GOOGLE_MAP_OBJECT"];
    06. 
    07.    System.Web.HttpContext.Current.Session["GOOGLE_MAP_OBJECT_OLD"] =
    08.                                                      new GoogleObject(objGoogle);
    09.    return objGoogle;
    10.}

    Return value type from this method is GoogleObject.

How to call ASP.Net function (Web service method) from Javascript using a Web Service

  • If you go to HTML source of GoogleMapForASPNet.ascx file, you will see that I am using <ScriptManagerProxy> control.
    When &ltServiceReference> is used with&ltScriptManagerProxy> or &ltScriptManager> controls, itallows you to use web service methods defined in code behind.
  • Go to source of GoogleMapAPIWrapper.js file. Observe how I am calling a web service method in DrawGoogleMap() function.
    01.function DrawGoogleMap()
    02.{
    03.    if (GBrowserIsCompatible())
    04.    {
    05.    map = new GMap2(document.getElementById("GoogleMap_Div"));
    06.    geocoder = new GClientGeocoder();
    07.   
    08.     GService.GetGoogleObject(fGetGoogleObject);
    09.    }
    10.}

    GService.GetGoogleObject() is a web service method.fGetGoogleObject() is a javascript function that should be called onceweb service method returns.
    01.function fGetGoogleObject(result, userContext)
    02.{
    03.    map.setCenter(new GLatLng(result.CenterPoint.Latitude,
    04.                        result.CenterPoint.Longitude), result.ZoomLevel);
    05.     
    06.    if(result.ShowMapTypesControl)
    07.    {
    08.        map.addControl(new GMapTypeControl());
    09.    }
    10.    .
    11.    .
    12.    .

    result is return value from web service method GService.GetGoogleObject(). Thus result is of type GoogleObject. You can access properties of result in javascript to get map parameters.

Difference between GetGoogleObject() and GetGoogleObjectOptimized()

  • Both of these methods work in similar fashion. GetGoogleObject() iscalled when page loads for first time. It returns all of theGoogleObject properties to javascript function. WhileGetGoogleObjectOptimized is called on postback. It does not return allof the properties. Instead it returns minimum properties required tomake a change in existing map.
  • If you view source of GoogleMapAPIWrapper.js file, there are two functions defined in it as below,
    01.function endRequestHandler(sender, args)
    02.{
    03.    GService.GetOptimizedGoogleObject(fGetGoogleObjectOptimized);
    04.}
    05.function pageLoad()
    06.{
    07.    if(!Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack())
    08.        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
    09.

    These function causes GService.GetOptimizedGoogleObject() to getfired when an AJAX call finishes. For example let's say you have abutton in an UpdatePanel. When you click it, it postbacks the page.When this postback completes, above function will get fire.

Functions defined in GoogleMapAPIWrapper.js

  • To make this article short, I don't want to explain each and everyfunction defined in this file. Instead I will explain importantfunctions only. If you want more details for any code that's notexplained here, you can post your questions in Comments section..
  • 01.function CreateMarker(point,icon1,InfoHTML,bDraggable,sTitle)
    02.{
    03.    var marker;
    04.        marker = new GMarker(point,{icon:icon1,draggable:bDraggable,title: sTitle});
    05.    if(InfoHTML!='')
    06.    {
    07.        GEvent.addListener(marker, "click", function() { this.openInfoWindowHtml(InfoHTML); });
    08.    }
    09.        GEvent.addListener(marker, "dragend", function() { 
    10.            GService.SetLatLon(this.value,this.getLatLng().y,this.getLatLng().x);
    11.            RaiseEvent('PushpinMoved',this.value);  });
    12.    return marker;
    13.}

    This function creates a marker on Google Map. As you can see, I amadding two events with each marker. First one is click(). When a userclicks on marker, a balloon (info window) pops up. This is a javascriptevent. Second one is dragend(). If a user wants he can drag a pushpinto a new location. This will cause a web method GService.SetLatLon() toget executed. This method sets new latitude and longitude values inSession Variable. As you can see this function also calls RaiseEvent()function which causes an AJAX postback.
    function RaiseEvent(pEventName,pEventValue)
    {
    document.getElementById('').value = pEventName;
    document.getElementById('').value = pEventValue;
    __doPostBack('UpdatePanel1','');
    }

    When postback finishes, new latitude and longitude values will be picked up from Session Variable.
  • function RecenterAndZoom(bRecenter,result)

    This function causes Recentering of map. It finds all visiblemarkers on map and decides center point and zoom level based on thesemarkers.
  • function CreatePolyline(points,color,width,isgeodesic)

    This function creates polylines between given points. See Polylines property in GoogleObject class.
  • function CreatePolygon(points,strokecolor,strokeweight,strokeopacity,fillcolor,fillopacity)

    This function creates polygons between given points. See Polygons property in GoogleObject class.

How to define Icons for google map

  • If you see implementation of fGetGoogleObject() andfGetGoogleObjectOptimized() javascript functions, you can see that I amcreating custom icons for google map. This is how they are defined.
        .
    .
    myIcon_google = new GIcon(G_DEFAULT_ICON);
    markerOptions = { icon:myIcon_google };

     

    myIcon_google.iconSize = new GSize(result.Points[i].IconImageWidth,
    result.Points[i].IconImageHeight);
    myIcon_google.image = result.Points[i].IconImage;
    myIcon_google.shadow = result.Points[i].IconShadowImage;
    myIcon_google.shadowSize = new GSize(result.Points[i].IconShadowWidth,
    result.Points[i].IconShadowHeight);
    myIcon_google.iconAnchor = new GPoint(result.Points[i].IconAnchor_posX,
    result.Points[i].IconAnchor_posY);
    myIcon_google.infoWindowAnchor = new GPoint(result.Points[i].InfoWindowAnchor_posX,
    result.Points[i].InfoWindowAnchor_posY);
    .
    .

  • There are various properties that you can set for a custom icon.Following article explains you each of these properties in detail.
    Making your own custom markers

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
ASP.NETWebForm中JavaScript修改了页面上Label的值,如何在后台代码中获取 ...发布时间:2022-07-10
下一篇:
ASP.NET发送电子邮件发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap