fifamaniac04
fifamaniac04

Reputation: 2383

How to add multiple markers in leaflet via codebehind

I want to add more than one leaflet marker on a map through the codebehind. My C# is as follows:

public void setMarker(double[] lat, double[] lng)
{
    string script = string.Empty;

    for (int i = 0; i < lat.Length; i++)
    {
        script = string.Format(@"<script language=""Javascript"">
                   addMarker('{0}','{1}')
                    </script>", lat[i], lng[i]);

        Page.ClientScript.RegisterStartupScript(this.GetType(), "onMapClick", script);
    }
}

where lat and lng are arrays that are the same length and hold pre-determined coordinate points where I want the markers to appear.

my addMarker() is defined in javascript as:

  function addMarker(lat, lng)
  {
       var myLatLng = new L.LatLng(lat, lng);
       L.marker(myLatLng, { icon: greenIcon, draggable: true }).addTo(Mymap);
  }

if I call the same functionality from the mouse click event, then every where I click, the markers just get added. how do get all the markers to stay on the map when using my functions?

Upvotes: 1

Views: 1707

Answers (1)

SergeyS
SergeyS

Reputation: 3553

A client script is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates. Only one script with a given type and key pair can be registered with the page.

In your case I would just append all the calls to your function to the one script block, and then register it once (outside of the loop):

StringBuilder startupScript = new StringBuilder();
startupScript.Append(@"<script language=""Javascript"">");
for (int i = 0; i < lat.Length; i++)
{
    startupScript.AppendFormat(@"addMarker('{0}','{1}'); ", lat[i], lng[i]);
}
startupScript.Append(@"</script>");
Page.ClientScript.RegisterStartupScript(this.GetType(), "onMapClick", startupScript.ToString());

Upvotes: 3

Related Questions