javascript 将 ID 添加到 Google Map Marker 然后将其定位

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18129052/
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-10-27 10:48:59  来源:igfitidea点击:

Adding an ID to Google Map Marker then targeting it

javascriptjquerygoogle-mapsgoogle-maps-api-3

提问by styler

I've created a google map using the Google Maps API v3 and have added a custom marker, I have added an ID to the Marker constructor which I am hoping to target with additional JS using jQuery, at the moment however when I simply try something like $( '#'+marker.id ).hide(); nothing happens?

我已经使用 Google Maps API v3 创建了一个谷歌地图并添加了一个自定义标记,我已经向 Marker 构造函数添加了一个 ID,我希望使用 jQuery 以其他 JS 为目标,但是当我只是尝试一些东西时像 $( '#'+marker.id ).hide(); 没发生什么事?

Could anyone advise me on how to properly access this marker id?

谁能建议我如何正确访问此标记 ID?

My maker code is as follows:

我的制造商代码如下:

marker = new google.maps.Marker({
            externalURL: 'http://www.google.com',
            position: defaults.center,
            map: map,
            icon: markerImg,
            id: 'marker'
        });

and then I use the following code to create a jQuery object to target:

然后我使用以下代码创建一个 jQuery 对象作为目标:

var mapMarker = $( '#'+marker.id );
    mapMarker.hide();

回答by Xion Dark

After creating a marker with

创建标记后

var myMarker = new google.maps.Marker({
                   externalURL: 'http://www.google.com',
                   position: defaults.center,
                   map: map,
                   icon: markerImg,
                   id: 'marker'
               });

To remove it from the map, use:

要将其从地图中删除,请使用:

myMarker.setMap(null);

To hide the marker marker from view, use:

要从视图中隐藏标记标记,请使用:

myMarker.setVisible(false);

If you need to have a lot of markers to access later, consider:

如果您需要稍后访问大量标记,请考虑:

var allMyMarkers = [];
allMyMarkers.push( myMarker );

To access a specific id, consider:

要访问特定 ID,请考虑:

for(var i=0;i<allMyMarkers.length;i++){
    if(allMyMarkers[i].id === "marker"){
        allMyMarker[i].setMap(null);
        break;
    }
}

回答by manwe

If you want to just hide the marker use this:

如果您只想隐藏标记,请使用以下命令:

marker.setMap(null);

Is that solution for your problem ?

那是您问题的解决方案吗?