Ben Ng
Ben Ng

Reputation: 15

C# gmap clear all markers

  private void loadMap()
    {
        MainMap.ShowCenter = false;

        string cor = string.Empty;
        using (MySqlConnection sqlConn = new MySqlConnection(myConnectionString))
        {
            sqlConn.Open();
            using (MySqlCommand cmd = new MySqlCommand())
            {
                cmd.CommandText = "SELECT * FROM event WHERE EventId=@eventId";

                cmd.Connection = sqlConn;
                cmd.Parameters.AddWithValue("@eventId", EventId);
                using (MySqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        cor = reader.GetString("EventCor");
                    }
                }
            }
        }
        string[] cord = cor.Split(',');
        if (cor != string.Empty)
        {

            Lat = Convert.ToDouble(cord[0]);
            Lng = Convert.ToDouble(cord[1]);

            // Initialize map:
            //GMap.NET.MapProviders.OpenCycleMapProvider
            MainMap.MapProvider = GMap.NET.MapProviders.GoogleMapProvider.Instance;
            GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
            MainMap.Position = new PointLatLng(Lat, Lng);

            GMapOverlay markersOverlay = new GMapOverlay("markers");

            GMarkerGoogle marker = new GMarkerGoogle(new PointLatLng(lat, lng),              
              GMarkerGoogleType.green);


            markersOverlay.Markers.Add(marker); 
            MainMap.Overlays.Add(markersOverlay);
        }
    }

Above is my method to load the gmap. The problem is that if i load the map again, the previous marker will remain on the map. Therefore, I would like to remove all the markers on the map before loading the map. Thank you for your help.

Upvotes: 0

Views: 4846

Answers (2)

Alex Horlock
Alex Horlock

Reputation: 306

The 'Markers' object in any gmaps overlay is an observableThreadSafeCollection. All you need to do is add the line:

'markersOverlay.Markers.Clear()'

to the top of your loadMap() method and that should do it.

Upvotes: 1

dhh
dhh

Reputation: 4335

According to the documentation over here you should keep a reference to all markers when generating / adding them. For removing the markers, you can then set their map to null for each marker.

Upvotes: 0

Related Questions