0

At the moment when my .preview button is clicked it looks at each address in a textarea and then plots it.

I would like to remove the markers each time .preview is clicked as I see that it just plots another marker around the same point as the marker before.

$('.preview').click(function(){    
setAllMap(null);
var temp_addresses = document.getElementById("gps").value.split("\n");
    for(var i=0;i<temp_addresses.length;i++){
        addresses.push(temp_addresses[i]);
        geocoder.geocode( { 'address': temp_addresses[i]}, function(response, status) {
            geocode_results[i] = new Array();
            geocode_results[i]['status'] = status;
            var top_location = response[0];
            var lat = Math.round(top_location.geometry.location.lat() * 1000000)/1000000;
            var lng = Math.round(top_location.geometry.location.lng() * 1000000)/1000000;
            geocode_results[i]['lat'] = lat;
            geocode_results[i]['lng'] = lng;
            geocode_results[i]['l_type'] = top_location.geometry.location_type;
            marker = markers[i] = new google.maps.Marker({
                icon: mapIcon,
                position: new google.maps.LatLng(lat,lng),
                map: map
            });
        });
    }
});

This gives me a console.log() of ReferenceError: setAllMap is not defined

I have tried marker.setMap(null); but I get back TypeError: marker.setMap is not a function

Help is appreciated

Edit.

    var marker = [];

    var addresses = new Array();
    var geocode_results = new Array();
    function setAllMap(map) {
       for (var i = 0; i < marker.length; i++) {
          marker[i].setMap(map);
       }
    }
    $('.preview').click(function(){    
setAllMap(null);
var temp_addresses = document.getElementById("gps").value.split("\n");
    for(var i=0;i<temp_addresses.length;i++){
        addresses.push(temp_addresses[i]);
        geocoder.geocode( { 'address': temp_addresses[i]}, function(response, status) {
            geocode_results[i] = new Array();
            geocode_results[i]['status'] = status;
            var top_location = response[0];
            var lat = Math.round(top_location.geometry.location.lat() * 1000000)/1000000;
            var lng = Math.round(top_location.geometry.location.lng() * 1000000)/1000000;
            geocode_results[i]['lat'] = lat;
            geocode_results[i]['lng'] = lng;
            geocode_results[i]['l_type'] = top_location.geometry.location_type;
            marker = markers[i] = new google.maps.Marker({
                icon: mapIcon,
                position: new google.maps.LatLng(lat,lng),
                map: map
            });
        });
    }
});
4

1 回答 1

0

您需要创建一个 setAllMap 函数(它不是 API 的一部分)......如果标记数组在全局范围内,这应该可以工作。

function setAllMap(map) {
   for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
   }
}

或者你可以把循环放在你调用函数的地方。

于 2013-11-05T15:23:14.537 回答