Google Map API v3 - проблема GET Ajax (Javascript + Jquery) - PullRequest
1 голос
/ 18 марта 2012

Я пытаюсь сделать маркеры загрузки карты - извлеченные из файла XML.Это в настоящее время делает это отлично.Однако я также хочу, чтобы карта перезагружала новые маркеры, основываясь на месяце, прошедшем с гиперссылки.

Когда переменная 'global_month' изменяется по гиперссылке, запрос ajax запускается, и 'data_array' должен быть заполнен новыми данными, основываясь на дате, переданной в оператор if в дальнейшем.Однако он повторно использует содержимое «data_array» и не заполняет его новыми данными.

Я попытался сбросить «global_month» через «global_month = []» в функции «change_date_range», однако -массив, кажется, не пополняется.Я потратил 3 часа, пытаясь понять, где я иду не так, но не могу.Кто-нибудь может помочь?Также есть ли более эффективный способ сделать это?

Большое спасибо за потраченное время!

/////////////////////////////////////////////////

            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="utf-8">  
                <script src="jquery-1.7.1.min.js" type="text/javascript"></script>
                <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
                <script>
                    $(document).ready(function()
                    {
                        $.ajax({
                            type: "GET",
                            url: "driving_test_centers.xml",
                            dataType: "xml",
                            success: parseXml
                        });
                    }); 
                    var global_month = 6;

                    function refetch()
                    {
                        $.ajax({
                            type: "GET",
                            url: "driving_test_centers.xml",
                            dataType: "xml",
                            success: parseXml
                        });
                    };          



                var data_array = [];
                var empty_holder;
                var empty_month;
                var info_date;
                var address1;
                var address2;
                var town;
                var county;
                var postcode;
                var lat;
                var lon;
                var male_pass_percentage1;
                var male_pass_percentage;
                var female_pass_percentage1;
                var female_pass_percentage;
                var the_new_date;
                var infowindow;
                var xml_contents;

                function parseXml(xml)
                {
                    $(xml).find("test_center").each(function()    // look for all of the test centers
                    {

                        center_name = $(this).attr('name');
                        address1 = $(this).find('address1').text();
                        address2 = $(this).find('address2').text();
                        town = $(this).find('town').text();
                        county = $(this).find('county').text();
                        postcode = $(this).find('postcode').text();
                        lat = $(this).find('lat').text();
                        lon = $(this).find('lon').text();

                        $(this).find("date_info").each(function()
                        {

                            info_date = $(this).attr('date');
                            empty_month = $(this).find('month').text();
                            male_pass_percentage = $(this).find('male');
                            male_pass_percentage = male_pass_percentage.find('pass_percentage').text();
                            female_pass_percentage = $(this).find('female');
                            female_pass_percentage = female_pass_percentage.find('pass_percentage').text();


                            if(empty_month == global_month){
                                data_array.push([lat,lon,center_name,info_date,male_pass_percentage,female_pass_percentage]);
                            }
                        });


                    });

                }


                function change_date_range(the_new_date){
                    global_month = the_new_date;
                    refetch();
                    init();
                };  




                </script>
                <script>


                function init() {


                    var options = {  
                        zoom: 5,
                        center: new google.maps.LatLng(55.3781, -3.4360),  
                        mapTypeId: google.maps.MapTypeId.ROADMAP  
                    };
                    var places;
                    places = null;  

                    var map = new google.maps.Map(document.getElementById('map'), options);
                    var bounds = new google.maps.LatLngBounds();

                    var places = data_array;
                    var temp_location;


                    for (var i = 0; i < places.length; i++) {

                        temp_location = new google.maps.LatLng(places[i][0], places[i][1])

                        // Adding the markers
                        var marker = new google.maps.Marker({
                            position: temp_location, 
                            map: map,
                            title: places[i][2]
                        });

                        // Wrapping the event listener inside an anonymous function 
                        // that we immediately invoke and passes the variable i to.
                        (function(i, marker) {

                            // Creating the event listener. It now has access to the values of
                            // i and marker as they were during its creation
                            google.maps.event.addListener(marker, 'click', function() {

                                // Check to see if we already have an InfoWindow  
                                if (!infowindow) {
                                    infowindow = new google.maps.InfoWindow();
                                }

                                // Setting the content of the InfoWindow
                                infowindow.setContent(places[i][2] + "<br />" + global_month + "<br />" + places[i][3] + "<br /><br />Male: " + places[i][4] + "%<br />Female: " + places[i][5] + "%");

                                // Tying the InfoWindow to the marker 
                                infowindow.open(map, marker);

                            });

                        })(i, marker);

                        // Extending the bounds object with each LatLng
                        bounds.extend(temp_location);

                    }

                    // Adjusting the map to new bounding box
                    map.fitBounds(bounds)

                };



                </script>
            </head>
            <body onload="init()">

                    <div id="map" style="width:800px;height:600px"></div>

                    <a href="javascript:change_date_range(7)">click</a>
            </body>
            </html>

/////////////////////////////////////////////////////////////////

XML-файл (небольшая часть):

http://tinypaste.com/198889bb

1 Ответ

0 голосов
/ 18 марта 2012

Вы не очищаете массив data_array ... вы просто продолжаете добавлять к нему. Почему бы вам не добавить data_array = []; в начало функции parseXml

edit: вы также должны очистить маркеры, которые уже были размещены ... хороший способ сделать это проще - если вы добавляете маркеры, удерживаете их в массиве, то можете циклически перемещаться по ним, устанавливая атрибут map каждый к нулю:

for (x=0;x<markers.length;x++) {markers[x].setMap(null);}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...