2013-02-05 31 views
0

我創建了一個Google地圖,該地圖從JSON文件加載標記,並在頁面首次加載時繪製它們。這一點功能正常工作。但是,我的頁面還包含一個表單,我希望在提交表單以更新地圖時再次觸發getJSON請求。這是我無法工作的一點。任何人都可以看到我做錯了什麼?重新載入表單上的Google地圖提交

<!doctype html> 

<html lang="en"> 
    <head> 
     <script src="http://maps.google.com/maps/api/js?sensor=false"></script> 
     <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> 
     <script src="jquery.ui.map.js"></script> 
     <script> 
      // convert form parameters sent using getJSON method to JSON 
      $.fn.serializeObject = function() { 
       var o = {}; 
       var a = this.serializeArray(); 
       $.each(a, function() { 
        if (o[this.name]) { 
         if (!o[this.name].push) { 
          o[this.name] = [o[this.name]]; 
         } 
         o[this.name].push(this.value || ''); 
        } else { 
         o[this.name] = this.value || ''; 
        } 
       }); 
       return o; 
      };   

      $(function() { 
       // method to initialise map 
       function initialise() { 
        $('#map_canvas').gmap({ 
         'disableDefaultUI':true, 'callback': function() { 
          var self = this; 
          $.getJSON('http://localhost:8888/googlemaps/demo.json', 
           $('#filter').serializeObject(), 
           function(data) { 
            $.each(data.markers, function(i, marker) { 
             self.addMarker({ 'position': new google.maps.LatLng(marker.latitude, marker.longitude), 'bounds':true }).click(function() { 
              self.openInfoWindow({ 'content': marker.content }, this); 
             }); 
            }); 
           } 
          ); 
         } 
        }); 
       } 

       // initial map on page load 
       initialise(); 

       // reinitialise map on form submit 
       $('#filter').submit(function(e) { 
        initialise(); 
        e.preventDefault(); 
       });   
      }); 
     </script> 
    </head> 

    <body> 
     <form id="filter"> 
      <select name="foo" id="foo"> 
       <option value="1">1</option> 
       <option value="2">2</option> 
       <option value="3">3</option> 
      </select> 

      <select name="bar" id="bar"> 
       <option value="1">1</option> 
       <option value="2">2</option> 
       <option value="3">3</option> 
      </select> 

      <input type="submit"> 
     </form> 

     <div id="map_canvas" style="height:400px; width:100%;"></div> 
    </body> 
</html> 

回答

2

調用destroy - 地圖的方法,然後再次初始化它。

1

"AJAX" Philosophy(來自Mike Williams的v2教程)將離開地圖(不要重新初始化它),只需更改顯示的數據(標記)即可。

將地圖創建從標記中分離出來,在加載頁面時初始化地圖並調用您的.getJSON作爲原始數據。在表單提交(或按鈕單擊)上,刪除所有標記並再次調用.getJSON,從表單中傳遞適當的數據。

0

謝謝Linuxios。這工作。修改參考代碼:

$('#filter').submit(function(e) { 
    $('#map_canvas').gmap('destroy'); 
    initialise(); 
    e.preventDefault(); 
}); 

我也將當前時間附加到getJSON URL以防止緩存。

$.getJSON('http://localhost:8888/googlemaps/demo.json?' + new Date().getTime()