2010-06-02 40 views
2

我無法從我的Rails應用程序獲取JSON數據以顯示在使用jQuery的Google地圖上。在我的控制器:使用jQuery和Rails在谷歌地圖上顯示數據

class PlacesController < ApplicationController 

    respond_to :html, :xml, :json 

    # GET /places 
    # GET /places.xml 
    # GET /places.json 
    def index 
    @places = Place.all 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render :json => @places } 
     format.xml { render :xml => @places } 
    end 
    end 

然後在我的map.js文件:

$(document).ready(function(){ 
    if (GBrowserIsCompatible()) { 
    var map = new google.maps.Map2($("#map").get(0)); 
     var burnsvilleMN = new GLatLng(44.797916,-93.278046); 
     map.setCenter(burnsvilleMN, 8); 
     map.setUIToDefault(); 

     $.getJSON("/places", function(json) { 
      if (json.Places.length > 0) { 
       for (i=0; i<json.Places.length; i++) { 
        var place = json.Places[i]; 
        addLocation(place); 
       } 
      } 
     }); 

     function addLocation(place) { 
      var point = new GLatLng(place.lat, place.lng);  
      var marker = new GMarker(point); 
      map.addOverlay(marker); 
     } 
     } 
}); 

$(window).unload(function() { GUnload(); }); 

我改編自this tutorial我的代碼 - 在地圖上顯示正常,但有沒有我的存在的標誌(由加手)。我正在使用Rails 3 beta 3和Ruby 1.9.1。輸出到JSON似乎很好 - 我可以訪問/places.json中的數據。任何幫助將非常感謝 - 提前感謝!

回答

1

解決!我沒有意識到,但Ruby輸出JSON作爲一個簡單的對象數組,所以json.Places.length是沒有意義的 - json.length完美地工作。新代碼現在是:

$.getJSON("/places", function(json) { 
    if (json.length > 0) { 
    for (i=0; i<json.length; i++) { 
     var place = json[i]; 
     addLocation(place); 
    } 
    } 
}); 

所有標記都按預期顯示!

1

您是否嘗試將您的getJSON調用中的路徑更改爲「/places.json」?

+0

是的,但可悲的是沒有快樂!在「/places.js」控制器中嘗試了format.js {:render => @places} ... – Budgie 2010-06-02 22:42:00