views:

49

answers:

2

Hi,

I'm having trouble getting JSON data from my Rails app to display on a Google Map using jQuery. In my controller:

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

And then in my map.js file:

$(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(); } );

I've adapted my code from this tutorial - the map displays fine but with none of my markers present (added by hand). I'm using Rails 3 beta 3 and Ruby 1.9.1. The output to JSON seems fine - I can access the data at /places.json. Any help would be much appreciated - thanks in advance!

+1  A: 

Have you tried changing the path in your getJSON call to "/places.json"?

mckeed
Yep, but sadly no joy! Have also tried format.js { :render => @places } in the controller with "/places.js"...
Sonia
A: 

Solved! I didn't realise, but Ruby outputs JSON as a simple array of objects, so json.Places.length is meaningless - json.length works perfectly. The new code is now:

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

All the markers appear as expected!

Sonia