Beispiel #1
0
        /// <summary>
        /// Create styled layer
        /// </summary>
        /// <param name="cartoLayer"></param>
        /// <param name="cartoTranslator"></param>
        /// <returns></returns>
        private static StyledLayer CreateStyledLayer(CartoLayer cartoLayer, Map map, ICartoTranslator cartoTranslator)
        {
            ParameterCollection parameters = cartoTranslator.ToDatasourceParameters(cartoLayer);
            StyledLayer         layer      = new StyledLayer(cartoLayer.Name, parameters);

            layer.FeaturesCaching.Enabled = true;

            if (cartoLayer.Properties != null)
            {
                if (cartoLayer.Properties.ContainsKey("minzoom"))
                {
                    layer.MinimumScale = ConvertUtility.ToScaleDenominator(Convert.ToInt32(cartoLayer.Properties["minzoom"]));
                }
                if (cartoLayer.Properties.ContainsKey("maxzoom"))
                {
                    layer.MaximumScale = ConvertUtility.ToScaleDenominator(Convert.ToInt32(cartoLayer.Properties["maxzoom"]));
                }
                if (cartoLayer.Properties.ContainsKey("queryable"))
                {
                    layer.Queryable = Convert.ToBoolean(cartoLayer.Properties["queryable"]);
                }
                if (cartoLayer.Properties.ContainsKey("cache-features")) // Extension
                {
                    layer.FeaturesCaching.Enabled = Convert.ToBoolean(cartoLayer.Properties["cache-features"]);
                }
            }

            layer.Enabled = cartoLayer.Status != "off";

            string providerName = parameters.GetValue("Type");

            if (string.IsNullOrEmpty(providerName))
            {
                LogFactory.WriteLogEntry(Logger.Default, new IOException(string.Format("Unable to detect the type of a data source provider for the layer '{0}'.", cartoLayer.Name)));
            }

            if (!string.IsNullOrEmpty(cartoLayer.Srs))
            {
                layer.CRS = cartoTranslator.ToCoordinateSystem(string.IsNullOrEmpty(cartoLayer.Srs) ? cartoLayer.SrsName : cartoLayer.Srs, !string.IsNullOrEmpty(cartoLayer.SrsName));
            }

            return(layer);
        }
Beispiel #2
0
        public static Map ReadFromFile(string fileContent, string fileName)
        {
            string path = Path.GetDirectoryName(fileName);

            CartoProject cartoProject = null;

            switch (Path.GetExtension(fileName).ToLower())
            {
            case ".mml":
                cartoProject = JsonConvert.DeserializeObject <CartoProject>(fileContent);

                if (cartoProject.Interactivity != null)
                {
                    try
                    {
                        Dictionary <string, object> dict = JsonConvert.DeserializeObject <Dictionary <string, object> >(cartoProject.Interactivity.ToString());
                        cartoProject.Interactivity = dict;
                    }
                    catch
                    { }

                    try
                    {
                        bool enabled = JsonConvert.DeserializeObject <bool>(cartoProject.Interactivity.ToString());
                        cartoProject.Interactivity = enabled;
                    }
                    catch
                    { }
                }
                break;

            case ".yaml":
                using (StringReader input = new StringReader(fileContent))
                {
                    Deserializer deserializer = new Deserializer(namingConvention: new CamelCaseNamingConvention(), ignoreUnmatched: true);
                    var          parser       = new MergingParser(new YamlDotNet.Core.Parser(input));
                    cartoProject = deserializer.Deserialize <CartoProject>(new EventReader(parser));
                }
                break;

            default:
                throw new Exception("Unknown extension of the CartoCSS project.");
            }

            Map map = null;

            if (cartoProject.Stylesheet != null && cartoProject.Stylesheet.Length > 0 && cartoProject.Layers.Length > 0)
            {
                ICartoTranslator cartoTranslator = CartoGeneratorConverterFactory.CreateTranslator(cartoProject.Generator);

                CartoParser parser = new CartoParser();
                parser.NodeProvider = new CartoNodeProvider();
                Env                    env         = new Env();
                List <Ruleset>         ruleSets    = new List <Ruleset>();
                List <CartoDefinition> definitions = new List <CartoDefinition>();

                foreach (string styleName in cartoProject.Stylesheet)
                {
                    string styleFileName = Path.Combine(path, styleName);

                    try
                    {
                        Ruleset ruleSet = parser.Parse(File.ReadAllText(styleFileName), styleFileName, env);

                        ruleSets.Add(ruleSet);

                        // Get an array of Ruleset objects, flattened
                        // and sorted according to specificitySort
                        var defs = new List <CartoDefinition>();
                        defs = ruleSet.Flatten(defs, null, env);
                        defs.Sort(new SpecificitySorter());

                        definitions.AddRange(defs);

                        env.Frames.Push(ruleSet);
                    }
                    catch (Exception ex)
                    {
                        Exception ex2 = new IOException(string.Format("An error occured during parsing of the style '{0}'.", styleFileName) + ex.Message);
                        LogFactory.WriteLogEntry(Logger.Default, ex2);
                        throw ex2;
                    }
                }

                string interactivityLayer = null;
                if (cartoProject.GetInteractivity() != null && cartoProject.GetInteractivity().ContainsKey("layer"))
                {
                    interactivityLayer = cartoProject.GetInteractivity()["layer"].ToString();
                }

                map = CreateMap(cartoProject, definitions, env, cartoTranslator);

                foreach (CartoLayer cartoLayer in cartoProject.Layers)
                {
                    CartoDatasource datasource  = cartoLayer.Datasource;
                    StyledLayer     styledLayer = CreateStyledLayer(cartoLayer, map, cartoTranslator);

                    try
                    {
                        string[] classes = (cartoLayer.Class.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
                        Dictionary <string, bool> classIndex = new Dictionary <string, bool>(classes.Length);
                        for (int i = 0; i < classes.Length; i++)
                        {
                            classIndex[classes[i]] = true;
                        }

                        var matching = definitions.FindAll(delegate(CartoDefinition def) { return(def.AppliesTo(cartoLayer.Name, classIndex)); });

                        if (matching.Count > 0)
                        {
                            List <CartoStyle> rules = InheritDefinitions(matching, env);

                            if (rules.Count > 0)
                            {
                                SortStyles(rules, env);

                                for (int k = 0; k < rules.Count; k++)
                                {
                                    CartoStyle cartoStyle = rules[k];
                                    cartoStyle.Fold(env);
                                    string           styleName = cartoLayer.Name + (cartoStyle.Attachment != "__default__" ? "-" + cartoStyle.Attachment : "");
                                    FeatureTypeStyle style     = CreateStyle(styleName, cartoStyle, env, cartoTranslator);

                                    if (style.Rules.Count > 0)
                                    {
                                        styledLayer.Styles.Add(style);
                                    }
                                }

                                cartoTranslator.ProcessStyles(styledLayer.Styles);
                            }

                            if (!string.IsNullOrEmpty(interactivityLayer) && interactivityLayer.Equals(styledLayer.Name))
                            {
                                styledLayer.Enabled = false;
                            }

                            map.AddLayer(styledLayer);
                        }
                    }
                    catch (Exception ex)
                    {
                        Exception ex2 = new IOException(string.Format("Unable to create data source provider with type '{0}' for the layer '{1}'.", datasource.Type, cartoLayer.Name) + ex.Message);
                        LogFactory.WriteLogEntry(Logger.Default, ex2);
                    }
                }
            }

            return(map);
        }
    /// <summary>
    /// Create styled layer
    /// </summary>
    /// <param name="cartoLayer"></param>
    /// <param name="cartoTranslator"></param>
    /// <returns></returns>
    private static StyledLayer CreateStyledLayer(CartoLayer cartoLayer, Map map, ICartoTranslator cartoTranslator)
    {
      ParameterCollection parameters = cartoTranslator.ToDatasourceParameters(cartoLayer);
      StyledLayer layer = new StyledLayer(cartoLayer.Name, parameters);
      layer.FeaturesCaching.Enabled = true;

      if (cartoLayer.Properties != null)
      {
        if (cartoLayer.Properties.ContainsKey("minzoom"))
          layer.MinimumScale = ConvertUtility.ToScaleDenominator(Convert.ToInt32(cartoLayer.Properties["minzoom"]));
        if (cartoLayer.Properties.ContainsKey("maxzoom"))
          layer.MaximumScale = ConvertUtility.ToScaleDenominator(Convert.ToInt32(cartoLayer.Properties["maxzoom"]));
        if (cartoLayer.Properties.ContainsKey("queryable"))
          layer.Queryable = Convert.ToBoolean(cartoLayer.Properties["queryable"]);
        if (cartoLayer.Properties.ContainsKey("cache-features")) // Extension
          layer.FeaturesCaching.Enabled = Convert.ToBoolean(cartoLayer.Properties["cache-features"]);
      }

      layer.Enabled = cartoLayer.Status != "off";

      string providerName = parameters.GetValue("Type");
      if (string.IsNullOrEmpty(providerName))
        LogFactory.WriteLogEntry(Logger.Default, new IOException(string.Format("Unable to detect the type of a data source provider for the layer '{0}'.", cartoLayer.Name)));

      if (!string.IsNullOrEmpty(cartoLayer.Srs))
        layer.CRS = cartoTranslator.ToCoordinateSystem(string.IsNullOrEmpty(cartoLayer.Srs) ? cartoLayer.SrsName : cartoLayer.Srs, !string.IsNullOrEmpty(cartoLayer.SrsName));

      return layer;
    }