Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • Devin 87 posts 251 karma points
    Dec 04, 2015 @ 13:46
    Devin
    0

    Pass Image Array to Javascript

    I have a foreach loop in Razor which takes images from the Multiple Media Picker in Umbraco. The Response.Write just allows me to see that the images are displaying fine (which they are) so you can ignore this bit.

    My question is, how do I populate the image tag with the image URL using the Javascript function? (see below which currently doesn't work).

    Razor View/CSHTML

    var imagesList = portfolioItem.GetPropertyValue<string>("Images").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
    var imagesCollection = Umbraco.TypedMedia(imagesList);
    
    foreach (var imageItem in imagesCollection)
    {   
        Response.Write("<img src='"+ @imageItem.Url +"' />");
    }
    

    Javascript

    openInfoWindow = function (name, imagesCollection, location, mw, url, marker) {
        var infoText = "<img src='" + imagesCollection + "' alt='" + imagesCollection + "'title='" + imagesCollection + "' />";
    }
    
  • Dave Woestenborghs 3504 posts 12135 karma points MVP 9x admin c-trib
    Dec 04, 2015 @ 14:58
    Dave Woestenborghs
    1

    Hi Devin,

    You probabley need something like this. This will out the imagelist from razor to a javascript array :

    @{
    var imagesList = portfolioItem.GetPropertyValue<string>("Images").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
    var imagesCollection = Umbraco.TypedMedia(imagesList);
    }
    
    <script type="text/javascript">
        var imagesCollection = [
            @string.Join(",", imagesCollection.Select(x => x.Url.EnsureStartsWith("'").EnsureEndsWith("'")))
        ];
    </script>
    

    I have not tested this, but I think it should work

    Dave

  • Devin 87 posts 251 karma points
    Dec 04, 2015 @ 17:16
    Devin
    0

    Thanks for your reply Dave, will have to test this when I'm back at work on Monday. Will report back +1

    Tried it and receive the following error:

    Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type
    

    Here's the full code:

    @inherits Umbraco.Web.Mvc.UmbracoTemplatePage
    <link rel="stylesheet" type="text/css" href="/css/Portfolio.css"/>
    <script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 
    <script type="text/javascript">  
      var map;
      var markers = [];
      var infowindow = new google.maps.InfoWindow({
          maxWidth: 200
      });
      function initialize() {
    
        var styles = [
        {
            "featureType": "administrative",
            "elementType": "geometry.stroke",
            "stylers": [
                {
                    "visibility": "on"
                },
                {
                    "color": "#aabdc7"
                }
            ]
        },
        {
            "featureType": "administrative",
            "elementType": "labels.text.fill",
            "stylers": [
                {
                    "color": "#444444"
                }
            ]
        },
        {
            "featureType": "administrative.land_parcel",
            "elementType": "geometry.stroke",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "landscape",
            "elementType": "all",
            "stylers": [
                {
                    "color": "#f2f2f2"
                }
            ]
        },
        {
            "featureType": "landscape.man_made",
            "elementType": "geometry.stroke",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "landscape.man_made",
            "elementType": "labels.text.stroke",
            "stylers": [
                {
                    "visibility": "on"
                },
                {
                    "color": "#f44545"
                }
            ]
        },
        {
            "featureType": "landscape.natural",
            "elementType": "geometry.stroke",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "landscape.natural.landcover",
            "elementType": "geometry.fill",
            "stylers": [
                {
                    "color": "#ebedee"
                }
            ]
        },
        {
            "featureType": "landscape.natural.landcover",
            "elementType": "geometry.stroke",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "landscape.natural.landcover",
            "elementType": "labels.text.stroke",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "landscape.natural.terrain",
            "elementType": "geometry",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "landscape.natural.terrain",
            "elementType": "geometry.stroke",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "landscape.natural.terrain",
            "elementType": "labels.text.stroke",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "poi",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "road",
            "elementType": "all",
            "stylers": [
                {
                    "saturation": -100
                },
                {
                    "lightness": 45
                }
            ]
        },
        {
            "featureType": "road.highway",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "simplified"
                }
            ]
        },
        {
            "featureType": "road.arterial",
            "elementType": "labels.icon",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "transit",
            "elementType": "all",
            "stylers": [
                {
                    "visibility": "off"
                }
            ]
        },
        {
            "featureType": "water",
            "elementType": "all",
            "stylers": [
                {
                    "color": "#c9d8df"
                },
                {
                    "visibility": "on"
                }
            ]
        }
    ];  
    
        var styledMap = new google.maps.StyledMapType(styles,{name: "Styled Map"});
        var geocoder = new google.maps.Geocoder();
        var map_canvas = document.getElementById('map_canvas');
        var map_options = {
            center: new google.maps.LatLng(32.1288162,-13.2088774),
            zoom: 3,
            zoomControlOptions: {
                position: google.maps.ControlPosition.TOP_LEFT
            },
            streetViewControlOptions: {
                position: google.maps.ControlPosition.TOP_LEFT
            },
            mapTypeId: google.maps.MapTypeId.TERRAIN,
            mapTypeControl: false,
            mapTypeControlOptions: {
              mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
            }
        };
        map = new google.maps.Map(map_canvas, map_options)
    
        map.mapTypes.set('map_style', styledMap);
        map.setMapTypeId('map_style');
    
    
          @{
              int i = 0;
    
              foreach (var portfolioItem in CurrentPage.Descendants("PortfolioItem").OrderBy("Name"))
              {
                  i++;
                  var url = "";
                  int port = HttpContext.Current.Request.Url.Port;
                  url = "http://" + HttpContext.Current.Request.Url.Host;
    
                  if (port != 80)
                  {
                      url += ":" + port;
                  }
    
                  if (!String.IsNullOrEmpty(portfolioItem.technology))
                  {
    
                      url += "/images/portfolio/" + portfolioItem.technology.ToString().ToLower().Split(new char[] { ',' })[0] + ".png";
                  }
                  else
                  {
                      url += "/images/portfolio/windmarker.png";
                  }
    
                  var description = portfolioItem.shortDescription.ToString().Replace("'", "&#39;");
                  var name = portfolioItem.Name.ToString().Replace("'", "&#39;");
    
                  var imagesList = portfolioItem.GetPropertyValue<string>("Images").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                  var imagesCollection = Umbraco.TypedMedia(imagesList);
    
                  foreach (var imageItem in imagesCollection)
                    {   
                        @:var imagesCollection =[
                            string.Join(",", imagesCollection.Select(x => x.Url.EnsureStartsWith("'").EnsureEndsWith("'")));
                        @:];
                    }
    
                  var imageName = portfolioItem.Name.ToString().Replace("&", "and").Replace(",", "").Replace("  ", " ").Replace(" ", "-").Replace("'", "").Replace(".", "").Replace("eacute;", "é").ToString().ToLower();
                  var location = portfolioItem.Location.ToString().Replace("'", "&#39;");
    
                  var mw = "";
                  if (portfolioItem.HasValue("totalExpectedInstalledCapacity")) { mw = portfolioItem.totalExpectedInstalledCapacity; }
                  if (portfolioItem.HasValue("totalInstalledCapacity")) { mw = portfolioItem.totalInstalledCapacity; }
                  if (portfolioItem.HasValue("capacity")) { mw = portfolioItem.capacity; }
    
                @Html.Raw("var marker" + i + " = new google.maps.Marker({");
                @Html.Raw(" position: new google.maps.LatLng(" + portfolioItem.latitude + "," + portfolioItem.longitude + "),");
                @Html.Raw(" map: map,");
                @Html.Raw(" title: '" + portfolioItem.Name.Replace("'", "&#39;") + "',");
                @Html.Raw(" icon: {         ");
                               /* Change based on technology */
                @Html.Raw("     url: '" + url + "'");
                @Html.Raw(" }");
                @Html.Raw("});");
                @Html.Raw("google.maps.event.addDomListener(document.getElementById('marker" + i + "'), 'click', function(ev) {map.setCenter(marker" + i + ".getPosition());});");
                @Html.Raw("marker" + i + ".phase = '" + portfolioItem.phase + "';"); 
                @Html.Raw("marker" + i + ".date = '" + ((DateTime)portfolioItem.date).Year + "';"); 
                @Html.Raw("marker" + i + ".country = '" + portfolioItem.Parent.Name + "';"); 
                @Html.Raw("marker" + i + ".technology = '" + portfolioItem.technology + "';");
    
                @Html.Raw("google.maps.event.addListener(marker" + i + ", 'click', function() {");
                @Html.Raw("openInfoWindow('" + name + "', '" + imagesCollection + "', '" + location + "', '" + mw + "', '" + portfolioItem.Url + "', marker" + i + ");");
                @Html.Raw("});");
    
                @Html.Raw("$('#marker" + i + "').on('click', function() {");
                @Html.Raw("openInfoWindow('" + name + "', '" + imagesCollection + "', '" + location + "', '" + mw + "', '" + portfolioItem.Url + "', marker" + i + ");");
                @Html.Raw("});");
    
                @Html.Raw("marker" + i + ".setVisible(true);");
                @Html.Raw("markers.push(marker" + i + ");");
              }
       }
    
          filterMarkers();
      }
    
        google.maps.event.addDomListener(window, 'load', initialize);
    
        selectAll = function(selected, type)
        {
            $(type + ' input').prop('checked', selected);
            filterMarkers();
        }
    
        filterMarkers = function()
        {
            var phases = [];
            var countries = [];
            var technologies = [];
            var date_start = '';
            var date_end = '';
    
            $("#phase input:checked").each(function(index, elem){
                phases.push($(this).val());
            });
            $("#country input:checked").each(function(index, elem){
                countries.push($(this).val());
            });
            $("#technology input:checked").each(function(index, elem){
                technologies.push($(this).val());
            });     
            date_start = $("#datestart option:selected").val();
            date_end = $("#dateend option:selected").val();
    
    
    
           for (i = 0; i < markers.length; i++) {
               var marker = markers[i];   
    
               var phasetrue = false;
               var countriestrue = false;
               var technologiestrue = false;
    
               if (phases.length == 0)
               {
                   phasetrue = false;
               }
               else
               {
                   for (j = 0; j < phases.length; j++)
                   {
                       if ((marker.phase).indexOf(phases[j]) > -1)
                       {
                           phasetrue = true;
                       }
                   }
               }
               if (countries.length == 0)
               {
                   countriestrue = false;
               }
               else
               {
                   for (j = 0; j < countries.length; j++)
                   {
                       if ((marker.country).indexOf(countries[j]) > -1)
                       {
                           countriestrue = true;
                       }
                   }
               }
               if (technologies.length == 0)
               {
                   technologiestrue = false;
               }
               else
               {
                   for (j = 0; j < technologies.length; j++)
                   {
                       if ((marker.technology).indexOf(technologies[j]) > -1)
                       {
                           technologiestrue = true;
                       }
                   }
               }
    
               if(phasetrue == true &&
                  countriestrue == true &&
                  technologiestrue == true &&
                  ((date_start <= marker.date && date_end >= marker.date) || (date_start == undefined || date_end ==undefined) || (date_start == '' || date_end == ''))
                )
               {
                   marker.setVisible(true);
               }
               else
               {          
                   marker.setVisible(false);
               }
            }  
        }
        setCenter = function(latitude, longitude)
        {
            map.panTo(new google.maps.LatLng(latitude, longitude));
        }
    
        openInfoWindow = function (name, imagesCollection, location, mw, url, marker) {
    
            var infoText = "<div class='portfolioTooltip'><div class='tooltipName'>" + name + "</div><img src='" + imagesCollection + "' alt='" + imagesCollection + "'title='" + imagesCollection + "' />";
            var moreInformationLink = "<div><a class='tooltipLink' href=\"" + url + "\" target=\"_blank\">More Information</a></div>";
            if (location.length > 0) {
                infoText += "<div class='tooltipLabel'>Location</div>";
                infoText += "<div class='tooltipData'>" + location + "</div>";
            }
            if (mw.length > 0) {
                infoText += "<div class='tooltipLabel'>MW</div>";
                infoText += "<div class='tooltipData'>" + mw + "</div>";
            }
            infoText += moreInformationLink;
            infoText += "</div>";
    
            infowindow.setContent(infoText);
            infowindow.open(map, marker);
        }
    
    </script>
    
Please Sign in or register to post replies

Write your reply to:

Draft