ASP.NET(VB.NET)项目按钮点击加载Google Map失败求助
问题描述
开发基于ASP.NET的Google Map项目,后端使用VB.NET。从SQL数据库加载位置数据,序列化后以JSON传递到前端,通过后端调用JavaScript函数加载地图。页面加载事件调用LoadMaps方法时地图显示正常,但按钮点击事件调用该方法时地图无法显示。
相关代码
前端代码
<script type="text/javascript"> // Function to load the map and plot markers for locations function loadMap(locationDataJson) { var locationData = JSON.parse(locationDataJson); var map = new google.maps.Map(document.getElementById('map'), { center: { lat: locationData[0].Latitude, lng: locationData[0].Longitude }, zoom: 16 // Adjust the zoom level as needed }); locationData.forEach(function (location) { // Split the combined latitude and longitude values var [lat, lng] = location.SiteGPSAddress.split(','); // Add a marker for each location var marker = new google.maps.Marker({ position: { lat: parseFloat(lat), lng: parseFloat(lng) }, map: map }); // Add a circle for each location (example radius in meters) var circle = new google.maps.Circle({ center: { lat: parseFloat(lat), lng: parseFloat(lng) }, radius: 100, // Adjust the radius in meters as needed strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35, map: map }); }); } // Call the server-side code to load the data and then load Google Maps API window.onload = function () { // Replace 'YourPageName' with the actual name of your VB.NET page fetch('Clientsiteaddition.aspx') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.text(); }) .then(data => eval(data)) //.then(loadGoogleMapsScript) .catch(function (error) { console.error('Error fetching or parsing data:', error); }); }; </script> <div id="map" style="height: 400px; width: 100%;"></div>
后端VB.NET代码
Protected Sub LoadMaps(sender As Object, e As EventArgs) If Not IsPostBack Then ' Dim connectionString As String = "your_connection_string_here" Dim locationData As List(Of LocationDataItem) = New List(Of LocationDataItem)() ' Using connection As SqlConnection = New SqlConnection(connectionString) Dim query As String = "SELECT LatLong FROM LocationData;" Using command As SqlCommand = New SqlCommand(query, cn) cn.Open() Using reader As SqlDataReader = command.ExecuteReader() While reader.Read() Dim item As LocationDataItem = New LocationDataItem() item.LatLong = Convert.ToString(reader("LatLong")) locationData.Add(item) End While End Using End Using 'End Using ' Split the combined latitude and longitude values For Each item As LocationDataItem In locationData Dim latLongArray As String() = item.LatLong.Split(","c) If latLongArray.Length = 2 Then item.Latitude = Double.Parse(latLongArray(0)) item.Longitude = Double.Parse(latLongArray(1)) End If Next ' Serialize the locationData to JSON and pass it to the client-side Dim jsSerializer As JavaScriptSerializer = New JavaScriptSerializer() Dim locationDataJson As String = jsSerializer.Serialize(locationData) ClientScript.RegisterStartupScript(Me.GetType(), "LoadMap", $"loadMap('{locationDataJson}');", True) End If End Sub
按钮点击事件代码
Protected Sub Button1_Click(sender As Object, e As EventArgs) LoadMaps(sender, e) End Sub
问题分析与解决方案
核心问题
IsPostBack判断阻断逻辑:按钮点击属于PostBack请求,If Not IsPostBack Then会直接跳过所有数据加载和脚本注册逻辑,前端无法收到地图加载指令。- 字段名不匹配:后端序列化的字段是
LatLong,但前端代码中使用location.SiteGPSAddress解析坐标,导致无法获取有效经纬度。 - JSON传递方式错误:直接将JSON字符串包裹在单引号中传递,若JSON含特殊字符会引发JS语法错误;且无需额外调用
JSON.parse,可直接传递JSON对象。 - 脚本注册键重复:固定键
"LoadMap"会导致PostBack后脚本无法重新注册。
修复步骤
1. 移除IsPostBack判断,修改脚本注册逻辑
Protected Sub LoadMaps(sender As Object, e As EventArgs) ' Dim connectionString As String = "your_connection_string_here" Dim locationData As List(Of LocationDataItem) = New List(Of LocationDataItem)() ' Using connection As SqlConnection = New SqlConnection(connectionString) Dim query As String = "SELECT LatLong FROM LocationData;" Using command As SqlCommand = New SqlCommand(query, cn) cn.Open() Using reader As SqlDataReader = command.ExecuteReader() While reader.Read() Dim item As LocationDataItem = New LocationDataItem() item.LatLong = Convert.ToString(reader("LatLong")) locationData.Add(item) End While End Using End Using 'End Using ' Split the combined latitude and longitude values For Each item As LocationDataItem In locationData Dim latLongArray As String() = item.LatLong.Split(","c) If latLongArray.Length = 2 Then item.Latitude = Double.Parse(latLongArray(0)) item.Longitude = Double.Parse(latLongArray(1)) End If Next ' Serialize the locationData to JSON and pass it to the client-side Dim jsSerializer As JavaScriptSerializer = New JavaScriptSerializer() Dim locationDataJson As String = jsSerializer.Serialize(locationData) ' 使用动态键避免重复,直接传递JSON对象而非字符串 ClientScript.RegisterStartupScript(Me.GetType(), "LoadMap_" & DateTime.Now.Ticks, $"loadMap({locationDataJson});", True) End Sub
2. 修复前端字段名匹配与JSON解析逻辑
function loadMap(locationData) { // 无需JSON.parse,直接使用传入的对象数组 var map = new google.maps.Map(document.getElementById('map'), { center: { lat: locationData[0].Latitude, lng: locationData[0].Longitude }, zoom: 16 }); locationData.forEach(function (location) { // 修正字段名为后端的LatLong var [lat, lng] = location.LatLong.split(','); var marker = new google.maps.Marker({ position: { lat: parseFloat(lat), lng: parseFloat(lng) }, map: map }); var circle = new google.maps.Circle({ center: { lat: parseFloat(lat), lng: parseFloat(lng) }, radius: 100, strokeColor: '#FF0000', strokeOpacity: 0.8, strokeWeight: 2, fillColor: '#FF0000', fillOpacity: 0.35, map: map }); }); } // 移除冗余的fetch逻辑,PostBack后注册的脚本会自动执行 window.onload = function () {};
3. 确保Google Maps API正确引入
在页面<head>中添加API脚本(替换为你的密钥):
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_MAPS_API_KEY"></script>
内容的提问来源于stack exchange,提问作者McVision Richard
相关产品推荐
相关产品推荐

