Removing an individual marker from Google Map - API v3

一笑奈何 提交于 2019-12-25 03:49:13

问题


I want to remove an individual marker from Google map. I am using version 3 API. I know how I can remove all the markers by maintaining a markerArray and setting map null for all.

For removing one by one, I am thinking to make a key value pair combination. So that I give a key and remove the particular marker. I need help over this.

Following is the code, that I use to dram marker:

function geoCodeAddresses(data) {

    var markerInfo = {addressKey: '', marker:''};

    for (var i = 0; i < data.length; i++) {
        myLocation = data[i];

        geocoder.geocode({"address":myLocation}, function (results, status) {

            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({map:map, position:results[0].geometry.location});
                // checkpoint A
                alert(myLocation);
                /*
                markerInfo.addressKey = myLocation;
                markerInfo.marker = marker;*/

                //mArray.push(markerInfo);
            }
        });

    }
}

I will search for addresskey and remove the marker from mArray. But I get last value every time in geocode callback method. And one object got pushed every time. the var myLocation always give me the address of the last index of my array. If I alert it at check point A.

My approach is right?


回答1:


Your problem is this line:

mArray.push(markerInfo);

That doesn't push the values of markerInfo into your array. It pushes a reference to markerInfo into your array. Now, on your next iteration of the loop, when you change the value of markerInfo, it changes the value pointed at by the references in the array too. So your array ends up having elements that all have the same value.

Try this instead:

mArray.push({addressKey:myLocation,marker:marker});

If that doesn't work, then this:

mArray.push({addressKey:data[i],marker:marker});


来源:https://stackoverflow.com/questions/6398979/removing-an-individual-marker-from-google-map-api-v3

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