2

I have the following javascript function in the head of a view

function addMarker(title, description, lon,lat, iconT) {
    var icon = new OpenLayers.Icon(iconT);
    var markerslayer = new OpenLayers.Layer.Markers("Markers");
    var lonlat = new OpenLayers.LonLat(lon, lat);
    lonlat = lonlat.transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject());
    var markerToAdd = new OpenLayers.Marker(lonlat, icon);
    markerToAdd.icon.imageDiv.title = title + "  -  " + description;
    markerslayer.addMarker(markerToAdd);
    map.addLayer(markerslayer);
    map.addControl(new OpenLayers.Control.LayerSwitcher());
}

I am trying to call the function above by using either:

@if (Model != null)
{
    foreach (var item in Model)
    {                
    <script type="text/javascript">
            addMarker(@item.Title, @item.Description, @item.Longitude, @item.Latiude, @item.Icon);
    </script>
    }
}

or alternatively

 public ActionResult Index()
 {
     List<CommonLayer.Map> userMaps = new BL.Map().getUserMaps(User.Identity.Name);
     foreach (var item in userMaps)
     {
         Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "MyFunction()", true);
     }

     return View(userMaps);
 }

What am I doing wrong? The view code is not calling the addMarket function whilst the c# code cannot be called from inside the foreach since it is not static

6
  • first one should work\ Commented May 8, 2014 at 11:14
  • First one: Is your addMarker function declared above the foreach loop in your view? Are you seeing any console errors? Commented May 8, 2014 at 11:18
  • What does the generated HTML/JS look like? Are there quotes around Title and Description? Commented May 8, 2014 at 11:21
  • 2
    try putting single quotes like : addMarker('@item.Title'....) Commented May 8, 2014 at 11:24
  • You are mixing server side and client side code there, are you sure that is what you want? Commented May 8, 2014 at 11:33

1 Answer 1

1

Try this:

@if (Model != null)
{
    foreach (var item in Model)
    {
    <script type="text/javascript">
            addMarker('@item.Title', '@item.Description', @item.Longitude, @item.Latiude, @item.Icon);
    </script>
    }
}

Also, this line has the icon misspelled (must be iconT instead of icon:

var markerToAdd = new OpenLayers.Marker(lonlat, icon);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.