HOW TO GET DOMAIN OBJECTS IN JAVASCRIPT WITH RAILS (PART 2)

The next step in the sequence for loading Rails objects in javascript is to dynamically get them from the script. To do this, I’m going to use the JQuery “Get” method. I’ll be hitting the same URL that I set up in the last post.

Once I get the object, I’ll just add a simple alert method to the script, so I can be sure that I loaded the data correctly (or you could use a javascript debugger…).

    $.get("/restaurants/recommendations", function(restaurant) {
      alert("successfully loaded: " + JSON.stringify(restaurant));
    });

Once I’ve confirmed that I have the correct object, I want to get the latitude and longitude values from the object and create a marker on the map that I have already set up.

  $.get("/restaurants/recommendations", function(restaurant) {  
    
    var myMarkerLatLng = new CM.LatLng(restaurant.lattitude, restaurant.longitude);
    var myMarker = new CM.Marker(myMarkerLatLng, {
      title: restaurant.name
    });
    map.addOverlay(myMarker);
    
  });

When I put it all together the entire javascript function looks like this:

$(document).ready(function(){ 
  
  var cloudmade = new CM.Tiles.CloudMade.Web({key: 'my_key'});
  var map = new CM.Map('map_canvas', cloudmade);

  map.setCenter(new CM.LatLng(35.998743, -78.90723), 13);
  map.addControl(new CM.LargeMapControl());

  $.get("/restaurants/recommendations", function(restaurant) {  
    
    var myMarkerLatLng = new CM.LatLng(restaurant.lattitude, restaurant.longitude);
    var myMarker = new CM.Marker(myMarkerLatLng, {
      title: restaurant.name
    });
    map.addOverlay(myMarker);
    
  });
    
    
});

And I get to see my “Watts Grocery” marker on the map.

Tagged , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *