javascript Gmaps.js 从数组中添加/删除标记

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

Gmaps.js add/remove markers from array

javascriptjquerygoogle-mapsgmaps.js

提问by Cosmin

I would like to display or hide some markers when a user click on a checkbox. I'm using Gmaps.jsand the code responsible for this is:

当用户单击复选框时,我想显示或隐藏一些标记。我正在使用Gmaps.js,负责此的代码是:

// Check if the user wants to display points of interest
$("#poi").click(function() {
    var poi_markers = [];

    if ($("#poi").is(':checked')) {
        // Get points of interest and display them on the map
        $.ajax({
            type: "POST",
            url: "/ajax/poi.php",
            dataType: "JSON",
            cache: false,
            success: function(data) {
                $.each(data, function(key, value) {
                    poi_marker = {
                        marker: {
                            lat: value.latitude,
                            lng: value.longitude,
                            icon: '/images/marker-sight.png',
                            infoWindow: {
                                content: value.name
                            }
                        }
                    }
                    poi_markers.push(poi_marker);
                });

                console.log(poi_markers);

                map.addMarkers(poi_markers);
            }
        });
    } else {
        map.removeMarkers(poi_markers);
    }
});

Sample JSON:

示例 JSON:

[{"name":"Biserica Neagra","latitude":"45.640981","longitude":"25.587723"}]

In Firebug I get this error: "uncaught exception: No latitude or longitude defined.".

在 Firebug 中,我收到此错误:“未捕获的异常:未定义纬度或经度。”。

What am I doing wrong?

我究竟做错了什么?

回答by blex

Problem #1

问题#1

The addMarkers()function takes an array of markers as a parameter. But you are giving it an array of objects with a markerproperty. They should be declared that way:

addMarkers()函数将一组标记作为参数。但是你给它一个带有标记属性的对象数组。他们应该这样声明:

poi_marker = {
    lat: value.latitude,
    lng: value.longitude,
    infoWindow: {
        content: value.name
    }
}

Problem #2

问题#2

The removeMarkers()function does not take any parameter because it removes all markers. It should be called that way:

removeMarkers()函数不接受任何参数,因为它删除了所有标记。应该这样称呼:

map.removeMarkers();


How to add/remove only groups of markers

如何仅添加/删除标记组

For clarity, and since I think you'll figure out how to do this, I'll omit the Ajax part, and assume you have all your markers defined like this after collecting them:

为清楚起见,并且因为我认为您会弄清楚如何执行此操作,所以我将省略 Ajax 部分,并假设您在收集完所有标记后都像这样定义了它们:

var realMarkers = {},
    gMarkers = {
        bars: [
            {lat:"45.640981",lng:"25.587723",infoWindow:{content:"Irish Pub"}},
            {lat:"45.645911",lng:"25.582753",infoWindow:{content:"Beer King"}}
        ],
        transportation: [
            {lat:"45.645981",lng:"25.590723",infoWindow:{content:"Subway"}},
            {lat:"45.640981",lng:"25.583723",infoWindow:{content:"Train"}},
            {lat:"45.636981",lng:"25.580723",infoWindow:{content:"Airport"}}
        ]
    };

As you can see, I used an Object gMarkerswhere the gstands for Gmaps.js, because these markers are different from real Google Maps markers, which you'll need for this. The real markers will be stored in the realMarkersvariable.

如您所见,我使用了一个对象gMarkers,其中g代表Gmaps.js,因为这些标记与真正的 Google Maps 标记不同,您需要使用它。真正的标记将存储在realMarkers变量中。

Since Gmaps.js does not provide a way to add/remove only some markers, I created 2 functions, which you can add to your code.

由于 Gmaps.js 不提供仅添加/删除某些标记的方法,因此我创建了 2 个函数,您可以将它们添加到您的代码中。

addMarkersOfType()

addMarkersOfType()

/* Takes the poi type as a parameter */

GMaps.prototype.addMarkersOfType = function (poi_type) {
    // clear markers of this type
    realMarkers[poi_type]=[];
    // for each Gmaps marker
    for(var i=0; i<gMarkers[poi_type].length; i++){
        // add the marker
        var marker = map.addMarker(gMarkers[poi_type][i]);
        // save it as real marker
        realMarkers[poi_type].push(marker);
    }
}

removeMarkersOfType()

removeMarkersOfType()

/* Takes the poi type as a parameter */

GMaps.prototype.removeMarkersOfType = function (poi_type) {
    // for each real marker of this type
    for(var i=0; i<gMarkers[poi_type].length; i++){
        // remove the marker
        realMarkers[poi_type][i].setMap(null);
    }
    // clear markers of this type
    realMarkers[poi_type]=[];
}

Example use

示例使用

$("#bar_poi").click(function() {
    if ($(this).is(':checked')) 
        map.addMarkersOfType("bars");
    else 
        map.removeMarkersOfType("bars");
});

JS Fiddle Demo

JS小提琴演示

回答by Pablo

Another solution could be use the method setVisible(true|false)to show or hide the marker without remove it from map.

另一种解决方案是使用该方法setVisible(true|false)来显示或隐藏标记而不将其从地图中删除。