【发布时间】:2017-05-11 12:33:33
【问题描述】:
我有一个无法解决的问题。如果我对数组进行硬编码(在附加代码中注释掉)并忽略 ajax 调用,则 map 函数有效。但是,从 ajax 调用构建数组并没有任何反应。我认为它一定是数组本身,但我看不出有什么问题。
这是我刚刚添加测试表的服务器端代码
[System.Web.Services.WebMethod]
public static string GetLocations()
{
DataTable dtSource = new DataTable();
dtSource.Columns.Add("address", typeof(string));
dtSource.Rows.Add("CM0 8JH");
dtSource.Rows.Add("SE14 5RU");
DataTable dtLatLng = new DataTable();
dtLatLng.Columns.Add("lat", typeof(string));
dtLatLng.Columns.Add("lng", typeof(string));
foreach (DataRow row in dtSource.Rows)
{
DataTable dtWork = GetLatLng(row[0].ToString());
foreach (DataRow rowwork in dtWork.Rows)
{
dtLatLng.Rows.Add(rowwork[2], rowwork[3]);
dtWork = null;
}
}
return ConvertDataTabletoString(dtLatLng);
}
public static string ConvertDataTabletoString(System.Data.DataTable dt)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (System.Data.DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (System.Data.DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
public static DataTable GetLatLng(string address)
{
string url = "https://maps.googleapis.com/maps/api/geocode/xml?address=" + address + "&key=AIzaSyBWQFCssXf-cic6HMYiRncde_4r9Paq9JY";
System.Net.WebRequest request = System.Net.WebRequest.Create(url);
using (System.Net.WebResponse response = (System.Net.HttpWebResponse)request.GetResponse())
{
using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
{
DataSet dsResult = new DataSet();
dsResult.ReadXml(reader);
DataTable dtCoordinates = new DataTable();
dtCoordinates.Columns.AddRange(new DataColumn[4] { new DataColumn("Id", typeof(int)),
new DataColumn("Address", typeof(string)),
new DataColumn("Latitude",typeof(string)),
new DataColumn("Longitude",typeof(string)) });
foreach (DataRow row in dsResult.Tables["result"].Rows)
{
string geometry_id = dsResult.Tables["geometry"].Select("result_id = " + row["result_id"].ToString())[0]["geometry_id"].ToString();
DataRow location = dsResult.Tables["location"].Select("geometry_id = " + geometry_id)[0];
dtCoordinates.Rows.Add(row["result_id"], row["formatted_address"], location["lat"], location["lng"]);
}
return dtCoordinates;
}
}
}
这是客户端代码,我在其中交替注释掉硬编码数组并调用 ajax 调用
<style>
#map {
height: 500px;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script type="text/javascript">
function initMap() {
var locations = [];
//var locations = [
// { "lat": 51.6286544, "lng": 0.8193251 },
// { "lat": 51.4826440, "lng": -0.0473788 }
//]
$.ajax({
type: "POST",
url: "SecretSquirrel.aspx/GetLocations",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
data = $.parseJSON(data.d);
$.each(data, function (i, item) {
locations.push({
"lat": item.lat,
"lng": item.lng
});
//alert(locations[i].lng);
});
}
});
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: {
lat: 51.5074,
lng: 0.1278
}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function (location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers, {
imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'
});
}
</script>
<script type="text/javascript" src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script type="text/javascript" async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBWQFCssXf-cic6HMYiRncde_4r9Paq9JY&callback=initMap">
</script>
我已经搜索了论坛,所以我不只是把这个放在不让自己筋疲力尽的情况下!!!谁能指出可能是愚蠢的错误????
【问题讨论】:
-
var markers = locations.map由于 AJAX 是异步的,这将在您有任何位置之前运行。断点这一行,我 100% 确定数组将为空。 -
@George - 应该回答这个问题:)
-
您有 2 个选项设置 async: false 用于 ajax 调用或调用位置,在调用 .each 后映射到 ajax 的成功函数中,更好地在成功时调用单独的函数并将剩余的其中地图初始化代码
-
@KarthikGanesan 让 AJAX 同步从来都不是什么好建议。
-
我在成功部分添加了尾随代码,数组已填充但仍然没有显示!!
标签: javascript jquery arrays ajax