在ASP.NET MVC中使用Google地圖(Visual Basic版本)

阿源哥哥有發表過一篇「在ASP.NET MVC中使用Google地圖」,我改寫為VB版本。

首先,你必須去申請Google API Key;

在「模組」中撰寫VB的延伸方法;
01Imports System.Runtime.CompilerServices
02Imports System.Web
03Imports System.Web.Configuration
04Imports System.Web.Helpers
05 
06Public Module GoogleMapExtension
07 
08    ''' <summary>
09    '''
10    ''' </summary>
11    ''' <param name="helper">擴充型別</param>
12    ''' <param name="address">地址</param>
13    ''' <param name="mapWidth">寬度</param>
14    ''' <param name="mapHeight">高度</param>
15    ''' <returns></returns>
16    ''' <remarks></remarks>
17    <Extension()>
18    Public Function GoogleMap(helper As HtmlHelper, address As String, mapWidth As Integer, mapHeight As Integer) As MvcHtmlString
19        Dim mapHtml = New StringBuilder()
20 
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>)
22  
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>)
24 
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);")
41        mapHtml.Append(" }")
42        mapHtml.Append("</script>")
43 
44        Return MvcHtmlString.Create(mapHtml.ToString())
45    End Function
46 
47End Module

在使用要使用的View中,引用Namespage,然以使用以下指令傳入相關參數即可。
1<%: Html.GoogleMap(ViewBag.Address, 400, 350)%>

上面的程式碼,被Blog用亂了,請直接看檔案。

沒有留言:

張貼留言

感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。