谷歌地图不工作,位置数组?

时间:2017-05-11 12:33:33

标签: javascript jquery arrays ajax

我遇到了无法解决的问题。如果我对数组进行硬编码(在附加代码中注释掉)并忽略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>

我搜索了论坛,所以我不仅仅是把它放在一边而不是让自己筋疲力尽!任何人都可以指出可能是愚蠢的错误????

1 个答案:

答案 0 :(得分:-1)

var markers = locations.map由于AJAX异步,这将在你有任何位置之前运行。

此外,您的latlng将作为字符串而不是数字传递。

JSFiddle For Example

要修复它,你可以做这样的事情

function initMap() {
    var locations = [];
    $.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": Number(item.lat),
                    "lng": Number(item.lng)
                });
            });
            createMarkers(map, locations);
        }
    });

    var map = new google.maps.Map(document.getElementById('map'), {
        zoom: 5,
        center: {
            lat: 51.5074,
            lng: 0.1278
        }
    });
}

function createMarkers(map, locations) {
    // 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'
    });
}

我会将标记删除给你并按你的意愿命名。