Home >Web Front-end >JS Tutorial >How Do You Remove Markers from a Google Maps API v3 Map?

How Do You Remove Markers from a Google Maps API v3 Map?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-14 10:16:011043browse

How Do You Remove Markers from a Google Maps API v3 Map?

Removing Markers in Google Maps API v3: A Comprehensive Guide

Unlike its predecessor, Google Maps API v3 lacks a clear method for removing all markers from the map. This article will explore an effective approach to achieve this goal.

Solution:

The key to clearing markers in v3 lies in initializing a global array called "markersArray" to store all the markers as they are created. A custom function named "clearOverlays()" can then be defined to iterate through this array and set the map property of each marker to "null," effectively removing them from the map.

Here's the detailed implementation:

  1. Declare a Global Array:

    var markersArray = [];
  2. Define the "clearOverlays()" Function:

    function clearOverlays() {
      for (var i = 0; i < markersArray.length; i++ ) {
     markersArray[i].setMap(null);
      }
      markersArray.length = 0;
    }
  3. Push Markers into the "markersArray":
    Before calling the "clearOverlays()" function, push all the markers into the "markersArray." Use the following code for each marker:

    markersArray.push(marker);
    google.maps.event.addListener(marker,"click",function(){});
  4. Call the "clearOverlays()" Function:
    Execute the "clearOverlays()" function or "map.clearOverlays()" (if you want to extend the functionality to the map object) when needed to remove all the markers.

The above is the detailed content of How Do You Remove Markers from a Google Maps API v3 Map?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn