开发者

Using jQuery and Rails to display data on a Google Map

开发者 https://www.devze.com 2023-01-01 20:03 出处:网络
I\'m having trouble getting JSON data from my R开发者_如何学Goails app to display on a Google Map using jQuery. In my controller:

I'm having trouble getting JSON data from my R开发者_如何学Goails 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!


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


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!

0

精彩评论

暂无评论...
验证码 换一张
取 消