Example #1
0
    public bool ClearSpatialFilter()
    {
        bool result = true;
        MgUserInformation userInfo = new MgUserInformation(Request["SESSION"]);
        MgSiteConnection siteConnection = new MgSiteConnection();
        siteConnection.Open(userInfo);

        MgResourceIdentifier sdfResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.FeatureSource");

        MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService;
        MgFeatureService featureService = siteConnection.CreateService(MgServiceType.FeatureService) as MgFeatureService;
        MgMap map = new MgMap();
        map.Open(resourceService, Request["MAPNAME"]);

        MgFeatureCommandCollection updateCommands = new MgFeatureCommandCollection();

        MgLayer layer = null;
        MgLayerCollection layers = map.GetLayers();
        if (layers.Contains("_QuerySpatialFilter"))
        {
            layer = (MgLayer)layers.GetItem("_QuerySpatialFilter");
            updateCommands.Add(new MgDeleteFeatures("Filter", "ID > 0"));
            featureService.UpdateFeatures(sdfResId, updateCommands, false);
            layers.Remove(layer);
            map.Save(resourceService);
        }

        return result;
    }
Example #2
0
    public bool ShowSpatialFilter()
    {
        bool result = true;
        MgUserInformation userInfo = new MgUserInformation(Request["SESSION"]);
        MgSiteConnection siteConnection = new MgSiteConnection();
        siteConnection.Open(userInfo);

        MgResourceIdentifier sdfResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.FeatureSource");

        MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService;
        MgFeatureService featureService = siteConnection.CreateService(MgServiceType.FeatureService) as MgFeatureService;

        MgFeatureCommandCollection updateCommands = new MgFeatureCommandCollection();

        MgMap map = new MgMap();
        map.Open(resourceService, Request["MAPNAME"]);

        MgLayer layer = null;
        MgLayerCollection layers = map.GetLayers();
        if (layers.Contains("_QuerySpatialFilter"))
        {
            layer = (MgLayer)layers.GetItem("_QuerySpatialFilter");
            //updateCommands.Add(new MgDeleteFeatures("Filter", "ID > 0"));
        }
        else
        {
            // Create the Feature Source (SDF)

            MgFeatureSchema sdfSchema = this.CreateFilterSchema();
            MgCreateSdfParams sdfParams = new MgCreateSdfParams("MAPCS", map.GetMapSRS(), sdfSchema);
            featureService.CreateFeatureSource(sdfResId, sdfParams);

            // Create the Layer

            MgResourceIdentifier layerResId = new MgResourceIdentifier("Session:" + Request["SESSION"] + "//Filter.LayerDefinition");
            String layerDefinition = File.ReadAllText(GetQueryXmlTemplatePath());
            layerDefinition = layerDefinition.Replace("%s", sdfResId.ToString());

            MgByteReader reader = new MgByteReader(layerDefinition, "text/xml");
            resourceService.SetResource(layerResId, reader, null);

            layer = new MgLayer(layerResId, resourceService);

            layer.SetName("_QuerySpatialFilter");
            layer.SetLegendLabel("תחום זמני");
            layer.SetDisplayInLegend(true);
            layer.SetSelectable(true);
            layer.ForceRefresh();
            layer.NeedsRefresh();

            layers.Insert(0, layer);
        }

        // Make the layer visible

        layer.SetVisible(true);
        map.Save(resourceService);

        // Add the geometry to the filter feature source
        MgPolygon polygon = this.CreatePolygonFromGeomText(Request["GEOMTEXT"].ToString());
        MgAgfReaderWriter agfWriter = new MgAgfReaderWriter();
        MgByteReader byteReader = agfWriter.Write(polygon);

        MgPropertyCollection propertyValues = new MgPropertyCollection();
        propertyValues.Add(new MgGeometryProperty("Geometry", byteReader));
        try
        {
            updateCommands.Add(new MgInsertFeatures("Filter", propertyValues));

            featureService.UpdateFeatures(sdfResId, updateCommands, false);
        }
        catch { }

        return result;
    }
Example #3
0
        public void CloseMarkup()
        {
            MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService);

            MgMap map = new MgMap();
            map.Open(resourceService, GetParameter(this.args, "MAPNAME"));

            // Add the Markup Layer

            MgResourceIdentifier markupLayerResId = new MgResourceIdentifier(GetParameter(this.args, "OPENMARKUP"));
            int index = map.GetLayers().IndexOf("_" + markupLayerResId.GetName());
            map.GetLayers().RemoveAt(index);

            map.Save(resourceService);
        }
Example #4
0
    //----------------------------------------------------------------------------------------
    // �� �ܣ� ������ʱ��
    //
    // �� �ߣ�
    //
    //
    // �� �ڣ�2007.05.#
    //
    //-----------------------------------------------------------------------------------------
    public bool CreatePointsLayer(String rootPath, String sessionId)
    {
        // ��ȡҪ�ط������Դ����
        MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
        MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);

        //  �򿪵�ͼ
        MgMap map = new MgMap();
        map.Open(resourceService, "Sheboygan");
        // ---Ҫ�����Ҫ�ز������û��������������滹Ҫ���ܣ�--��ʼ
        // ���������ݵ�Ҫ��Դ
        CreateFeatureSource(sessionId);
        String featureSourceName = "Session:" + sessionId + "//Points.FeatureSource";
        MgResourceIdentifier resourceIdentifier = new MgResourceIdentifier(featureSourceName);

        MgBatchPropertyCollection batchPropertyCollection = new MgBatchPropertyCollection();
        MgWktReaderWriter wktReaderWriter = new MgWktReaderWriter();
        MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();
        MgGeometryFactory geometryFactory = new MgGeometryFactory();

        // �������¼
        MgPropertyCollection propertyCollection = MakePoint("Point A", -87.727, 43.748);
        batchPropertyCollection.Add(propertyCollection);

        propertyCollection = MakePoint("Point B", -87.728, 43.730);
        batchPropertyCollection.Add(propertyCollection);

        propertyCollection = MakePoint("Point C", -87.726, 43.750);
        batchPropertyCollection.Add(propertyCollection);

        propertyCollection = MakePoint("Point D", -87.728, 43.750);
        batchPropertyCollection.Add(propertyCollection);

        // ��������Ҫ��������ӵ�Ҫ��Դ
        MgInsertFeatures Insertcmd = new MgInsertFeatures("Points", batchPropertyCollection);
        MgFeatureCommandCollection featureCommandCollection = new MgFeatureCommandCollection();
        featureCommandCollection.Add(Insertcmd);
        featureService.UpdateFeatures(resourceIdentifier, featureCommandCollection, false);
        MgResourceIdentifier resourceID = null;
        //--------------Ҫ�����Ҫ�ز��� ����

        // �����㣬ͨ���㹤��LayerDefinitionFactory
        LayerDefinitionFactory factory = new LayerDefinitionFactory();
        factory.RootDirectoryPath = rootPath;

        //-------------------��������ʽ------------------------//
        // ������Ƿ���l
        string resourceSymbel = "Library://MgTutorial/Symbols/BasicSymbols.SymbolLibrary";
        string symbolName = "PushPin";
        string width = "24";  // unit = points
        string height = "24"; // unit = points
        string color = "FFFF0000";
        string markSymbol = factory.CreateMarkSymbol(resourceSymbel, symbolName, width, height, color);

        // �����ı�
        string text = "ID";
        string fontHeight = "12";
        string foregroundColor = "FF000000";
        string textSymbol = factory.CreateTextSymbol(text, fontHeight, foregroundColor);

        // ���������
        string legendLabel = "trees";
        string filter = "";
        string pointRule = factory.CreatePointRule(legendLabel, filter, textSymbol, markSymbol);

        // ��������ʽ
        string pointTypeStyle = factory.CreatePointTypeStyle(pointRule);

        // �������ŷ�Χ
        string minScale = "0";
        string maxScale = "1000000000000";
        string pointScaleRange = factory.CreateScaleRange(minScale, maxScale, pointTypeStyle);

        // �����㶨��
        string featureName = "PointSchema:Points";
        string geometry = "GEOM";
        string layerDefinition = factory.CreateLayerDefinition(featureSourceName, featureName, geometry, pointScaleRange);

        MgByteSource byteSource = new MgByteSource(Encoding.UTF8.GetBytes(layerDefinition), layerDefinition.Length);
        MgByteReader byteReader = byteSource.GetReader();

        resourceID = new MgResourceIdentifier("Session:" + sessionId + "//Points.LayerDefinition");
        resourceService.SetResource(resourceID, byteReader, null);
        //��������IJ㶨�����ݣ������ã�
        MgByteSink byteSink = new MgByteSink(resourceService.GetResourceContent(resourceID));
        string filePath = "C:\\Temp\\LayerDefinition.xml";
        byteSink.ToFile(filePath);

        // �����㲢��ӵ�����͵�ͼ��
        MgLayer newLayer = CreateLayerResource(resourceID, resourceService, "Points", "��ʱ��", map);

        AddLayerToGroup(newLayer, "Analysis", "����", map);

        MgLayerCollection layerCollection = map.GetLayers();
        if (layerCollection.Contains("Points"))
        {
            MgLayer pointsLayer = layerCollection.GetItem("Points");
            pointsLayer.SetVisible(true);
        }
        // �����ͼ
        map.Save(resourceService);

        return true;
    }
Example #5
0
        public void OpenMarkup()
        {
            MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService);

            MgMap map = new MgMap();
            map.Open(resourceService, GetParameter(this.args, "MAPNAME"));

            // Create the Layer Groups

            MgLayerGroup markupGroup = null;
            MgLayerGroupCollection layerGroups = map.GetLayerGroups();
            if (layerGroups.Contains("_Markup"))
            {
                markupGroup = layerGroups.GetItem("_Markup");
            }
            else
            {
                markupGroup = new MgLayerGroup("_Markup");
                markupGroup.SetVisible(true);
                markupGroup.SetLegendLabel("Markup");
                markupGroup.SetDisplayInLegend(false);
                layerGroups.Add(markupGroup);
            }

            // Add the Markup Layer

            MgResourceIdentifier markupLayerResId = new MgResourceIdentifier(GetParameter(this.args, "MARKUPLAYER"));
            MgLayer markupLayer = new MgLayer(markupLayerResId, resourceService);
            markupLayer.SetName("_" + markupLayerResId.GetName());
            markupLayer.SetLegendLabel(markupLayerResId.GetName());
            markupLayer.SetDisplayInLegend(false);
            markupLayer.SetSelectable(true);
            markupLayer.SetGroup(markupGroup);
            map.GetLayers().Insert(0, markupLayer);

            map.Save(resourceService);
        }
Example #6
0
    //---------------------------------------------------------------------------------------
    //
    //        ���ܣ�����һ����ΪtempParcel����ʱ��
    //
    //         ���ߣ�
    //
    //         ���ڣ� 2007.5.23
    //        
    //         �޸���ʷ����
    //        
    //---------------------------------------------------------------------------------------
    public void createTempParcels(MgPolygon geom, ParcelProperty newParcel, string sessionId)
    {
        MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);
        MgResourceService resService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);

        // ��ȡ��ͼ����
        MgMap map = new MgMap();
        map.Open(resService, "Sheboygan");
        // ������ʱ��
           MgResourceIdentifier tempLayerSourceId = new MgResourceIdentifier("Session:" + sessionId + "//tempParcel.FeatureSource");

        MgLayer tempParcelLayer = getLayerByName(map, "TempParcels");
        if (tempParcelLayer == null)
        {
            createTempParcelFeatureSource(featureService, tempLayerSourceId);
            tempParcelLayer = createTempParcelLayer(resService, tempLayerSourceId, sessionId);
            map.GetLayers().Insert(0, tempParcelLayer);
        }

        //��Ҫ��Դ�в���Ҫ������
        MgPropertyCollection props = populateParcelFeatureAttributes(geom, newParcel);
        MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
        commands.Add(new MgInsertFeatures("tempParcel", props));
        featureService.UpdateFeatures(tempLayerSourceId, commands, false);

        tempParcelLayer.SetVisible(true);
        tempParcelLayer.ForceRefresh();
        map.Save(resService);
    }
Example #7
0
        public string AddNaaz(double X, double Y, string MapSession, string mapName)
        {
            try
            {
                string dataSource = "Session:" + MapSession + "//RedlineSymbol.FeatureSource";
                string layerDef = "Session:" + MapSession + "//RedlineSymbol.LayerDefinition";
                //  MgSiteConnection site = MGMapObject.GetMgSite(MapSession);

                MgUserInformation userInfo = new MgUserInformation(MapSession);
                MgSiteConnection siteConnection = new MgSiteConnection();
                siteConnection.Open(userInfo);

                // Create a ReserviceService object and use it to open the Map
                // object from the sessions repository. Use the Map object to
                // determine if the "AddressMarker" layer is visible.

                MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService;
                MgMap map = new MgMap();
                map.Open(resourceService, mapName);
              //  MgLayer locationLayer = GetLayerByName(map, "LocationMarker");

                if (siteConnection == null)
                {
                    return "יש לרענן את האתר , לחיצה על כפתור הבית בפינה השמאלית עליונה";
                }
                MgFeatureService featureSrvc = siteConnection.CreateService(2) as MgFeatureService;
                MgResourceService resourceSrvc = siteConnection.CreateService(0) as MgResourceService;
                MgResourceIdentifier dataSourceId = new MgResourceIdentifier(dataSource);
                MgResourceIdentifier layerDefId = new MgResourceIdentifier(layerDef);
                //MgMap map = MGMapObject.GetMgMap(resourceSrvc, mapName);
                MgGeometryFactory geomFactory = new MgGeometryFactory();
                MgPoint geom = geomFactory.CreatePoint(geomFactory.CreateCoordinateXY(X, Y));
                if (DataSourceExists(resourceSrvc, dataSourceId))
                {
                    resourceSrvc.DeleteResource(dataSourceId);
                }
                MgClassDefinition classDef = CreateFeatureClass("RedlineSymbol", "RedlineSymbol");
                AddFeatureClassProperty(classDef, "KEY", 7, true);
                SetGeometryProp(classDef);
                MgFeatureSchema schema = CreateSchema(classDef, "RedlineSymbolShema", "RedlineSymbolShema");
                MgCreateSdfParams parameters = new MgCreateSdfParams("ArbitraryXY", GetMapSrs(map), schema);
                featureSrvc.CreateFeatureSource(dataSourceId, parameters);
                MgLayerCollection layers = map.GetLayers();
                MgLayer layer = FindLayer(layers, layerDef);
                LayerDefinitionFactory LayerDeffactory = new LayerDefinitionFactory();
                if ((layer == null) && LayerDeffactory.CreateLayerDef("SymbolLayerDef_Cell", dataSource, "RedlineSymbol", ""))
                {
                    resourceSrvc.SetResource(layerDefId, LayerDeffactory.layerDefContent, null);
                    layer = new MgLayer(layerDefId, resourceSrvc);
                    layer.SetDisplayInLegend(false);
                    layer.SetSelectable(false);
                    layer.SetVisible(true);
                    layer.SetLegendLabel("ZoomSymbol");
                    layers.Insert(0, layer);
                }
                MgPropertyCollection featureProps = new MgPropertyCollection();
                AddPointFeature("RedlineSymbol", featureProps, geom, featureSrvc, dataSourceId);
                if (layer != null)
                {
                    layer.ForceRefresh();
                }
                map.Save(resourceSrvc);
                siteConnection = null;
                map = null;
                dataSourceId = null;
                layerDefId = null;
                featureSrvc = null;
                resourceSrvc = null;
                geomFactory = null;
                geom = null;
                classDef = null;
                schema = null;
                featureProps = null;
                parameters = null;
                layers = null;
                layer = null;
                LayerDeffactory = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                return "Ok";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
Example #8
0
        public string getPlanMapImageAsBase64String(string planID, string imageWidth, string imageHeight)
        {
            try
            {
                MgUserInformation userInfo = null;
                string mapWebTierInit = ConfigurationManager.AppSettings["MGWebTierInit"].ToString();
                MapGuideApi.MgInitializeWebTier(mapWebTierInit);

                // Om kartsession finns för applikationssession använd den annars skapa ny kartssitesession
                string mapSiteSessionID = null;
                if (Session["MapSiteSessionID"] != null)
                {
                    mapSiteSessionID = Session["MapSiteSessionID"].ToString();
                    userInfo = new MgUserInformation(mapSiteSessionID);
                }
                else
                {
                    // Initierar kartsite och kartsession
                    string mapUserName = ConfigurationManager.AppSettings["MGUserName"].ToString();
                    string mapUserPass = ConfigurationManager.AppSettings["MGUserPass"].ToString();

                    userInfo = new MgUserInformation(mapUserName, mapUserPass);
                    MgSite mapSite = new MgSite();
                    mapSite.Open(userInfo);

                    userInfo.Dispose();

                    mapSiteSessionID = mapSite.CreateSession();

                    //mapSite.Close();

                    Session["MapSiteSessionID"] = mapSiteSessionID;

                    userInfo = new MgUserInformation(mapSiteSessionID);
                }

                //bool test = resSvc.ResourceExists(mapResId);

                string mapSurfaceFactor = ConfigurationManager.AppSettings["MGMapSurfaceFactor"].ToString();
                string mapRes = ConfigurationManager.AppSettings["MGMapResource"].ToString();
                string planRes = ConfigurationManager.AppSettings["MGPlanytorResource"].ToString();
                string planClassName = ConfigurationManager.AppSettings["MGPlanytorClassName"].ToString();
                string planFilterColumn = ConfigurationManager.AppSettings["MGPlanytorFilterColumn"].ToString();
                string planGeometryColumn = ConfigurationManager.AppSettings["MGPlanytorGeometryColumn"].ToString();
                string planytorStrokeRgbaColor = ConfigurationManager.AppSettings["MGPlanytorStrokeRgbaColor"].ToString();
                string planytorForegroundRgbaColor = ConfigurationManager.AppSettings["MGPlanytorForegroundRgbaColor"].ToString();

                string mapImageSizeFromServer = ConfigurationManager.AppSettings["MGMapImageSizeFromServer"].ToString();

                // Standardvärde för storlek på kartbild, används om värde ej finns i Settings.config eller skickas in som parametrar i webbmetod
                string mapImageWidthPixel = "400";
                string mapImageHeightPixel = "300";
                // Väljer bredd och höjd på kartbild om värde ska finnas i Settings.config samt indikeras att de ska användas
                // annars förväntas värde skickas med i webbmetod
                if (mapImageSizeFromServer.ToLower() == "true")
                {
                    mapImageWidthPixel = ConfigurationManager.AppSettings["MGMapImageWidth"].ToString();
                    mapImageHeightPixel = ConfigurationManager.AppSettings["MGMapImageHeight"].ToString();
                }
                else
                {
                    if (!string.IsNullOrWhiteSpace(imageWidth) && !string.IsNullOrWhiteSpace(imageHeight))
                    {
                        mapImageWidthPixel = imageWidth;
                        mapImageHeightPixel = imageHeight;
                    }
                }

                MgSiteConnection siteConnection = new MgSiteConnection();
                siteConnection.Open(userInfo);

                MgResourceService resSvc = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
                MgResourceIdentifier mapResId = new MgResourceIdentifier(mapRes);
                MgFeatureService featSvc = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);
                MgResourceIdentifier planResId = new MgResourceIdentifier(planRes);

                // Filter för planDoc efter planDoc-ID
                MgFeatureQueryOptions featureQuery = new MgFeatureQueryOptions();
                featureQuery.SetFilter(planFilterColumn + " = " + planID);

                MgFeatureReader featureReader = featSvc.SelectFeatures(planResId, planClassName, featureQuery);
                MgByteReader byteReaderGeometry = null;
                MgAgfReaderWriter agfReaderWriter = new MgAgfReaderWriter();
                MgGeometryCollection geometryCollection = new MgGeometryCollection();
                int featureCount = 0;
                try
                {
                    while (featureReader.ReadNext())
                    {
                        byteReaderGeometry = featureReader.GetGeometry(planGeometryColumn);
                        MgGeometry districtGeometry = agfReaderWriter.Read(byteReaderGeometry);
                        geometryCollection.Add(districtGeometry);

                        featureCount++;
                    }
                }
                finally
                {
                    featureReader.Close();
                }

                MgGeometryFactory geometryFactory = new MgGeometryFactory();
                MgMultiGeometry multiGeometry = geometryFactory.CreateMultiGeometry(geometryCollection);

                MgMap map = new MgMap(siteConnection);

                MgEnvelope envelope = multiGeometry.Envelope();

                // Anpassar ev. punkt till komma i tal som hanteras som textsträng för kommande konvertering
                if (mapImageHeightPixel.IndexOf(".") != -1)
                {
                    mapImageHeightPixel = mapImageHeightPixel.Replace(".", ",");
                }
                if (mapImageWidthPixel.IndexOf(".") != -1)
                {
                    mapImageWidthPixel = mapImageWidthPixel.Replace(".", ",");
                }

                // Önskad bilds höjd och bredd i punkter
                double imageHeightPixel = Convert.ToDouble(mapImageHeightPixel);
                double imageWidthPixel = Convert.ToDouble(mapImageWidthPixel);

                map.DisplayDpi = 120;

                double heightEnvelopeN = envelope.Height;
                double widthEnvelopeE = envelope.Width;

                // Anpassar utbredningen på sökta planer (envelope) till bildens format för att bevara skalriktighet
                string mapFarthest = string.Empty;
                if (heightEnvelopeN > widthEnvelopeE)
                    mapFarthest = "height";
                else
                    mapFarthest = "width";

                string imageFarthest = string.Empty;
                if (imageHeightPixel > imageWidthPixel)
                    imageFarthest = "height";
                else
                    imageFarthest = "width";

                double scale = 1.0;
                const double inch = 2.54;

                // Ändring av kartans utbredning och addering av utrymme i kartans bild runt planavgränsningen
                // Map = avgränsning enligt planytan (utbredning i kartan), Image = önskad bild att skapa med kartan
                // Om: kartans höjd är längst & bildens bredd är längst
                if (mapFarthest == "height" && imageFarthest == "width")
                {
                    scale = imageWidthPixel / imageHeightPixel * inch;

                    widthEnvelopeE = imageWidthPixel / imageHeightPixel * heightEnvelopeN * scale;
                }
                // Om: kartans bredd är längst & bildens höjd är längst
                else if (mapFarthest == "width" && imageFarthest == "height")
                {
                    scale = imageHeightPixel / imageWidthPixel * inch;

                    heightEnvelopeN = imageHeightPixel / imageWidthPixel * widthEnvelopeE * scale;
                }
                // Om: kartans höjd är längst & bildens höjd är längst
                else if (mapFarthest == "height" && imageFarthest == "height")
                {
                    double compareSide = (heightEnvelopeN / (imageHeightPixel / imageWidthPixel));
                    bool isCompareSideFarthest = false;
                    if (compareSide > widthEnvelopeE)
                    {
                        isCompareSideFarthest = true;
                    }
                    else
                    {
                        isCompareSideFarthest = false;
                    }

                    scale = imageHeightPixel / imageWidthPixel * inch;

                    if (isCompareSideFarthest)
                    {
                        widthEnvelopeE = heightEnvelopeN / (imageHeightPixel / imageWidthPixel) * scale;
                    }
                    else
                    {
                        heightEnvelopeN = (imageHeightPixel / imageWidthPixel) * widthEnvelopeE * scale;
                    }
                }
                // Om(annars): kartans bredd är längst & bildens bredd är längst
                else
                {
                    double compareSide = (widthEnvelopeE / (imageWidthPixel / imageHeightPixel));
                    bool isCompareSideFarthest = false;
                    if (compareSide > heightEnvelopeN)
                    {
                        isCompareSideFarthest = true;
                    }
                    else
                    {
                        isCompareSideFarthest = false;
                    }

                    scale = imageWidthPixel / imageHeightPixel * inch;

                    if (isCompareSideFarthest)
                    {
                        heightEnvelopeN = widthEnvelopeE / (imageWidthPixel / imageHeightPixel) * scale;
                    }
                    else
                    {
                        widthEnvelopeE = heightEnvelopeN * (imageWidthPixel / imageHeightPixel) * scale;
                    }
                }

                double mapSurfaceFactorDbl = Convert.ToDouble(mapSurfaceFactor.Replace('.', ','));
                double newHeightN = heightEnvelopeN * mapSurfaceFactorDbl;
                double newWidthE = widthEnvelopeE * mapSurfaceFactorDbl;
                MgCoordinate lowerLeft = envelope.LowerLeftCoordinate;
                MgCoordinate upperRight = envelope.UpperRightCoordinate;
                envelope = new MgEnvelope(lowerLeft.X - (newWidthE - widthEnvelopeE) / 2,
                                          lowerLeft.Y - (newHeightN - heightEnvelopeN) / 2,
                                          upperRight.X + (newWidthE - widthEnvelopeE) / 2,
                                          upperRight.Y + (newHeightN - heightEnvelopeN) / 2);

                map.Create(resSvc, mapResId, mapResId.Name);

                // Skapa lagerdefinition i XML
                DefineAreaLayer areaLayer = new DefineAreaLayer();
                areaLayer.FeatureName = planClassName;
                areaLayer.FeatureSourceName = planRes;
                areaLayer.GeometryColumnName = planGeometryColumn;
                areaLayer.Filter = planFilterColumn + " = " + planID;

                LayerScaleRangeCollection lsrCollection = new LayerScaleRangeCollection();

                LayerScaleRange lsr = new LayerScaleRange();
                // MinScale applikations-default till 0 (inklusive) om utelämnat, MaxScale applikations-default till kartans maxskala (exklusive) om utelämnat
                //lsr.MinScale = "0";
                //lsr.MaxScale = "100000000";
                AreaTypeStyle ats = new AreaTypeStyle();

                AreaRuleCollection arCollection = new AreaRuleCollection();

                AreaRule ar = new AreaRule();
                //ar.Filter = planFilterColumn + " = " + planID;
                ar.LegendLabel = "Plan" + planID;
                AreaSymbolization2D symb2D = new AreaSymbolization2D();
                Fill fill = new Fill();
                fill.BackgroundColor = "FFFF0000";
                fill.FillPattern = "Solid";
                fill.ForegroundColor = convertRgbsToHexColor(planytorForegroundRgbaColor);
                Stroke stroke = new Stroke();
                stroke.Color = convertRgbsToHexColor(planytorStrokeRgbaColor);
                stroke.LineStyle = "Solid";
                stroke.Thickness = "1";
                stroke.Unit = "Points";
                symb2D.Fill = fill;
                symb2D.Stroke = stroke;
                ar.Symbolization2D = symb2D;
                arCollection.Add(ar);

                ats.AreaRules = arCollection;

                lsr.AreaTypeStyle = ats;

                lsrCollection.Add(lsr);

                areaLayer.LayerScaleRanges = lsrCollection;

                XmlDocument xmlFile = new XmlDocument();
                //XDocument xmlFile = new XDocument();
                // om returnerande av xml-dokument
                //xmlFile = areaLayer.CreateLayerDefinitionAsXmlDocument();
                // om returnerande av xml-sträng
                xmlFile.LoadXml(areaLayer.CreateLayerDefinitionAsXmlString());
                //xmlFile = areaLayer.CreateLayerDefinitionAsXDocument();
                //xmlFile.Save(Server.MapPath(this.Context.Request.ApplicationPath) + "XmlTestLayerDefinition.xml");

                using (MemoryStream msNewPlanLayer = new MemoryStream())
                {
                    xmlFile.Save(msNewPlanLayer);
                    msNewPlanLayer.Position = 0L;
                    //Note we do this to ensure our XML content is free of any BOM characters
                    byte[] layerDefinition = msNewPlanLayer.ToArray();
                    Encoding utf8 = Encoding.UTF8;
                    String layerDefStr = new String(utf8.GetChars(layerDefinition));
                    layerDefinition = new byte[layerDefStr.Length - 1];
                    int byteCount = utf8.GetBytes(layerDefStr, 1, layerDefStr.Length - 1, layerDefinition, 0);
                    // Save the new layer definition to the session repository
                    MgByteSource byteSource = new MgByteSource(layerDefinition, layerDefinition.Length);
                    MgResourceIdentifier layerResourceID = new MgResourceIdentifier("Session:" + mapSiteSessionID + "//" + "planytor" + ".LayerDefinition"); //"SearchedPlan" + planID + ".LayerDefinition");
                    resSvc.SetResource(layerResourceID, byteSource.GetReader(), null);

                    MgLayer newPlanLayer = new MgLayer(layerResourceID, resSvc);
                    newPlanLayer.SetName("Sökta planer");
                    newPlanLayer.SetVisible(true);
                    newPlanLayer.SetLegendLabel("Sökta planer");
                    newPlanLayer.SetDisplayInLegend(true);
                    MgLayerCollection layerCollection = map.GetLayers();
                    if (!layerCollection.Contains(newPlanLayer))
                    {
                        // Insert the new layer at position 0 so it is at the top
                        // of the drawing order
                        layerCollection.Insert(0, newPlanLayer);
                    }
                    else
                    {
                        layerCollection.Remove(newPlanLayer);
                        layerCollection.Insert(0, newPlanLayer);
                    }

                    map.Save();
                }

                double mapScale = map.ViewScale;

                // XML-dokument till ren text
                //StringWriter stringWriter = new StringWriter();
                //XmlWriter xmlTextWriter = XmlWriter.Create(stringWriter);
                //xmlFile.WriteTo(xmlTextWriter);
                //xmlTextWriter.Flush();
                string xmlSelection = string.Empty;
                //string xmlSelection = stringWriter.GetStringBuilder().ToString();

                MgSelection selection = null;
                if (!string.IsNullOrEmpty(xmlSelection))
                {
                    selection = new MgSelection(map, xmlSelection);
                }
                else
                {
                    selection = new MgSelection(map);
                }

                MgColor color = new MgColor("255,255,255");

                // Skapar bild av kartan
                MgRenderingService renderingService = (MgRenderingService)siteConnection.CreateService(MgServiceType.RenderingService);
                //MgByteReader byteReader = renderingService.RenderMap(map, selection, "PNG");
                MgByteReader byteReader = renderingService.RenderMap(map, selection, envelope, Convert.ToInt32(imageWidthPixel), Convert.ToInt32(imageHeightPixel), color, "PNG");
                MemoryStream ms = new MemoryStream();
                byte[] byteBuffer = new byte[1024];
                int numBytes = byteReader.Read(byteBuffer, 1024);
                while (numBytes > 0)
                {
                    ms.Write(byteBuffer, 0, numBytes);
                    numBytes = byteReader.Read(byteBuffer, 1024);
                }
                byte[] mapImageByte = ms.ToArray();
                string imageBase64String = Convert.ToBase64String(mapImageByte);

                map.Dispose();
                siteConnection.Dispose();

                DataTable dtResult = new DataTable();
                DataColumn dc = new DataColumn("MAPIMAGEBASE64");
                dtResult.Columns.Add(dc);
                dc = new DataColumn("WIDTH");
                dtResult.Columns.Add(dc);
                dc = new DataColumn("HEIGHT");
                dtResult.Columns.Add(dc);
                DataRow dr = dtResult.NewRow();
                dr["MAPIMAGEBASE64"] = imageBase64String;
                dr["WIDTH"] = imageWidthPixel;
                dr["HEIGHT"] = imageHeightPixel;
                dtResult.Rows.Add(dr);

                //TODO: MAP: Vad kan returneras, base64 eller länk där bild temporärt genereras på server
                //JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                //return jsonSerializer.Serialize(imageBase64String);

                return getDatatableAsJson(dtResult);
            }
            catch (System.Exception ex)
            {
                UtilityException.LogException(ex, "Webbmetod : getPlanMapImageAsBase64String", true);
                return null;
            }
        }
Example #9
0
        private void ClearSessions()
        {
            try
            {
                InitializeWebTier();

                MgUserInformation userInfo = new MgUserInformation(mgSessionId);
                MgSiteConnection siteConnection = new MgSiteConnection();
                siteConnection.Open(userInfo);
                MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
                MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);

                MgMap map = new MgMap();
                map.Open(resourceService, mgMap);

                MgLayerCollection layerCol = map.GetLayers();

                string layerName = "LocationMarker";

            MgLayer layerToRemove = null;
            foreach(MgLayer layer in layerCol)
            {
              if(layer.Name == layerName)
              {
            layerToRemove = layer;
            break;
              }
            }

            if(layerToRemove != null)
            {
              layerCol.Remove(layerToRemove);
            }

                map.Save(resourceService);
                Xcoord.Value = "";
                Ycoord.Value = "";
                kanam.Value = "10000";
                targetsnewTitle.InnerHtml = "";
                targetsnew.InnerHtml = "";
                targetsold.InnerHtml="";
                targetsoldTitle.InnerHtml = "";

                Response.Write("<script>try{ parent.parent.mapFrame.Refresh();   parent.parent.mapFrame.ZoomToSelection();}catch(e){}</script>");
                /* success = true;*/

            }
            catch (Exception exx)
            {

            }
        }
Example #10
0
        protected void Button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(Xcoord.Value) || string.IsNullOrEmpty(Ycoord.Value) || string.IsNullOrEmpty(kanam.Value))
            {
               //   Response.Write("<script type='text/javascript'>try{ zoom();}catch(e){}</script>");
                ClientScript.RegisterStartupScript(GetType(), "zoomme", "<script>try{ zoomzfd();}catch(e){}</script>");
              return;
            }

            /*

             String mgSessionId = GetRequestParameters()["SESSION"];
             String mgMap = GetRequestParameters()["map"];
             //GeocodeAddress addr = null;
             bool success = false;
             decimal LatInput=0;
             decimal LonInput=0;*/

                // Initialize the web-extensions and connect to the Site using
                // the session identifier passed in the query string.

            try
            {

                InitializeWebTier();
                //MgUserInformation userInfo = new MgUserInformation(mgSessionId);

              //  mgSessionId = site.CreateSession();
                MgUserInformation userInfo = new MgUserInformation(mgSessionId);
                MgSiteConnection siteConnection = new MgSiteConnection();
               siteConnection.Open(userInfo);
                decimal LatInput = System.Convert.ToDecimal(Xcoord.Value);
                decimal LonInput = System.Convert.ToDecimal(Ycoord.Value);
                /* LatInput = System.Convert.ToDecimal(GetRequestParameters()["LatInput"]);
                 LonInput = System.Convert.ToDecimal(GetRequestParameters()["LonInput"]);*/

                // Make the request to geocoder.us passing the address.
                //addr = requestGeocodeAddress(address);

                if (LatInput != 0 && LonInput != 0)
                {
                      //Request the specified address to the geocode service using REST, the
            // GET interface
            //

                    if (targetsnew.InnerHtml == "")
                    {
                        targetsnewTitle.InnerHtml = "מיקום נוכחי :";
                        targetsoldTitle.InnerHtml = "";
                        targetsnew.InnerHtml = "<table>";
                        targetsnew.InnerHtml += "<tr><td><img src=\"../images/pushpinblue.jpg\">";
                        targetsnew.InnerHtml += "<a href=\"gotopoint.aspx?X=" + LonInput + "&Y=" + LatInput + "&Scale=2000\" target=\"scriptFrame\">  מיקום נמצא </a></td></tr>";
                        targetsnew.InnerHtml += "<tr><td align=left>X: " + LonInput + "</td></tr>";
                        targetsnew.InnerHtml += "<tr><td align=left>Y: " + LatInput + "<hr></td></tr>";
                        targetsnew.InnerHtml += "</table>";
                    }
                    else
                    {
                        targetsoldTitle.InnerHtml = "מיקום קודם :";
                        targetsold.InnerHtml += targetsnew.InnerHtml;
                        targetsnew.InnerHtml = "<table>";
                        targetsnew.InnerHtml += "<tr><td><img src=\"../images/pushpinblue.jpg\">";
                        targetsnew.InnerHtml += "<a href=\"gotopoint.aspx?X=" + LonInput + "&Y=" + LatInput + "&Scale=2000\" target=\"scriptFrame\">  מיקום נמצא </a></td></tr>";
                        targetsnew.InnerHtml += "<tr><td align=left>X: " + LonInput + "</td></tr>";
                        targetsnew.InnerHtml += "<tr><td align=left>Y: " + LatInput + "<hr></td></tr>";
                        targetsnew.InnerHtml += "</table>";

                    }
                    // The geocode successfully returned a location.

                    //if (IsDebugAssembly(this.GetType().Assembly))
                    //    System.Diagnostics.Debugger.Launch();
                    MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService);
                    MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService);

                    MgMap map = new MgMap();
                  map.Open(resourceService, mgMap);
                 //   map.Open(mgMap);
                    // Check the map for the AddressMarker layer. If it does not
                    // exist then create a feature source to store address results
                    // and a layer to display them.
                    MgResourceIdentifier locationMarkerDataResId = new MgResourceIdentifier("Session:" + mgSessionId + "//LocationMarker.FeatureSource");
                  //  Session:7f4231a2-0d7e-11e2-8000-000c294ca3a6_en_7F0000010AFC0AFB0AFA//a2f5e4fb-0c3c-4ee7-bb5d-c8f4a226a68b.FeatureSource
                   // MgResourceIdentifier locationMarkerDataResId = new MgResourceIdentifier("Library://rany1/Data/findLocation/temp/LocationMarker.FeatureSource");
                  //  string layerDef = "Session:" + mgSessionId + "//LocationMarker.FeatureSource";
                    //string dataSource = "Library://rany1/Data/LocationMarker.FeatureSource";

                    /*string layerDef  = "Library://rany1/Layers/LocationMarker.LayerDefinition";

                    MgLayerCollection colLays = map.GetLayers();

                    MgLayer layer = FindLayer(colLays, layerDef);*/

                    ////                       MgLayer locationLayer = FindLayerByName(,"LocationMarker") ;//GetLayerByName(map, "LocationMarker");

                    //MgLayerCollection colLays = map.GetLayers();
                    MgLayerCollection colLays = map.GetLayers();
                    MgLayer locationLayer = FindLayerByName(colLays, "LocationMarker");

                    if (locationLayer == null)
                    {
                       // diverr.InnerHtml += " לא נמצאו שכבות LocationMarker ";
                        lf.CreateLocationMarkerFeatureSource(featureService, locationMarkerDataResId, map);
                        locationLayer = lf.CreateLocationMarkerLayer(resourceService, locationMarkerDataResId, mgSessionId);

                        map.GetLayers().Insert(0, locationLayer);
                    }
                    else if (locationLayer.GetVisible())
                    {
                        // If the layer exists and is visible, then display the
                        // previous results.

                        //EmitAddressResults(featureService, locationMarkerDataResId, mgSessionId, Response);
                        EmitLocationResults(featureService, locationMarkerDataResId, mgSessionId, HttpContext.Current.Response);
                    }

                    // Insert the results of the Geo-Code into the temporary
                    // feature source and ensure the address marker layer
                    // is visible.

                    MgAgfReaderWriter geometryReaderWriter = new MgAgfReaderWriter();
                    MgGeometryFactory geometryFactory = new MgGeometryFactory();
                    MgPoint locationPoint = geometryFactory.CreatePoint(geometryFactory.CreateCoordinateXY(Convert.ToDouble(LonInput), Convert.ToDouble(LatInput)));

                    MgPropertyCollection properties = new MgPropertyCollection();
                    properties.Add(new MgStringProperty("Address", ""));
                    properties.Add(new MgGeometryProperty("Location", geometryReaderWriter.Write(locationPoint)));

                    MgFeatureCommandCollection commands = new MgFeatureCommandCollection();
                    commands.Add(new MgInsertFeatures("LocationMarker", properties));

                    featureService.UpdateFeatures(locationMarkerDataResId, commands, false);

                    locationLayer.SetVisible(true);
                    locationLayer.ForceRefresh();

                    map.Save(resourceService);

                    Response.Write("<script type='text/javascript'>try{ parent.parent.ZoomToView(" + px1.Value + ", " + py1.Value + ", " + kanam.Value + ", true);parent.parent.mapFrame.Refresh();}catch(e){}</script>");
                    /* success = true;*/

                }
                else
                {
                    // Response.Write("<tr><td>נקודת הציון לא נמצאה: <hr></td></tr>");
                }
            }
            catch (MgException eee)
            {
               // Response.Write("<script type='text/javascript'>try{alert('rany'); parent.parent.ZoomToView(" + px1.Value + ", " + py1.Value + ", " + kanam.Value + ", true);parent.parent.mapFrame.Refresh();}catch(e){}</script>");
               // Response.Write("<tr><td>" + eee.GetExceptionMessage() + "</td></tr>");
             //   Response.Write("<tr><td>" + eee.InnerException.Message + "</td></tr>");
                Response.Write("<tr><td>" + eee.ToString() + "</td></tr>");
                Response.Write("<tr><td>" + eee.GetBaseException() + "</td></tr>");
                Response.Write("<tr><td>" + eee.GetStackTrace()+ "</td></tr>");
                Response.Write("<tr><td>" + eee.GetExceptionMessage() + "</td></tr>");

                  Response.Write("<tr><td class=\"Spacer\"></td></tr>");
                 // Response.Write("<tr><td>" + eee.GetDetails() + "</td></tr>");
            }
        }