简体   繁体   English

点击即可更改谷歌地图标记

[英]Change google maps marker on click

Hey I have a product loop where each product has its own data-location="number" 嘿,我有一个产品循环,每个产品都有自己的data-location =“number”

I want to be able to change the marker icon on click of one of the buttons according to its location. 我希望能够根据其位置单击其中一个按钮来更改标记图标。

<button class="btn" data-location="80"></button>
<button class="btn" data-location="81"></button>
<button class="btn" data-location="82"></button>

so that marker with data-location="80" becomes green or changes the image on click 因此,data-location =“80”的标记变为绿色或在点击时更改图像

here is my addMarker function 这是我的addMarker函数

function addMarker(location) {
    location.Position = { 
        lat: parseFloat(location.mapURL.split(',')[0]),
        lng: parseFloat(location.mapURL.split(',')[1]) 
    };

    location.Marker = new google.maps.Marker({
        icon: 'images/map-marker-blue-2.png',
        map: map,
        position: location.Position,
        title: location.name,
    });
}

let me know if you need more info 如果您需要更多信息,请告诉我

You can do with setIcon 你可以用setIcon

 marker.setIcon('newImage.png'); 

You should use an array of markers populated with the marker you create 您应该使用填充了您创建的标记的标记数组

var markers ;
function addMarker(location) {
  location.Position = { 
    lat: parseFloat(location.mapURL.split(',')[0]),
    lng: parseFloat(location.mapURL.split(',')[1]) 
};

location.Marker = new google.maps.Marker({
    icon: 'images/map-marker-blue-2.png',
    map: map,
    position: location.Position,
    title: location.name,
});
markers.push[location.Marker];

} }

then you can use a function on click of the button with a ref to marker id 然后你可以使用一个函数点击按钮并带有ref标记id

<button class="btn" data-location="80" onclick="changeMarker(80);"></button>

function changeMarker(id){
   markers[id].setIcon('newImage.png'); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM