Google 地图 Web 部件






3.13/5 (4投票s)
一个 Google 地图 WebPart。
引言
本文介绍了一个 Google 地图 WebPart。
使用代码
Google 地图控件的渲染在 WebPart 的 Render
事件中进行。Google 地图控件使用 ClientScriptManager
对象进行初始化。
protected override void Render(HtmlTextWriter writer)
{
string rScript = "";
rScript += "<script src=\"http://maps.google.com/maps?file=api&v=2&key=" +
m_rGoogleKey + "\"\n type=\"text/javascript\"></script>\n";
rScript += "<script type=\"text/javascript\">\n";
rScript += "//<![CDATA[\n";
rScript += "function Init()\n";
rScript += "{\n";
rScript += "var map = new GMap2(document.getElementById(\"map\"));\n";
if (DisableDragging)
rScript += "map.disableDragging();\n";
rScript += "var latlng = new GLatLng(" + m_dLatitude + ", " + m_dLongitude + ");\n";
rScript += "map.setCenter(latlng, " + m_nZoomLevel + ");\n";
if (DisplayZoomControl)
rScript += "map.addControl(new GLargeMapControl());\n";
rScript += "map.addControl(new GMapTypeControl());\n";
rScript += "var mkr = new GMarker(latlng);\n";
if (DisplayIcon)
rScript += "map.addOverlay(mkr);\n";
rScript += "}\n";
rScript += "//]]>\n";
rScript += "</script>\n";
rScript += " <div id=\"map\" style=\"width: " + GWidth + "px; height: " +
GHeight + "px\"></div>\n";
writer.Write(rScript);
if (!Page.ClientScript.IsStartupScriptRegistered("MapInit"))
Page.ClientScript.RegisterStartupScript(typeof(string), "MapInit",
"Init()", true);
}
为了能够修改 Google 地图的属性,我创建了一个 EditorPart
类,允许用户更改 Google API 密钥或 WebPart 的尺寸。
public class GoogleMapEditor : System.Web.UI.WebControls.WebParts.EditorPart
{
TextBox googleKey = new TextBox();
TextBox tbWidth = new TextBox();
TextBox tbHeight = new TextBox();
TextBox tbLat = new TextBox();
TextBox tbLong = new TextBox();
TextBox tbZoom = new TextBox();
CheckBox chkDisplayZoom = new CheckBox();
CheckBox chkDragging = new CheckBox();
CheckBox chkIcon = new CheckBox();
就像标准的 WebPart 一样,编辑器部件必须重写 CreateChildControls
方法来构建用户界面。用户界面通过重写 RenderContents
方法来绘制。
protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write("Google Key <br/>");
googleKey.RenderControl(writer);
writer.Write("<br/>Width<br/>");
tbWidth.RenderControl(writer);
writer.Write("<br/>Height<br/>");
tbHeight.RenderControl(writer);
图 1. 自定义编辑器
结果
图 2. Google 地图 WebPart