Removing an individual marker from Google Map - AP

2019-08-19 06:39发布

问题:

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});