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
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
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.