1

I have a view that generates a map for a specific district (available in @district). My map plotting code is coffeescript available to every page but it needs data available as a set of json files (district1.json, district2.json, etc). The first way I got this working was to load this variable in my view, making it globally available.

# in my view
<script type="text/javascript">
    var d_data = <%= render file: "#{Rails.root}/data/district_data/#{@district}.json" %>
</script>

Then I use the following coffeescript accepting this global variable:

$(document).ready ->
  if $("#users-district-display")
    myLatLng = new google.maps.LatLng(d_data.centroid.lat,d_data.centroid.lon)

This works well for this page, but I now throw errors on all pages that don't define d_data. Also, I made these json files available at mysite.com/district_data and was thinking of using .get to bring in the data from ajax (and let the view load quickly), but I still have to the the @district parameter in there.

I know I could just render the js as a partial, and am going to do that unless I can find a way to make this coffeescript work.

Any thoughts appreciated.

Regards,

Tim

1 Answer 1

1

Why don't you just check to see if the data was defined?

$(document).ready ->
  if $("#users-district-display") and d_data
    myLatLng = new google.maps.LatLng(d_data.centroid.lat,d_data.centroid.lon)

Also, if you want to create a new LatLng object with zero parameters, you can always use the existential operator (?):

$(document).ready ->
  if $("#users-district-display")
    myLatLng = new google.maps.LatLng(
      d_data?.centroid.lat || 0
      d_data?.centroid.lon || 0
    )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.