0

I have two variables, <%= @user.lat %> and <%= @user.lng %>

These variables change depending on the user whose logged into my system - it's the address the user gave when registering with my app.

In a scripts.js file I've been trying to define them, so my Google map can show with the user's latitude and longitude.

But

function initialize_google_maps() {
    var currentlatlng = new google.maps.LatLng(<%= @user.lat %>, <%= @user.lng %>);

etc, etc doesn't work, because it can't understand my ruby code.

I tried defining them at the top of the scripts.js file like:

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

and then using:

  function initialize_google_maps() {
    var currentlatlng = new google.maps.LatLng(map_latitude, map_longitude);

but I've learnt that you just can't put ruby in a js file. I did try renaming it to scripts.js.erb but that didn't work either.

So, how can I define <%= @user.lat %> and <%= @user.lng %> so they'll be recognised by my scripts.js file, and show up in my maps? I did try this answer here, creating a partial, but it didn't work for me. Maybe I was doing it wrong.

Please note: I can't simply put the code and maps function between script tags in a html.erb file because I'm using some ajax, and things get messed up - the ruby variables need to be recognised by the js file. Thanks.

4 Answers 4

6

It's possible to use Ruby in JavaScript file, but it's not recommended so I will not explain how.

To answer your question, you can just put the variable in your HTML attribute:

<div id="foo" data-lat="<%= @user.lat %>">Books are coming soon!</div>

And then extract it with JavaScript:

var lat = $("#foo").data("lat");
Sign up to request clarification or add additional context in comments.

2 Comments

Do you mean just define <div id="foo" data-lat="<%= @user.lat %>"></div> in my js file, then map_latitude = $("#foo").data("lat");, and then use the variable map_latitude in my google maps function?
I mean to write <div id="foo" data-lat="<%= @user.lat %>"></div> in your .html.erb file. JavaScript can access HTML attributes, so them can be used to pass data between Ruby and JavaScript.
1

http://railscasts.com/episodes/324-passing-data-to-javascript will get you going in the right direction.

1 Comment

Those videos were very helpful.
0

I think unobtrusive javascript is probably a good way to do this:

http://railscasts.com/episodes/205-unobtrusive-javascript

Comments

0

As the others suggested, you should aim for unobtrusive javascript.

Yet, you might want to use embedded javascript code in a js response for a view, for example. In this cases, you should use the erb extension in your javascript files, so the correct is.js.erb.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.