ambe5960
ambe5960

Reputation: 2000

Change google map icon with jQuery drop down menu

So I have a google map with a number of different marker icons available for a user to select via a drop down menu:

<div class="btn-group white">
  <a id="location-type-menu-button" class="btn btn-primary dropdown-toggle" data-    toggle="dropdown" href="#" >Select a Country <span class="caret"></span></a>
         <ul id="location-type-menu" class="dropdown-menu">
                <li><a value="ItemI" href="#">Item I</a></li>
                <li><a value="ItemII" href="#">Item II</a></li>
                <li><a value="ItemIII" href="#">Item III</a></li>             </ul>
</div>

Right now, when the drop down menu is selected, it changes the text of the button via this bit of jquery:

$(window).load(function () {
            $("#location-type-menu li a").click(function () {
                $("#location-type-menu-button:first-child").text($(this).text());
                $("#location-type-menu-button:first-child").val($(this).text());
            });

        });

but I would also like it to instantly change the icon on the google map. The google map marker is created by, and is initially set as a question mark icon.

 var customIcons = {
            ItemI: {
                icon: 'http://...'
            },
            ItemII: {
                icon: 'http://...'
            },
            ItemIII: {
                icon: 'https:...'
            },
            question: {
                icon: 'https:...'
            }
};
var icon = customIcons['question'] || {};
var marker = new google.maps.Marker({
                position: location,
                icon: icon.icon,
                map: map,
                draggable: true
            });

As the icon variable is only called in when creating a new marker, I suspect changing the icon variable is not the way to do this.

I have tried a couple of different things, but have opted not to include them here as I don't think they are along the right path to a solution. I sincerely thank you for any help. It is greatly appreciated!

Upvotes: 1

Views: 859

Answers (1)

PeterA
PeterA

Reputation: 121

make sure your marker is defined in 'click' event, then you can just simply update the icon,

e.g.:

marker.setIcon(customIcons['ItemI'].icon);

Upvotes: 1

Related Questions