Introduction
This article presents a Google map WebPart.
Using the code
The rendering on the Google map control is performed in the WebPart Render
event. The Google map control is initialized using the ClientScriptManager
object.
protected override void Render(HtmlTextWriter writer)
{
string rScript = "";
rScript += "<script src=\"http:
m_rGoogleKey + "\"\n type=\"text/javascript\"></script>\n";
rScript += "<script type=\"text/javascript\">\n";
rScript += "
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 += "
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);
}
In order to be able to modify the Google map properties, I created an EditorPart
class, allowing the user to change the Google API key or the dimensions of the 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();
Just like a standard WebPart, editor parts must override the CreateChildControls
to build a user interface. The user interface is drawn by overriding the RenderContents
method.
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);
Figure 1. Custom Editor
Result
Figure 2. Google Map WebPart