阿源哥哥有發表過一篇「
在ASP.NET MVC中使用Google地圖」,我改寫為VB版本。
首先,你必須去申請Google API Key;
在「模組」中撰寫VB的延伸方法;
01 | Imports System.Runtime.CompilerServices |
03 | Imports System.Web.Configuration |
04 | Imports System.Web.Helpers |
06 | Public Module GoogleMapExtension |
18 | Public Function GoogleMap(helper As HtmlHelper, address As String , mapWidth As Integer , mapHeight As Integer ) As MvcHtmlString |
19 | Dim mapHtml = New StringBuilder() |
21 | mapHtml.Append(<span style= "color: #a31515;" > "<div id=" "map" " style=" "width:" </span> & mapWidth.ToString() & <span style= "color: #a31515;" > "px; height:" </span> & mapHeight.ToString() & <span style= "color: #a31515;" > "px" "></div>" </span>) |
23 | mapHtml.Append(<span style= "color: #a31515;" > "<script src=" "http://maps.google.com/maps?file=api&v=2&key=" "" </span> & <span style= "color: #2b91af;" >WebConfigurationManager</span>.AppSettings(<span style= "color: #a31515;" > "GoogleMapApiKey" </span>) & <span style= "color: #a31515;" > "\"" type= "" text/javascript "" ></script>"</span>) |
25 | mapHtml.Append( "<script type=" "text/javascript" ">" ) |
26 | mapHtml.Append( "var geocoder;" ) |
27 | mapHtml.Append( "var map;" ) |
28 | mapHtml.Append( "var address = '" & address & "';" ) |
29 | mapHtml.Append( "map = new GMap2(document.getElementById(" "map" "));" ) |
30 | mapHtml.Append( "map.addControl(new GLargeMapControl());" ) |
31 | mapHtml.Append( "map.addControl(new GMapTypeControl());" ) |
32 | mapHtml.Append( "geocoder = new GClientGeocoder();" ) |
33 | mapHtml.Append( "geocoder.getLocations(address, addToMap);" ) |
34 | mapHtml.Append( "function addToMap(response) {" ) |
35 | mapHtml.Append( "place = response.Placemark[0];" ) |
36 | mapHtml.Append( "point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);" ) |
37 | mapHtml.Append( "map.setCenter(point, 13);" ) |
38 | mapHtml.Append( "marker = new GMarker(point);" ) |
39 | mapHtml.Append( "map.addOverlay(marker);" ) |
40 | mapHtml.Append( "marker.openInfoWindowHtml(place.address);" ) |
42 | mapHtml.Append( "</script>" ) |
44 | Return MvcHtmlString.Create(mapHtml.ToString()) |
在使用要使用的View中,引用Namespage,然以使用以下指令傳入相關參數即可。
1 | <%: Html.GoogleMap(ViewBag.Address, 400, 350)%> |
上面的程式碼,被Blog用亂了,請直接看檔案。
沒有留言:
張貼留言
感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。