nizniz
nizniz

Reputation: 77

What is the best way to add data redred by Rails controller in Javascript

I am developing a rails application. For my show view I must add gps coordinates, which I have in my model, in a javascript function to display the map. I had to add a method in my controller that I send Ajax requests to get the coordinates. I don't want use GON gem since it's not thread safe, neither Gmap4rails. I am not sure this is the best way I should take : - DRY : I have 2 methods to render the same thing ? - Why I should make an extra call when I have all data in the view?

What's the best way to deal with rails values in Javascript?

Upvotes: 0

Views: 44

Answers (1)

Sravan
Sravan

Reputation: 18647

the easiest and best method to do is jsut add a javascript file in a js and call a function in that js from your view.

function gmap_show(company) {
  if ((company.lat == null) || (company.lng == null) ) {    // validation check if coordinates are there
    return 0;
  }

  handler = Gmaps.build('Google');    // map init
  handler.buildMap({ provider: {}, internal: {id: 'map'}}, function(){
    markers = handler.addMarkers([    // put marker method
      {
        "lat": company.lat,    // coordinates from parameter company
        "lng": company.lng,
        "picture": {    // setup marker icon
          "url": '/assets/images.jpeg',
          "width":  32,
          "height": 32
        },
        "infowindow": "<b>" + company.name + "</b> " + company.address + ", " + company.postal_code + " " + company.city
      }
    ]);
    handler.bounds.extendWith(markers);
    handler.fitMapToBounds();
    handler.getMap().setZoom(12);    // set the default zoom of the map
    // handler.getStreetView().setZoom(12);
  });
}

This is the function for a company object and in you controller show page, add this script with your object.

<div id="map" style="width: 550px; height: 350px;"></div>
<script>
  
  $(document).ready(function(){
    var company =  <%= raw @company.to_json %>      // pass ruby variable to javascript
    gmap_show(company);    // init show map for company card (only print marker)
  });

</script>

This makes a call to that javascript function and the coordinates are displayed.Thats it.Done

Upvotes: 1

Related Questions