Javascript 在 Google Maps API 3 中获取标记的 DOM 元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2065485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 22:38:20  来源:igfitidea点击:

Get DOM Element of a marker in Google Maps API 3

javascriptgoogle-mapsdom

提问by fredrik

I'm trying to find a way to get the DOM element of a marker. It seems that Google uses different elements for showing a marker and one of handling the event.

我试图找到一种方法来获取标记的 DOM 元素。似乎谷歌使用不同的元素来显示标记和处理事件。

I've figured out 2 things so far. There's a generated variable called fbthat holds the DOM element on a marker object, but I think the next time Google updates the API, it will be named something different. So no go.

到目前为止,我已经弄清楚了两件事。有一个名为的生成变量fb,用于保存标记对象上的 DOM 元素,但我认为下次 Google 更新 API 时,它会被命名为不同的名称。所以没去。

Second, if one attach a click event to a marker the API send the event DOM element as arguments to what ever function you have specified. While looking through it in Firebug I can't find any relations between the two.

其次,如果将点击事件附加到标记上,API 会将事件 DOM 元素作为参数发送到您指定的任何函数。在 Firebug 中查看它时,我找不到两者之间的任何关系。

What I'm trying to accomplish is to manipulate the DOM element() and feed it more information then just a 'div' element with a background.

我想要完成的是操纵 DOM element() 并向它提供更多信息,然后只是一个带有背景的“div”元素。

I've done this in version 2 using a name property(undocumented) that generates an id on the div element.

我在第 2 版中使用 name 属性(未记录)完成了此操作,该属性在 div 元素上生成一个 id。

Does anyone have an idea?

有没有人有想法?

采纳答案by fredrik

I found a really really bad workaround. One can use the title attribute to pass a id property.

我发现了一个非常糟糕的解决方法。可以使用 title 属性来传递 id 属性。

fixMarkerId = function () {
                $('div[title^="mtg_"]').each(function (index, elem) {
                    el = $(elem);
                    el.attr('id', el.attr('title'));
                    el.removeAttr('title');
                });
            },
            tryAgainFixMarkerId = function () {
                if ($('div[title^="mtg_"]').length) {
                    fixMarkerId();
                } else {
                    setTimeout(function () {
                        tryAgainFixMarkerId();
                    }, 100);
                };
            }

if ($('div[title^="mtg_"]').length) {
                fixMarkerId();
            } else {
                setTimeout(function () {
                    tryAgainFixMarkerId();
                }, 100);
            };

I would strongly not recommend this solution for any production environment. But for now I use it so that I can keep developing. But still looking for a better solution.

我强烈不建议将此解决方案用于任何生产环境。但现在我使用它,以便我可以继续开发。但仍在寻找更好的解决方案。

回答by BenjyCook

I've found this method to be useful, although it might not be suitable for all environments. When setting the marker image, add a unique anchor to the URL. For example:

我发现这种方法很有用,尽管它可能并不适合所有环境。设置标记图像时,向 URL 添加唯一的锚点。例如:

// Create the icon
var icon = new google.maps.MarkerImage(
    "data/ui/marker.png",
    new google.maps.Size(64, 64),
    new google.maps.Point(0,0),
    new google.maps.Point(48, 32)
);

// Determine a unique id somehow, perhaps from your data
var markerId = Math.floor(Math.random() * 1000000);
icon.url += "#" + markerId;

// Set up options for the marker
var marker = new google.maps.Marker({
    map: map,
    optimized: false,
    icon: icon,
    id: markerId,
    uniqueSrc: icon.url
});

Now you have a unique selector i.e.:

现在你有一个独特的选择器,即:

$("img[src='data/ui/marker.png#619299']")

or if you have the marker:

或者如果你有标记:

$("img[src='" + marker.uniqueSrc + "']")

回答by Matt

I was looking for the DOM element too in order to implement a custom tooltip. After a while digging into google overlays, custom libraries and so on, i've ended up with the following solution based on fredrik's title approach (using jQuery) :

我也在寻找 DOM 元素以实现自定义工具提示。经过一段时间深入研究谷歌覆盖、自定义库等,我最终得到了基于 fredrik 的标题方法(使用 jQuery)的以下解决方案:

google.maps.event.addListener(marker, 'mouseover', function() {

    if (!this.hovercardInitialized) {

        var markerInDOM = $('div[title="' + this.title + '"]').get(0);

        // do whatever you want with the DOM element

        this.hovercardInitialized = true;
    }

});

Hope this helps someone.

希望这可以帮助某人。

回答by user2806330

  1. Customize overlays (by implements onAdd, draw, remove) while drag it has some issues.
  2. Maybe you can get the marker dom element by the class name gmnoprintand the index it has been appended in.
  1. 在拖动时自定义叠加层(通过实现 onAdd、draw、remove)有一些问题。
  2. 也许你可以通过类名gmnoprint和它所附加的索引来获取标记 dom 元素。

回答by Mehyar Sawas

I have checked that google maps marker click event has a MosueEvent property in it and the target of the mouse event is the dom element of the marker.

我已经检查过 google maps 标记单击事件中有一个 MosueEvent 属性,并且鼠标事件的目标是标记的 dom 元素。

It worked for me until i found out that the property name has changed from tb to rb. I did not know why and I could not find an explaination for that in the google maps api docs but I have created a work around.

它对我有用,直到我发现属性名称已从 tb 更改为 rb。我不知道为什么,我在 google maps api docs 中找不到对此的解释,但我已经创建了一个解决方法。

I check the click event object properties for the one which is an instance of MouseEvent and I use its target as the marker dom element.

我检查作为 MouseEvent 实例的单击事件对象属性,并将其目标用作标记 dom 元素。

marker.addListener('click', (e) => {

      let markerElement;

   // with underscore
    _.toArray(markerClickEvent).some(item => {
        if (item instanceof MouseEvent) {
            markerElement = item.target;
            return true;
        }
    });
  // or maybe with for loop
for (let key in markerClickEvent) {
        if (markerClickEvent.hasOwnProperty(key) && markerClickEvent[key] instanceof MouseEvent) {
            markerElement = markerClickEvent[key].target;
            break;
        }
    }
});