为什么我不能将数据从ajax传递到谷歌地图

时间:2017-03-01 09:51:59

标签: javascript arrays ajax google-maps google-maps-api-3

我有一个谷歌地图,我想传递一个动态返回的数据数组,以便向地图添加标记,但是当我这样做时,标记不起作用。它只有在我将数据变量传递给函数add_markers()时才有效。 为什么?以及如何解决这个问题?

    function RelatedLocationAjax() {
           var lat = $( "#lat" ).val();
           var lng = $( "#lng" ).val();
           var srv = $( "#ServiceId" ).val();
            var data = [
                ["john","Do this service 1 <a href=''>more</a>",  "29.957051,30.914529", "http://maps.google.com/mapfiles/ms/icons/blue.png"],
                ["peter", "Do this service 1 <a href=''>more</a>", "29.956051,30.913529", "http://maps.google.com/mapfiles/ms/icons/green.png"],
                ["sara","Do this service 1 <a href=''>more</a>","29.955051,30.912529", "http://maps.google.com/mapfiles/ms/icons/red.png"],
            ];
            $.ajax({
                type: "POST",
                url: "<?= base_url() ?>services/closest_locations",
                data:"data="+ '{ "latitude":"'+ lat+'", "longitude": "'+lng+'", "ServiceId": "'+srv+'" }',
                success:function(data) {
// here i pass the data array to add_markers and doesn't work
                    add_markers(data);
                }
            });
        }

        function add_markers(data){
        var marker, i;
        var bounds = new google.maps.LatLngBounds();
        var infowindow = new google.maps.InfoWindow();

        document.getElementById('info').innerHTML = "found " + data.length + " data<br>";
        for (i = 0; i < data.length; i++) {
            var coordStr = data[i][2];
            var coords = coordStr.split(",");
            var pt = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
            bounds.extend(pt);
            marker = new google.maps.Marker({
                position: pt,
                map: map,
                icon: data[i][3],
                address: data[i][1],
                title: data[i][0],
                html: data[i][0] + "<br>" + data[i][1]
            });
            markers.push(marker);
            google.maps.event.addListener(marker, 'click', (function (marker, i) {
                return function () {
                    infowindow.setContent(marker.html);
                    infowindow.open(map, marker);
                }
            })
            (marker, i));
        }
        map.fitBounds(bounds);
    }

1 个答案:

答案 0 :(得分:0)

因为从ajax返回的数据不是数组 它的响应对象