Bazley
Bazley

Reputation: 2847

Rails Google maps javascript api v3 setIcon() url can't locate image

I'm changing the marker image upon mouseover of an element on the page, using the setIcon() method. It works fine when the url is something like this:

marker.setIcon('https://www.google.com/mapfiles/marker_green.png');

but when I try to get it to find an image in my local application directory, it can't find the image (the original marker image disappears but the new one doesn't appear):

marker.setIcon('images/myMarker.png');

I've tried every possible url (app/assets/images/myMarker.png, /images/myMarker.png, assets/images/myMarker.png, etc), and also placed the image in many different locations, it still doesn't work.

How do I get the javascript to find my png??

Upvotes: 0

Views: 530

Answers (2)

Nicholas.V
Nicholas.V

Reputation: 1936

Assuming that it is an asset pipeline error i.e marker_green.png becomes something like marker_green-336339d13ed7edf253018e0f7f70bee2.png in production. Here are a couple of solutions:

  1. Place the marker_green.png file in a public directory e.g. public/mapfiles/marker_green.png

or

  1. Set a data attribute for the image path on a html element such as the div which loads the map and get is using JS/jQuery. i.e:

HTML:

<div id="map" data-marker-url="<%= asset_url('marker_green.png') %>"></div>

JS:

var markerIcon = $("#map").data('marker-url');
marker.setIcon(markerIcon);

Upvotes: 2

brenzy
brenzy

Reputation: 1986

It sounds like this is an issue with the rails asset pipeline. Here are a few options you can try:

1) Forget about the asset pipeline (not ideal), and move your marker to public/images. marker.setIcon('images/myMarker.png'); should then work.

2) Add the .erb extension to your file, and use asset_url to get the proper asset path when referring to the image: marker.setIcon("<%= asset_url('marker_green.png') %>");

It would be good to read through the asset pipeline documentation to figure out what will work with your configuration.

Upvotes: 1

Related Questions