Add HTML class/ID to Google Maps Marker (API V3)

帅比萌擦擦* 提交于 2019-12-23 16:59:40

问题


How can I add a class or ID to a Google Maps API V3 marker? I want to be able to access the markers using jQuery.

EDIT: Hi clarkf, thanks for the response. Using Firebug I'm not able to see those classes when inspecting my map but I did notice there are two divs. One for the icon and one for the button.

What I am trying to do is: I have a list of lost pets displayed on the site, they are also displayed on the map. Each pet in the list has a unique ID, and I want the ones on the map to mirror this ID using a class as ID's need to be unique and there might be several points per pet. So I'm looking for a way of adding a class to a map marker. This way when a user selects a lost pet from the list it'll highlight it on the map or vice-versa.

Thanks

Ric


回答1:


After doing a bit of prodding, I discovered map markers all have the class of gmnoprint (assumed Google Maps No Print). So, I did a maps search for pizza near my house, and in a Chrome's Inspector's Console Window, I:

> var list = document.getElementsByClassName('gmnoprint');
  [...] //length=37
> for ( var i = 0, item; item = list[i]; i++ ) { console.log(item.id); }
  //(11 items with no id)
  mtgt_A.1001
  mtgt_B.1001
  mtgt_C.1001
  mtgt_D.1001
  mtgt_E.1001
  mtgt_F.1001
  mtgt_G.1001
  mtgt_H.1001
  mtgt_I.1001
  mtgt_J.1001
  mtgt_A.1000
  map_overview
  //Irrelevant information...

All of the visible markers were in the format of mtgt_[LETTER].1001. The numeral suffix seems to have something to do with multiple sets of lettered markers (mtgt_A.1000 was a hidden marker - maybe the place wasn't open, or something. But all pertinent markers followed that schema. So, presumably, you should be able to access the markers via jQuery with $('#mtgt_[LETTER].1001') - again, depending on your context, but maybe what you're looking for is

function getMarker(letter) {
    return $('mtgt_'+letter+'.1000');
}

Sort of ad-hoc-y, but I'm still not sure what you're getting at.




回答2:


Not managed to get this to work. Not sure it's possible yet. I did hack around it though as my markers were stored in an array along with the item I wanted to link to them. So I could say if the first item was clicked, then highlight the marker for the first item of the array. A bit crude, and it'll break if a system needed several markers for one item but it works now. If you're wondering what I am talking about it's here: http://www.isabellevetslostpets.com/page/search-for-a-lost-pet

Search for lost pets and click a result (sadly no one is uploading photos!). The results are stored in the same array (a JSON object loaded via AJAX - Firebug it to see) as the marker info so that's how I tie them together.



来源:https://stackoverflow.com/questions/4006511/add-html-class-id-to-google-maps-marker-api-v3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!