Skip to content Skip to sidebar Skip to footer

Javascript Can't Find The Image File (rails 4 App)

I have a ruby on rails 4 app. In app/assets/javascripts, I created a file map.js to draw some custom markers on google map: var marker = new google.maps.Marker({ draggable: false

Solution 1:

If you want to use images in your js file then first of all you'll have to change your js file to maps.js.erb and then you can access your assets by rails asset_path which will allow you to access your images , so you can have this in your js file

var marker = new google.maps.Marker({
  draggable: false,
  title: 'Hi',
  icon: "<%= asset_path('icon1.png') %>"//this will look for an image "icon1.png" in assets/images
});

Edit:

Rails asset pipeline basically concatenate assets, which can reduce the number of requests that a browser makes. If you look at rails guides it says

Sprockets concatenates all JavaScript files into one master .js file and all CSS files into one master .css file. Rails inserts an MD5 fingerprint into each filename so that the file is cached by the web browser

So you can't specify your assets path by a static url for this reason we use rails asset_path which will make proper url for your assets

Solution 2:

You can try to use gem js_assets

In your application.js

//= require app_assets

This directive adds the method asset_path in the global scope.

Add to filter files *.png. To do this, add initizlizer:

# config/initializers/js_assets.rb

JsAssets::List.allow << '*.png'

To get the path to the file icon1.png depending on the environment

var marker = new google.maps.Marker({
    draggable: false,
    title: 'Hi',
    icon: asset_path('icon1.png')
});

Post a Comment for "Javascript Can't Find The Image File (rails 4 App)"