0

I have a scripts.js file in my ruby project folder - assets/javascripts, in which I'm trying to render a google map. I can't get my javascript to understand the code between the embedded ruby tags. How should I do it? I thought something like declaring the variables at the top of the page of the scripts.js would work, something like:

var map_latitude = <%= @user.lat %>;
var map_longitude = <%= @user.lng %>;

Here's my code (problem is on the 5th line):

var map;
  var markers = [];

  function initialize_google_maps() {
    var currentlatlng = new google.maps.LatLng(<%= @user.lat %>, <%= @user.lng %>);
    var zoom = <%= @kms_range %> > 9 ? 9 : 10;
    var myOptions = {
        zoom: zoom,
        center: currentlatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP, // ROADMAP, SATELLITE, HYBRID
        streetViewControl: false
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var marker = new google.maps.Marker({map: map, position: currentlatlng, icon:{oppacity:0}});
    map.setCenter(currentlatlng);
    map.setZoom(zoom);

    var circle = new google.maps.Circle({
        map: map,
        fillOpacity: 0,
        strokeWeight: 2,
        strokeOpacity: 0.7,
        radius: <%= @kms_range %>*1000,
    });
    circle.bindTo('center', marker, 'position');

  }

  function show_markers() {
    if (markers)
      for(i in markers) {
        markers[i].setMap(map);
      }
  }

  function add_marker(location) {
    marker = new google.maps.Marker({
      position: location,
      map: map
    });
    markers.push(marker);
    // markers.setVisible(false);
  }

  function initialize_markers() {
    <% (@reviews || []).each do |r| %>
      <% next unless r.lat && r.lng %>
      position = new google.maps.LatLng(<%= r.lat %>, <%= r.lng %>);
      add_marker(position);
    <% end %>
  }

  $(function() {
    initialize_google_maps();
    initialize_markers();
    show_markers();
  });

I'd be grateful for any help, thanks.

CHarris
  • 2,693
  • 8
  • 45
  • 71

1 Answers1

0
var map_latitude = "<%= @user.lat %>";
var map_longitude = "<%= @user.lng %>";

Look at the generated javascript, you might have missing the quotes.

Also, if it is a string, you could do

var map_latitude = <%= p @user.lat %>;
var map_longitude = <%= p @user.lng %>;

But never saw this in a code before

fotanus
  • 19,618
  • 13
  • 77
  • 111
  • where do I declare these variables? Because if I put them at the top of my scripts.js file, my map still doesn't recognise the ruby values. In chrome if I do console.log(map_latitude) I get returned <%= atuser.lat %>, where I should be getting a dynamic latitude value. Thanks. – CHarris May 01 '13 at 14:45
  • The @user variable would need to be loaded first than your javacript get executed, and as pointed by @MrYoshiji, your file must end with `.erb` – fotanus May 01 '13 at 15:00