user6434390
user6434390

Reputation:

How to get rails image location in javascript file

I have an image in app/assets/images/ folder which is named map-marker.png. I need to get the image location in my javascript file to use it as a map marker.

 var image  = "map-marker.png";
    var beachMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image
    });

Upvotes: 2

Views: 932

Answers (2)

Khanh Pham
Khanh Pham

Reputation: 2973

You have two solutions to make it.

Case1:

var image  = "/assets/map-marker.png";
var beachMarker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: image
});

Case2:

You save your original file (your_script.js) as (your_script.js.erb) with the image path helper:

var image  = "<%= asset_path('map-marker.png') %>";
var beachMarker = new google.maps.Marker({
    position: myLatLng,
    map: map,
    icon: image
});

You can refer document at: http://guides.rubyonrails.org/asset_pipeline.html

Upvotes: 1

Harry Bomrah
Harry Bomrah

Reputation: 1668

You can directly use /assets/map-marker.png in your js file. It will work.

Upvotes: 1

Related Questions