Programming

Google Maps API v3 : 모든 마커를 제거하는 방법?

procodes 2020. 2. 19. 22:15
반응형

Google Maps API v3 : 모든 마커를 제거하는 방법?


Google Maps API v2에서 모든지도 표시를 제거하려면 간단히 다음을 수행 할 수 있습니다.

map.clearOverlays();

Google Maps API v3 에서 어떻게해야 합니까?

상기 찾고 참조 API , 그것은 나에게 불분명하다.


간단히 다음을 수행하십시오.

I. 전역 변수를 선언하십시오.

var markersArray = [];

II. 함수를 정의하십시오.

function clearOverlays() {
  for (var i = 0; i < markersArray.length; i++ ) {
    markersArray[i].setMap(null);
  }
  markersArray.length = 0;
}

또는

google.maps.Map.prototype.clearOverlays = function() {
  for (var i = 0; i < markersArray.length; i++ ) {
    markersArray[i].setMap(null);
  }
  markersArray.length = 0;
}

III. 다음을 호출하기 전에 'markerArray'에서 마커를 푸시하십시오.

markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(){});

IV. 필요한 경우 clearOverlays();또는 map.clearOverlays();기능을 호출하십시오 .

그게 다야 !!


같은 문제입니다. 이 코드는 더 이상 작동하지 않습니다.

수정했습니다 .clearMarkers 메소드를 다음과 같이 변경하십시오.

set_map (null) ---> setMap (null)

google.maps.Map.prototype.clearMarkers = function() {
    for(var i=0; i < this.markers.length; i++){
        this.markers[i].setMap(null);
    }
    this.markers = new Array();
};

https://developers.google.com/maps/documentation/javascript/markers#remove 주제에 대한 세부 사항을 포함하도록 설명서가 업데이트되었습니다.


V3에는 아직 그러한 기능이없는 것 같습니다.

사람들은지도에있는 모든 마커를 배열로 유지하는 것이 좋습니다. 그런 다음 em을 모두 삭제하려면 배열을 루프하여 각 참조에서 .setMap (null) 메서드를 호출하십시오.

자세한 정보 / 코드는이 질문을 참조하십시오.

내 버전 :

google.maps.Map.prototype.markers = new Array();

google.maps.Map.prototype.getMarkers = function() {
    return this.markers
};

google.maps.Map.prototype.clearMarkers = function() {
    for(var i=0; i<this.markers.length; i++){
        this.markers[i].setMap(null);
    }
    this.markers = new Array();
};

google.maps.Marker.prototype._setMap = google.maps.Marker.prototype.setMap;

google.maps.Marker.prototype.setMap = function(map) {
    if (map) {
        map.markers[map.markers.length] = this;
    }
    this._setMap(map);
}

코드는이 코드의 편집 된 버전입니다. http://www.lootogo.com/googlemapsapi3/markerPlugin.html addMarker를 수동으로 호출 할 필요가 없습니다.

찬성

  • 이 방법을 사용하면 코드를 간결하고 한 곳에 보관할 수 있습니다 (네임 스페이스를 오염시키지 않음).
  • 더 이상 마커를 직접 추적 할 필요는 없습니다. map.getMarkers ()를 호출하여지도에서 항상 모든 마커를 찾을 수 있습니다.

단점

  • 내가했던 것처럼 프로토 타입과 래퍼를 사용하면 코드가 Google 코드에 의존하게됩니다. 소스에서 시장을 변경하면 중단됩니다.
  • 당신이 그것을 이해하지 못하면 깨지면 고칠 수 없습니다. 그들이 이것을 깨뜨릴 수있는 것을 바꿀 가능성은 낮지 만 여전히 ..
  • 하나의 마커를 수동으로 제거해도 참조는 여전히 마커 배열에 있습니다. (setMap 메소드를 수정하여 수정할 수는 있지만 여물통 마커 배열을 반복하고 참조를 제거하는 비용)

이것은 원래 질문에 대한 원래의 응답으로 YingYang Mar 11 '14에 15 : 049게시 한 모든 솔루션 중 가장 간단 했습니다.

2.5 년 후 Google지도 v3.18과 동일한 솔루션을 사용하고 있으며 매력처럼 작동합니다.

markersArray.push(newMarker) ;
while(markersArray.length) { markersArray.pop().setMap(null); }

// No need to clear the array after that.

google.maps.Map.prototype.markers = new Array();

google.maps.Map.prototype.addMarker = function(marker) {
    this.markers[this.markers.length] = marker;
};

google.maps.Map.prototype.getMarkers = function() {
    return this.markers
};

google.maps.Map.prototype.clearMarkers = function() {
    for(var i=0; i<this.markers.length; i++){
        this.markers[i].setMap(null);
    }
    this.markers = new Array();
};

V3에 하나가 없다고 생각하므로 위의 사용자 정의 구현을 사용했습니다.

면책 조항 : 나는이 코드를 작성하지 않았지만 코드베이스에 병합 할 때 참조를 유지하는 것을 잊어 버렸습니다.


새 버전 v3에서는 배열을 유지하는 것이 좋습니다. 다음과 같이.

오버레이 개요의 샘플을 참조하십시오 .

var map;
var markersArray = [];

function initialize() {
  var haightAshbury = new google.maps.LatLng(37.7699298, -122.4469157);
  var mapOptions = {
    zoom: 12,
    center: haightAshbury,
    mapTypeId: google.maps.MapTypeId.TERRAIN
  };
  map =  new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

  google.maps.event.addListener(map, 'click', function(event) {
    addMarker(event.latLng);
  });
}

function addMarker(location) {
  marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markersArray.push(marker);
}

// Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

// Shows any overlays currently in the array
function showOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(map);
    }
  }
}

// Deletes all markers in the array by removing references to them
function deleteOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

Google의 데모 갤러리에는 다음과 같은 방법에 대한 데모가 있습니다.

http://code.google.com/apis/maps/documentation/javascript/examples/overlay-remove.html

소스 코드를보고 마커를 추가하는 방법을 볼 수 있습니다.

간단히 말해서 마커를 전역 배열로 유지합니다. 그것들을 지우거나 삭제할 때 배열을 반복하고 주어진 마커 객체에서 ".setMap (null)"을 호출합니다.

그러나이 예는 하나의 '트릭'을 보여줍니다. 이 예에서 "지우기"는 맵에서 해당 항목을 제거하고 배열에 유지하여 애플리케이션이 맵에 신속하게 다시 추가 할 수 있도록합니다. 어떤 의미에서 이것은 "숨김"처럼 작동합니다.

"삭제"도 배열을 지 웁니다.


for (i in markersArray) {
  markersArray[i].setMap(null);
}

IE에서만 작동합니다.


for (var i=0; i<markersArray.length; i++) {
  markersArray[i].setMap(null);
}

크롬, 파이어 폭스, 즉 ...


해결책은 매우 쉽습니다. 다음 방법을 사용할 수 있습니다 marker.setMap(map);.. 여기서 핀이 나타날지도를 정의합니다.

따라서이 null방법 ( marker.setMap(null);)으로 설정하면 핀이 사라집니다.


이제 맵에서 모든 마커를 사라지게하는 동안 함수 마녀를 작성할 수 있습니다.

핀을 배열에 넣고이 markers.push (your_new pin)코드를 사용 하여 다음과 같이 선언하면됩니다 .

// Adds a marker to the map and push to the array.
function addMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markers.push(marker);
}

이것은 기능 마녀가 맵에서 배열의 모든 마커를 설정하거나 숨길 수 있습니다.

// Sets the map on all markers in the array.
  function setMapOnAll(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }

모든 마커를 사라지게하려면 다음을 사용하여 함수를 호출해야합니다 null.

// Removes the markers from the map, but keeps them in the array.
  function clearMarkers() {
    setMapOnAll(null);
  }

그리고 모든 마커를 제거하고 사라지게하려면 다음과 같이 마커 배열을 재설정해야합니다.

// Deletes all markers in the array by removing references to them.
  function deleteMarkers() {
    clearMarkers();
    markers = [];
  }

이것은 내 완전한 코드입니다. 내가 줄일 수있는 가장 간단한 방법입니다. 핵심 Google API로 코드에서 대체 할 수 있도록 주의하십시오YOUR_API_KEY .

<!DOCTYPE html>
<html>
  <head>
  <title>Remove Markers</title>
  <style>
     /* Always set the map height explicitly to define the size of the div
     * element that contains the map. */
     #map {
       height: 100%;
       }
  </style>
</head>
<body>

<div id="map"></div>
<p>Click on the map to add markers.</p>
<script>

  // In the following example, markers appear when the user clicks on the map.
  // The markers are stored in an array.
  // The user can then click an option to hide, show or delete the markers.
  var map;
  var markers = [];

  function initMap() {
    var haightAshbury = {lat: 37.769, lng: -122.446};

    map = new google.maps.Map(document.getElementById('map'), {
      zoom: 12,
      center: haightAshbury,
      mapTypeId: 'terrain'
    });

    // This event listener will call addMarker() when the map is clicked.
    map.addListener('click', function(event) {
      addMarker(event.latLng);
    });

    // Adds a marker at the center of the map.
    addMarker(haightAshbury);
  }

   // Adds a marker to the map and push to the array.
  function addMarker(location) {
    var marker = new google.maps.Marker({
      position: location,
      map: map
    });
    markers.push(marker);
  }

  // Sets the map on all markers in the array.
  function setMapOnAll(map) {
    for (var i = 0; i < markers.length; i++) {
      markers[i].setMap(map);
    }
  }

  // Removes the markers from the map, but keeps them in the array.
  function clearMarkers() {
    setMapOnAll(null);
  }

  // Shows any markers currently in the array.
  function showMarkers() {
    setMapOnAll(map);
  }

  // Deletes all markers in the array by removing references to them.
  function deleteMarkers() {
    clearMarkers();
    markers = [];
  }

</script>
   <script async defer
    src="https://maps.googleapis.com/maps/api/js key=YOUR_API_KEY&callback=initMap">
   </script>
</body>
</html>

당신은 협의 할 수있다 구글 개발자 도, 나에 대한 문서 개발자 웹 사이트를 구글 .


롤링 거의 답변을 깨끗하고 쉽게 적용 할 수 있습니다.

function placeMarkerAndPanTo(latLng, map) {
      while(markersArray.length) { markersArray.pop().setMap(null); }
      var marker = new google.maps.Marker({
        position: latLng,
        map: map
      });
      map.panTo(latLng);

      markersArray.push(marker) ;
    }

set_map두 답변 모두에 게시 된 " "기능은 더 이상 Google Maps v3 API에서 작동하지 않는 것 같습니다.

무슨 일이 있었는지 궁금해

최신 정보:

Google이 " set_map"이 (가) " "가 아닌 API를 변경 한 것으로 보입니다 setMap.

http://code.google.com/apis/maps/documentation/v3/reference.html


다음은 마커를 제거하는 방법의 예입니다.

https://developers.google.com/maps/documentation/javascript/examples/marker-remove?hl=es

// Add a marker to the map and push to the array.
function addMarker(location) {
  var marker = new google.maps.Marker({
    position: location,
    map: map
  });
  markers.push(marker);
}

// Sets the map on all markers in the array.
function setAllMap(map) {
  for (var i = 0; i < markers.length; i++) {
    markers[i].setMap(map);
   }
}

// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
  setAllMap(null);
}

// Deletes all markers in the array by removing references to them.
function deleteMarkers() {
  clearMarkers();
  markers = [];
}

오버레이를 반복적으로 지울 때 깜박임이 있지만 Anon의 다음은 완벽하게 작동합니다.

간단히 다음을 수행하십시오.

I. 전역 변수를 선언하십시오.

var markersArray = [];

II. 함수를 정의하십시오.

function clearOverlays() {
  if (markersArray) {
    for (i in markersArray) {
      markersArray[i].setMap(null);
    }
  }
}

III. 다음을 호출하기 전에 'markerArray'에서 마커를 푸시하십시오.

markersArray.push(marker);
google.maps.event.addListener(marker,"click",function(){});

IV. clearOverlays()필요한 곳 에서 함수를 호출하십시오 .

그게 다야 !!

희망이 당신을 도울 것입니다.


가장 쉬운 방법으로 google-maps-utility-library-v3 프로젝트에서 markermanager 라이브러리를 사용하는 것을 발견했습니다.

1. MarkerManager 설정

mgr = new MarkerManager(map);
google.maps.event.addListener(mgr, 'loaded', function () {
    loadMarkers();
});

2. MarkerManager에 마커 추가

function loadMarkers() {
  var marker = new google.maps.Marker({
            title: title,
            position: latlng,
            icon: icon
   });
   mgr.addMarker(marker);
   mgr.refresh();
 }

3. 마커를 지우려면 MarkerManger의 clearMarkers()함수 를 호출하면 됩니다.

mgr.clearMarkers();

이 방법으로도 할 수 있습니다.

function clearMarkers(category){ 
  var i;       

  for (i = 0; i < markers.length; i++) {                          
    markers[i].setVisible(false);        
  }    
}

방금 kmlLayer.setMap (null)으로 시도해 보았습니다. 그것이 일반 마커와 함께 작동하지만 확실하게 작동하는지 확실하지 않습니다.


폴리, 마커 등을 포함한 모든 오버레이를 지우려면 ...

간단히 사용하십시오 :

map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);}

다음은지도 응용 프로그램에서 나를 작성하기 위해 작성한 함수입니다.

  function clear_Map() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    //var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var myOptions = {
        zoom: 8,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: HamptonRoads
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}

지도에서 모든 마커를 제거하려면 다음과 같은 함수를 작성하십시오.

1. addMarker (location) :이 함수는지도에 마커를 추가하는 데 사용됩니다

2.clearMarkers () :이 함수는 배열이 아닌 맵에서 모든 마커를 제거합니다.

3. setMapOnAll (map) :이 함수는 마커 정보를 배열에 추가하는 데 사용됩니다.

4. deleteMarkers () :이 함수는 참조를 제거하여 배열의 모든 마커를 삭제합니다.

// Adds a marker to the map and push to the array.
      function addMarker(location) {
        var marker = new google.maps.Marker({
          position: location,
          map: map
        });
        markers.push(marker);
      }


// Sets the map on all markers in the array.
      function setMapOnAll(map) {
        for (var i = 0; i < markers.length; i++) {
          markers[i].setMap(map);
        }
      }



// Removes the markers from the map, but keeps them in the array.
  function clearMarkers() {
    setMapOnAll(null);
  }

// Deletes all markers in the array by removing references to them.
      function deleteMarkers() {
        clearMarkers();
        markers = [];
      }

가장 깨끗한 방법은지도의 모든 기능을 반복하는 것입니다. 마커 (다각형, 폴리 라인 등)는 데이터 레이어저장 됩니다.

function removeAllMarkers() {
  map.data.forEach((feature) => {
    feature.getGeometry().getType() === 'Point' ? map.data.remove(feature) : null
  });
}

마커가 drawing manager 를 통해 추가되는 경우 다음과 같이 마커 의 전역 배열을 만들거나 마커를 데이터 레이어로 밀어 넣는 것이 가장 좋습니다.

google.maps.event.addListener(drawingManager, 'overlaycomplete', (e) => {
    var newShape = e.overlay;
    newShape.type = e.type;

    if (newShape.type === 'marker') {
      var pos = newShape.getPosition()
      map.data.add({ geometry: new google.maps.Data.Point(pos) });

      // remove from drawing layer
      newShape.setMap(null);
    }
  });

나중에 다른 google.maps.data 클래스 메소드를 사용할 수 있으므로 두 번째 방법을 권장합니다.


이것은 Google이 하나 이상의 샘플에서 사용하는 방법입니다.

var markers = [];

// Clear out the old markers.
markers.forEach(function(marker) {
  marker.setMap(null);
});
markers = [];

전체 코드 예제는 Google 샘플을 확인하십시오.

https://developers.google.com/maps/documentation/javascript/examples/places-searchbox


왜 그런지 setMap(null)모르겠지만을 사용할 때 마커 설정 이 작동하지 않았습니다 DirectionsRenderer.

제 경우에는 저에게도 전화 setMap(null)해야 DirectionsRenderer했습니다.

그런 것 :

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();

if (map.directionsDisplay) {
    map.directionsDisplay.setMap(null);
}

map.directionsDisplay = directionsDisplay;

var request = {
    origin: start,
    destination: end,
    travelMode: google.maps.TravelMode.DRIVING
};

directionsDisplay.setMap(map);
directionsService.route(request, function (result, status) {
    if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(result);
    }
});

마커 위로 걸어서 맵에서 빈 마커 마커 배열을 제거하십시오.

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

Googlemap을 지우십시오.

mGoogle_map.clear();

나는 일을 잘하는 속기를 사용합니다. 그냥 해

    map.clear();

제안 된 모든 솔루션을 시도했지만 모든 마커가 클러스터 아래에있는 동안 아무것도 효과가 없었습니다. 결국 나는 이것을 넣었다.

var markerCluster = new MarkerClusterer(map, markers,
    { imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m' });
agentsGpsData[agentGpsData.ID].CLUSTER = markerCluster;

//this did the trick
agentsGpsData[agentId].CLUSTER.clearMarkers();

다시 말해, 마커를 클러스터에 포장하고 모든 마커를 제거하려면 다음을 호출하십시오.

clearMarkers();

숨기거나 삭제하는 것처럼 제거 하시겠습니까?

숨어있는 경우 :

function clearMarkers() {
            setAllMap(null);
        }

삭제하려는 경우 :

 function deleteMarkers() {
            clearMarkers();
            markers = [];
        }

배열 마커를 사용하여 추적하고 수동으로 재설정합니다.


해당 마커에 map null을 설정해야합니다.

var markersList = [];    

function removeMarkers(markersList) {
   for(var i = 0; i < markersList.length; i++) {
      markersList[i].setMap(null);
   }
}

function addMarkers() {
   var marker = new google.maps.Marker({
        position : {
            lat : 12.374,
            lng : -11.55
        },
        map : map
       });
      markersList.push(marker);
   }

간단한 해결책을 찾았습니다.

var marker = new google.maps.Marker();

function Clear(){
     marker.setMap(null);
}

gmap V3 플러그인을 사용하는 경우 : $("#map").gmap("removeAllMarkers");

참조 : http://www.smashinglabs.pl/gmap/documentation#after-load


이를 사용하여 map에서 모든 마커를 제거 할 수 있습니다.

map.clear();

참고 URL : https://stackoverflow.com/questions/1544739/google-maps-api-v3-how-to-remove-all-markers



반응형