title: Remove specific markers from a map?
body: <p>I have a Google Map with a bunch of markers.</p>
  
  <p>I add markers to the map one-by-one and need to remove individual markers one-by-one too when required, using individual IDs.</p>
  
  <p>Currently I have some horrible, verbose code, involving a global array of markers, an ID added as metadata to each marker, and a clunky method for looking up a marker's position within the array, as follows:</p>
  
  <pre><code>  var markersArray = [];
    function getPositionById(markerId, arr) { 
        for (var i = 0; i &lt; arr.length; i++) { 
            if (arr[i].metadata.id === markerId) { 
                    return i;
            }
        }
        return null;
    }
    function removeMarker(markerId) { 
        var marker_position = getPositionById(markerId, markersArray);
        if (marker_position !== null) {
            markersArray[marker_position].setMap(null);
            markersArray.splice(marker_position,1);
        }
    }
    function setMarker(position, markerId) {
        removeMarker(markerId);
        var temp_marker = new google.maps.Marker({
            position: position
        });
        temp_marker.setMap(map);
        temp_marker.metadata = { id: markerId };
        markersArray.push(temp_marker);
    }
  </code></pre>
  
  <p>Could anyone suggest an even slightly more elegant way to do it?</p>