首先,你必須去申請Google API Key;
在「模組」中撰寫VB的延伸方法;
Imports System.Runtime.CompilerServices
Imports System.Web
Imports System.Web.Configuration
Imports System.Web.Helpers
Public Module GoogleMapExtension
''' <summary>
'''
''' </summary>
''' <param name="helper">擴充型別</param>
''' <param name="address">地址</param>
''' <param name="mapWidth">寬度</param>
''' <param name="mapHeight">高度</param>
''' <returns></returns>
''' <remarks></remarks>
<Extension()>
Public Function GoogleMap(helper As HtmlHelper, address As String, mapWidth As Integer, mapHeight As Integer) As MvcHtmlString
Dim mapHtml = New StringBuilder()
mapHtml.Append("<div id=""map"" style=""width:" & mapWidth.ToString() & "px; height:" & mapHeight.ToString() & "px""></div>")
mapHtml.Append("<script src=""http://maps.google.com/maps?file=api&v=2&key=""" & WebConfigurationManager.AppSettings("GoogleMapApiKey") & "\"" type=""text/javascript""></script>")
mapHtml.Append("<script type=""text/javascript"">")
mapHtml.Append("var geocoder;")
mapHtml.Append("var map;")
mapHtml.Append("var address = '" & address & "';")
mapHtml.Append("map = new GMap2(document.getElementById(""map""));")
mapHtml.Append("map.addControl(new GLargeMapControl());")
mapHtml.Append("map.addControl(new GMapTypeControl());")
mapHtml.Append("geocoder = new GClientGeocoder();")
mapHtml.Append("geocoder.getLocations(address, addToMap);")
mapHtml.Append("function addToMap(response) {")
mapHtml.Append("place = response.Placemark[0];")
mapHtml.Append("point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);")
mapHtml.Append("map.setCenter(point, 13);")
mapHtml.Append("marker = new GMarker(point);")
mapHtml.Append("map.addOverlay(marker);")
mapHtml.Append("marker.openInfoWindowHtml(place.address);")
mapHtml.Append(" }")
mapHtml.Append("</script>")
Return MvcHtmlString.Create(mapHtml.ToString())
End Function
End Module
在使用要使用的View中,引用Namespage,然以使用以下指令傳入相關參數即可。
<%: Html.GoogleMap(ViewBag.Address, 400, 350)%>
上面的程式碼,被Blog用亂了,請直接看檔案。
沒有留言:
張貼留言
感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。