public MgMapBase CreateMap(string coordSys, MgEnvelope env, string name) { var map = new MgMap(_siteConn); map.Create(coordSys, env, name); return(map); }
//---------------------------------------------------------------------------------------- // �� �ܣ� ����ͼ���Ϊͼ���ļ� // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public bool GenerateMapImage() { // ��ȡ��Դ�������Ⱦ������� MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgRenderingService renderingService = (MgRenderingService)siteConnection.CreateService(MgServiceType.RenderingService); // ��ͼ MgMap map = new MgMap(); map.Open(resourceService, "Sheboygan"); // ����ѡ�� MgSelection selection = new MgSelection(map); selection.Open(resourceService, "Sheboygan"); // ָ����Χ MgEnvelope extent = map.GetMapExtent(); double x = 0.5*extent.GetLowerLeftCoordinate().GetX(); double y = 0.5*extent.GetLowerLeftCoordinate().GetY() ; MgColor color = new MgColor("FFFFBF20"); // ���ɲ�����ͼ���ļ� MgByteReader byteReader = renderingService.RenderMap(map, selection, extent, 450, 613, color, "PNG"); MgByteSink byteSink = new MgByteSink(byteReader); string filePath = "C:\\Temp\\Map.PNG"; byteSink.ToFile(filePath); return true; }
public MgMapBase CreateMap(MgResourceIdentifier mapDefinition) { var map = new MgMap(_siteConn); map.Create(mapDefinition, mapDefinition.Name); return(map); }
private MgByteReader Plot(MapGuideViewerInputModel input, bool useLayout, double?scale) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgPoint center = map.ViewCenter; MgCoordinate coord = center.Coordinate; MgMappingService mappingService = (MgMappingService)conn.CreateService(MgServiceType.MappingService); MgDwfVersion dwfVersion = new MgDwfVersion("6.01", "1.2"); MgPlotSpecification plotSpec = new MgPlotSpecification(8.5f, 11f, MgPageUnitsType.Inches, 0f, 0f, 0f, 0f); plotSpec.SetMargins(0.5f, 0.5f, 0.5f, 0.5f); MgLayout layout = null; if (useLayout) { MgResourceIdentifier layoutRes = new MgResourceIdentifier("Library://Samples/Sheboygan/Layouts/SheboyganMap.PrintLayout"); layout = new MgLayout(layoutRes, "City of Sheboygan", MgPageUnitsType.Inches); } if (!scale.HasValue) { return(mappingService.GeneratePlot(map, plotSpec, layout, dwfVersion)); } else { MgCoordinate mapCenter = map.GetViewCenter().GetCoordinate(); return(mappingService.GeneratePlot(map, mapCenter, scale.Value, plotSpec, layout, dwfVersion)); } }
public MarkupManager(NameValueCollection incomingArgs) { try { /*if (IsDebugAssembly(this.GetType().Assembly)) System.Diagnostics.Debugger.Launch();*/ this.args = incomingArgs; this.site = new MgSiteConnection(); this.site.Open(new MgUserInformation(GetParameter(this.args, "SESSION"))); if (!string.IsNullOrEmpty(GetParameter(this.args, "DIR"))) libraryPath = GetParameter(this.args, "DIR"); else { MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService); MgMap map = new MgMap(); map.Open(resourceService, GetParameter(this.args, "MAPNAME")); string path = map.MapDefinition.Path; if (path.ToLower().EndsWith("maps")) path = path.Substring(0, path.Length - 4); //Debug // libraryPath = Path.Combine(String.Format("Library://{0}", path), "Markup/"); // libraryPath = "Library://" + path + "Markup/"; // Response.Write(libraryPath); } } catch (System.Exception ex) { throw ex; // Response.Write("\n MarkupManager manager" + ex.InnerException); } }
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; }
private MgByteReader Plot(MapGuideViewerInputModel input, bool useLayout, double? scale) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgPoint center = map.ViewCenter; MgCoordinate coord = center.Coordinate; MgMappingService mappingService = (MgMappingService)conn.CreateService(MgServiceType.MappingService); MgDwfVersion dwfVersion = new MgDwfVersion("6.01", "1.2"); MgPlotSpecification plotSpec = new MgPlotSpecification(8.5f, 11f, MgPageUnitsType.Inches, 0f, 0f, 0f, 0f); plotSpec.SetMargins(0.5f, 0.5f, 0.5f, 0.5f); MgLayout layout = null; if (useLayout) { MgResourceIdentifier layoutRes = new MgResourceIdentifier("Library://Samples/Sheboygan/Layouts/SheboyganMap.PrintLayout"); layout = new MgLayout(layoutRes, "City of Sheboygan", MgPageUnitsType.Inches); } if (!scale.HasValue) { return mappingService.GeneratePlot(map, plotSpec, layout, dwfVersion); } else { MgCoordinate mapCenter = map.GetViewCenter().GetCoordinate(); return mappingService.GeneratePlot(map, mapCenter, scale.Value, plotSpec, layout, dwfVersion); } }
public MgMapBase CreateMap(MgResourceIdentifier mapDefinition, string mapName, int width, int height, double x, double y, double scale, int dpi) { var map = new MgMap(_siteConn); map.Create(mapDefinition, mapName, width, height, x, y, scale, dpi); return(map); }
string pointTransformAndWriteZ(string geom, MgMap map) { double[] x = new double[1]; double[] y = new double[1]; double[] z = new double[1]; MgWktReaderWriter wktrwdmr = new MgWktReaderWriter(); MgPoint cntr = wktrwdmr.Read(geom).Centroid; x[0] = cntr.Coordinate.X; y[0] = cntr.Coordinate.Y; z[0] = 0; StringBuilder output = new StringBuilder(); output.Append("<table width=\"100%\" class=\"results\">"); //WGS preko MG API MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory(); string wktFrom = map.GetMapSRS(); string wktTo = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]"; MgCoordinateSystem CSSource = fact.Create(wktFrom); MgCoordinateSystem CSTarget = fact.Create(wktTo); MgCoordinateSystemTransform coordTransform = fact.GetTransform(CSSource, CSTarget); MgGeometryFactory geomFact = new MgGeometryFactory(); // GK //samo prvo višino zaenkrat, dokler ni enačbe za Z output.Append(String.Format("<tr><td class='header'><b>Map koordinates:</b></td><td class=\"results\"><table><tr><td><b>Y:</b></td><td>{0}</td></tr><tr><td><b>X:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.0}", x[0]), string.Format("{0:0.0}", y[0]))); int i = 0; //transformacija preko MG koordinatnega sistema foreach (double pointX in x) { MgCoordinate coord = geomFact.CreateCoordinateXY(x[i], y[i]); coord = coordTransform.Transform(coord); x[i] = coord.X; y[i] = coord.Y; i++; } double[] xwgs = x; double[] ywgs = y; output.Append(String.Format("<tr><td class='header'><b>WGS84:</b></td><td class=\"results\"><table><tr><td><b>Lon:</b></td><td>{0}</td></tr><tr><td><b>Lat:</b></td><td>{1}</td></tr></table></td></tr>", string.Format("{0:0.000000}", xwgs[0]), string.Format("{0:0.000000}", ywgs[0]))); output.Append("</table>"); return(output.ToString()); }
public void AddBuffer() { MgMap map = new MgMap(); map.Open(_resourceService, GetParameter(this.args, "MAPNAME")); MgSelection selection = new MgSelection(map); selection.Open(_resourceService, map.Name); MgReadOnlyLayerCollection layers = selection.GetLayers(); if (layers != null && layers.Count == 1) { MgFeatureQueryOptions opt = new MgFeatureQueryOptions(); opt.SetFilter(selection.GenerateFilter(layers[0], layers[0].FeatureClassName)); MgFeatureReader featureReader = _featureService.SelectFeatures(new MgResourceIdentifier(layers[0].FeatureSourceId), layers[0].FeatureClassName, opt); MgAgfReaderWriter agfRW = new MgAgfReaderWriter(); MgGeometryCollection inputGeometries = new MgGeometryCollection(); MgClassDefinition classDef = _featureService.GetClassDefinition( new MgResourceIdentifier(layers[0].FeatureSourceId), layers[0].FeatureClassName.Split(':')[0], layers[0].FeatureClassName.Split(':')[1]); while (featureReader.ReadNext()) { MgByteReader byteReader = featureReader.GetGeometry(classDef.DefaultGeometryPropertyName); MgGeometry geom = agfRW.Read(byteReader); inputGeometries.Add(geom); } if (inputGeometries.Count > 0) { MgCoordinateSystemFactory coordSysFactory = new MgCoordinateSystemFactory(); MgCoordinateSystem mapSrs = coordSysFactory.Create(map.MapSRS); double distance = mapSrs.ConvertMetersToCoordinateSystemUnits(7.0); MgCoordinateSystemMeasure measure = mapSrs.GetMeasure(); MgGeometryFactory geomFactory = new MgGeometryFactory(); MgGeometry buffer = geomFactory.CreateMultiGeometry(inputGeometries).Buffer(distance, measure); if (buffer != null) { MgByteReader byteReader = agfRW.Write(buffer); MgGeometryFactory geometryFactory = new MgGeometryFactory(); MgAgfReaderWriter agfWriter = new MgAgfReaderWriter(); MgPropertyCollection propertyValues = CreatePropertyCollection(byteReader); this.InsertMarkupFeature(propertyValues); } } } }
public HtzMgHelper(string userName, string userPass, string layoutId, string mapDefinition) { Init(); this._connection = new MgSiteConnection(); this._connection.Open(new MgUserInformation(userName, userPass)); this._sessionId = this._connection.GetSite().CreateSession(); this._map = new MgMap(); MgResourceIdentifier mapDef = new MgResourceIdentifier(mapDefinition); this._map.Create(this.ResourceService, mapDef, mapDef.Name); this._layoutId = layoutId; }
// GET: Search/Results public ActionResult Results(SearchInputModel input) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgLayerCollection layers = map.GetLayers(); int lidx = layers.IndexOf("Parcels"); if (lidx < 0) { throw new Exception("Layer not found on map: Parcels"); } MgLayerBase layer = layers[lidx]; MgFeatureQueryOptions query = new MgFeatureQueryOptions(); //Don't fret about the input here. This is not a SQL injection attack vector. This filter string is //not SQL, it's a FDO filter. A 'DROP TABLE' or any other destructive SQL will fail on //query execution when this filter is parsed to a FDO filter. switch (input.By) { case "OWNER": query.SetFilter("RNAME LIKE '%" + input.Query.Replace("'", "\'") + "%'"); break; case "ADDRESS": query.SetFilter("RPROPAD LIKE '%" + input.Query.Replace("'", "\'") + "%'"); break; case "BBOX": double[] parts = input.Query.Split(',').Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); if (parts.Length != 4) { throw new Exception("Invalid BBOX parameter"); } MgWktReaderWriter wktRw = new MgWktReaderWriter(); MgGeometry filterGeom = wktRw.Read(MakeWktPolygon(parts[0], parts[1], parts[2], parts[3])); query.SetSpatialFilter(layer.FeatureGeometryName, filterGeom, MgFeatureSpatialOperations.Intersects); break; default: throw new Exception("Unknown query type: " + input.By); } SearchResultViewModel vm = new SearchResultViewModel(); vm.Session = input.Session; vm.MapName = input.MapName; vm.LoadResults(layer, query); return(View(vm)); }
public MgMapBase CreateMap(MgResourceIdentifier resId) { //The test suite relies on the same map and not a new one //re-created on each test of that particular test suite if (_map != null) { return(_map); } _map = new MgMap(_siteConn); _map.Create(resId, resId.GetName()); return(_map); }
String GetLegendIcons() { // Initialize the web-tier. String realPath = Request.ServerVariables["APPL_PHYSICAL_PATH"]; String configPath = realPath + "..\\webconfig.ini"; MapGuideApi.MgInitializeWebTier(configPath); // Connect to the site. MgUserInformation userInfo = new MgUserInformation(sessionId); MgSiteConnection siteConnection = new MgSiteConnection(); siteConnection.Open(userInfo); // Get an instance of the required service(s). MgResourceService resourceService = siteConnection.CreateService(MgServiceType.ResourceService) as MgResourceService; // Get the current map. MgMap map = new MgMap(); map.Open(resourceService, mapName); // Get map layers. MgLayerCollection mgLayers = map.GetLayers(); // Define table-body rows, one per layer. int mgLayerCount = mgLayers.Count; // Get the current-visiable layer list String jsonlist = ""; for (int i = 0; i < mgLayerCount; i++) { MgLayer mgLayer = mgLayers.GetItem(i) as MgLayer; Boolean inLegend = false; String mgLayerName = mgLayer.LegendLabel; String mgLegendImage = mgLayer.GetLayerDefinition().Path + "/" + mgLayer.GetName(); String mgLayerIsVisible = mgLayer.IsVisible() ? "on" : "off"; String[] mgLayerData = new String[] { mgLegendImage, mgLayerName, mgLayerIsVisible }; for (int j = 0; j < mgLayerData.Length - 1; j++) { if (mgLayerData[mgLayerData.Length - 1] == "on" && mgLayerData[mgLayerData.Length - 2].Trim() != "") { jsonlist += mgLayerData[j] + "$"; inLegend = true; } } if (inLegend) jsonlist = jsonlist.Substring(0, (jsonlist.Length - 1)) + "@"; } return jsonlist.Substring(0, (jsonlist.Length - 1)); }
// Searches the map for a layer with the specified name. public static MgLayer GetLayerByName(MgMap map, String layerName) { MgLayer layer = null; for (int i = 0; i < map.GetLayers().GetCount(); i++) { MgLayer nextLayer = (MgLayer)map.GetLayers().GetItem(i); if (nextLayer.GetName().Equals(layerName)) { layer = nextLayer; break; } } return layer; }
// Create a temporary Feature Source to store geocode results. public void CreateLocationMarkerFeatureSource(MgFeatureService featureService, MgResourceIdentifier locationMarkerDataResId, MgMap map) { //String ll84Wkt = "GEOGCS[\"LL84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.25722293287],TOWGS84[0,0,0,0,0,0,0]],PRIMEM[\"Greenwich\",0],UNIT[\"Degrees\",1]]"; //string ll84Wkt = "LOCAL_CS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]] "; MgCoordinateSystemFactory sysCoordsFactory = new MgCoordinateSystemFactory(); string srsDefMap = map.GetMapSRS(); string mapSrsUnits = string.Empty; srsDefMap = !string.IsNullOrEmpty(srsDefMap) ? srsDefMap : "LOCAL_CS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]] "; MgCoordinateSystem srsMap = sysCoordsFactory.Create(srsDefMap); MgClassDefinition locationClass = new MgClassDefinition(); locationClass.SetName("LocationMarker"); MgPropertyDefinitionCollection properties = locationClass.GetProperties(); MgDataPropertyDefinition idProperty = new MgDataPropertyDefinition("ID"); idProperty.SetDataType(MgPropertyType.Int32); idProperty.SetReadOnly(true); idProperty.SetNullable(false); idProperty.SetAutoGeneration(true); properties.Add(idProperty); MgDataPropertyDefinition addressProperty = new MgDataPropertyDefinition("Address"); addressProperty.SetDataType(MgPropertyType.String); addressProperty.SetLength(512); properties.Add(addressProperty); MgGeometricPropertyDefinition locationProperty = new MgGeometricPropertyDefinition("Location"); locationProperty.SetGeometryTypes(MgGeometryType.Point); locationProperty.SetHasElevation(false); locationProperty.SetHasMeasure(false); locationProperty.SetReadOnly(false); locationProperty.SetSpatialContextAssociation(srsMap.GetCsCode()); properties.Add(locationProperty); MgPropertyDefinitionCollection idProperties = locationClass.GetIdentityProperties(); idProperties.Add(idProperty); locationClass.SetDefaultGeometryPropertyName("Location"); MgFeatureSchema locationSchema = new MgFeatureSchema(); locationSchema.SetName("LocationMarkerSchema"); locationSchema.GetClasses().Add(locationClass); MgCreateSdfParams sdfParams = new MgCreateSdfParams(srsMap.GetCsCode(), srsDefMap, locationSchema); featureService.CreateFeatureSource(locationMarkerDataResId, sdfParams); }
// GET: Search/Results public ActionResult Results(SearchInputModel input) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgLayerCollection layers = map.GetLayers(); int lidx = layers.IndexOf("Parcels"); if (lidx < 0) { throw new Exception("Layer not found on map: Parcels"); } MgLayerBase layer = layers.GetItem(lidx); MgFeatureQueryOptions query = new MgFeatureQueryOptions(); //Don't fret about the input here. This is not a SQL injection attack vector. This filter string is //not SQL, it's a FDO filter. A 'DROP TABLE' or any other destructive SQL will fail on //query execution when this filter is parsed to a FDO filter. switch (input.By) { case "OWNER": query.SetFilter("RNAME LIKE '%" + input.Query.Replace("'", "\'") + "%'"); break; case "ADDRESS": query.SetFilter("RPROPAD LIKE '%" + input.Query.Replace("'", "\'") + "%'"); break; case "BBOX": double[] parts = input.Query.Split(',').Select(s => double.Parse(s, CultureInfo.InvariantCulture)).ToArray(); if (parts.Length != 4) { throw new Exception("Invalid BBOX parameter"); } MgWktReaderWriter wktRw = new MgWktReaderWriter(); MgGeometry filterGeom = wktRw.Read(MakeWktPolygon(parts[0], parts[1], parts[2], parts[3])); query.SetSpatialFilter(layer.FeatureGeometryName, filterGeom, MgFeatureSpatialOperations.Intersects); break; default: throw new Exception("Unknown query type: " + input.By); } SearchResultViewModel vm = new SearchResultViewModel(); vm.Session = input.Session; vm.MapName = input.MapName; vm.LoadResults(layer, query); return View(vm); }
public void Execute(IPlatformFactory factory, ITestLogger logger) { string coordsys = "GEOGCS[\"LL84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9108\"]],AXIS[\"Lat\",NORTH],AXIS[\"Long\",EAST],AUTHORITY[\"EPSG\",\"4326\"]]"; MgEnvelope env = new MgEnvelope(10, 10, 20, 20); MgMap map1 = (MgMap)factory.CreateMap(coordsys, env, "map1"); MgMap map2 = (MgMap)factory.CreateMap(coordsys, env, "map2"); MgMap map3 = (MgMap)factory.CreateMap(coordsys, env, "map3"); MgPlotSpecification spec = new MgPlotSpecification((float)8.0, (float)11.0, "in", (float)0.0, (float)0.0, (float)5.0, (float)5.0); MgResourceIdentifier resId = new MgResourceIdentifier("Library://test.WebLayout"); MgLayout layout1 = new MgLayout(resId, "Title1", "in"); MgMapPlot plot1 = new MgMapPlot(map1, spec, layout1); MgLayout layout2 = new MgLayout(resId, "Title2", "in"); MgMapPlot plot2 = new MgMapPlot(map2, spec, layout2); MgLayout layout3 = new MgLayout(resId, "Title3", "in"); MgMapPlot plot3 = new MgMapPlot(map3, spec, layout3); MgMapPlotCollection coll = new MgMapPlotCollection(); coll.Add(plot1); coll.Add(plot2); coll.Remove(plot1); Assert.AreEqual(1, coll.Count); coll.Insert(0, plot1); coll.Insert(2, plot3); MgMapPlot tmp = coll[2]; coll[2] = tmp; Assert.AreEqual(3, coll.Count); string txt = ""; foreach (MgMapPlot plot in coll) { txt += "[" + plot.GetLayout().GetTitle() + "]"; } Assert.AreEqual("[Title1][Title2][Title3]", txt); }
public ActionResult SelectFeature(SelectInputModel input) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgLayerCollection layers = map.GetLayers(); int lidx = layers.IndexOf("Parcels"); if (lidx < 0) { throw new Exception("Layer not found on map: Parcels"); } MgLayerBase layer = layers[lidx]; MgClassDefinition clsDef = layer.GetClassDefinition(); MgPropertyDefinitionCollection props = clsDef.GetProperties(); MgPropertyDefinition idProp = props[0]; string idPropName = idProp.Name; MgFeatureQueryOptions query = new MgFeatureQueryOptions(); query.SetFilter(idPropName + " = " + input.id); MgFeatureReader reader = layer.SelectFeatures(query); MgSelection selection = new MgSelection(map, ""); MgResourceService resSvc = (MgResourceService)conn.CreateService(MgServiceType.ResourceService); string result = ""; try { selection.Open(resSvc, input.MapName); selection.FromXml(""); //Clear existing selection.AddFeatures(layer, reader, 0); result = selection.ToXml(); } finally { reader.Close(); } return(Content(result, MgMimeType.Xml)); }
// GET: DwfPlot public ActionResult Index(MapGuideViewerInputModel input) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgPoint center = map.ViewCenter; MgCoordinate coord = center.Coordinate; DwfPlotViewModel vm = new DwfPlotViewModel() { MapName = input.MapName, Session = input.Session, Scale = map.GetViewScale(), X = coord.X, Y = coord.Y }; return View(vm); }
//--------------------------------------------------------------------------------------- // // ���ܣ�����ѯ���ת��ΪXML��ʽ���ַ� // // ���ߣ� // // ���ڣ� 2007.5.23 // // ����ʷ���� // //--------------------------------------------------------------------------------------- public void CreateSelectionXML(String queryString) { //������Դ��Ҫ�ط��� MgResourceService resService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgFeatureService featureService = (MgFeatureService)siteConnection.CreateService(MgServiceType.FeatureService); //��ȡҪ��ѯ��Ҫ��������ڵIJ� MgMap map = new MgMap(); map.Open(resService, "Sheboygan"); MgLayer layer = map.GetLayers().GetItem("Parcels"); //ִ��Ҫ�ز�ѯ MgResourceIdentifier resId = new MgResourceIdentifier(layer.GetFeatureSourceId()); MgFeatureQueryOptions queryOption = new MgFeatureQueryOptions(); queryOption.SetFilter(queryString); MgFeatureReader featureReader = featureService.SelectFeatures(resId, "Parcels", queryOption); //����ѡ�� MgSelection selection = new MgSelection(map); selection.AddFeatures(layer, featureReader, 0); //����ѡ����ת��ΪXML OutputSelectionInHTML(selection, featureService); selectionXML = selection.ToXml(); }
public static string GetVisSelLayers(string ss, string mpN) { MgMap map = new MgMap(); MgResourceService resourceSrvc = GetMgResurceService(ss); map.Open(resourceSrvc, mpN); StringBuilder sb = new StringBuilder(); sb.Append("({"); sb.Append("'layers': ["); foreach (var item in map.GetLayers()) { if (item.IsVisible() && item.Selectable) { sb.Append("{'name':"); sb.Append("'" + item.Name + "', "); sb.Append("'legend':"); sb.Append("'" + item.LegendLabel + "'"); sb.Append("},"); } } return sb.ToString().Substring(0, sb.ToString().Length - 1) + "]})"; }
// GET: DwfPlot public ActionResult Index(MapGuideViewerInputModel input) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgPoint center = map.ViewCenter; MgCoordinate coord = center.Coordinate; DwfPlotViewModel vm = new DwfPlotViewModel() { MapName = input.MapName, Session = input.Session, Scale = map.GetViewScale(), X = coord.X, Y = coord.Y }; return(View(vm)); }
public static string TransformWgs2GK(double lat, double lon, double accuracy, string ss, string mpN) { MgMap map = new MgMap(); MgResourceService resourceSrvc = GetMgResurceService(ss); map.Open(resourceSrvc, mpN); //Create coordinate system factory MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory(); string wktTo = map.GetMapSRS(); string wktFrom = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]"; MgCoordinateSystem coordinateSystemSource = fact.Create(wktFrom); MgCoordinateSystem coordinateSystemTarget = fact.Create(wktTo); MgGeometryFactory geomFact = new MgGeometryFactory(); MgCoordinateSystemTransform coordTransform = fact.GetTransform(coordinateSystemSource, coordinateSystemTarget); MgCoordinate coord = coordTransform.Transform(lon, lat); return coord.X.ToString().Replace(',', '.') + ";" + coord.Y.ToString().Replace(',', '.') + ";" + accuracy.ToString().Replace(',', '.'); }
public IActionResult SelectFeature(SelectInputModel input) { MgSiteConnection conn = CreateConnection(input); MgMap map = new MgMap(conn); map.Open(input.MapName); MgLayerCollection layers = map.GetLayers(); int lidx = layers.IndexOf("Parcels"); if (lidx < 0) { throw new Exception("Layer not found on map: Parcels"); } MgLayerBase layer = layers.GetItem(lidx); MgClassDefinition clsDef = layer.GetClassDefinition(); MgPropertyDefinitionCollection props = clsDef.GetProperties(); MgPropertyDefinition idProp = props.GetItem(0); string idPropName = idProp.Name; MgFeatureQueryOptions query = new MgFeatureQueryOptions(); query.SetFilter(idPropName + " = " + input.id); MgFeatureReader reader = layer.SelectFeatures(query); MgSelection selection = new MgSelection(map, ""); MgResourceService resSvc = (MgResourceService)conn.CreateService(MgServiceType.ResourceService); string result = ""; try { selection.Open(resSvc, input.MapName); selection.FromXml(""); //Clear existing selection.AddFeatures(layer, reader, 0); result = selection.ToXml(); selection.Save(resSvc); } finally { reader.Close(); } return Content(result, MgMimeType.Xml); }
//---------------------------------------------------------------------------------------- // �� �ܣ� ��Ӳ㵽���飬������鲻���ڣ��� // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public void AddLayerToGroup(MgLayer layer, string layerGroupName, string layerGroupLegendLabel, MgMap map) { // ��ȡ���� MgLayerGroupCollection layerGroupCollection = map.GetLayerGroups(); MgLayerGroup layerGroup = null; if (layerGroupCollection.Contains(layerGroupName)) { layerGroup = layerGroupCollection.GetItem(layerGroupName); } else { // ���û�д��ڣ������� layerGroup = new MgLayerGroup(layerGroupName); layerGroup.SetVisible(true); layerGroup.SetDisplayInLegend(true); layerGroup.SetLegendLabel(layerGroupLegendLabel); layerGroupCollection.Add(layerGroup); } layerGroup.SetDisplayInLegend(true); // ��Ӳ㵽���� layer.SetGroup(layerGroup); }
public static string GetVisSelLayers(string ss, string mpN) { MgMap map = new MgMap(); MgResourceService resourceSrvc = GetMgResurceService(ss); map.Open(resourceSrvc, mpN); StringBuilder sb = new StringBuilder(); sb.Append("({"); sb.Append("'layers': ["); foreach (var item in map.GetLayers()) { if (item.IsVisible() && item.Selectable) { sb.Append("{'name':"); sb.Append("'" + item.Name + "', "); sb.Append("'legend':"); sb.Append("'" + item.LegendLabel + "'"); sb.Append("},"); } } return(sb.ToString().Substring(0, sb.ToString().Length - 1) + "]})"); }
public static string TransformGK2Wgs(double x, double y, string ss, string mpN) //Transform from Map to WGS 84 Coordtnate System { MgMap map = new MgMap(); MgResourceService resourceSrvc = GetMgResurceService(ss); map.Open(resourceSrvc, mpN); //Create coordinate system factory MgCoordinateSystemFactory fact = new MgCoordinateSystemFactory(); string wktFrom = map.GetMapSRS(); string wktTo = "GEOGCS[\"LL84\",DATUM[\"WGS84\",SPHEROID[\"WGS84\",6378137.000,298.25722293]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.01745329251994]]"; MgCoordinateSystem coordinateSystemSource = fact.Create(wktFrom); MgCoordinateSystem coordinateSystemTarget = fact.Create(wktTo); MgGeometryFactory geomFact = new MgGeometryFactory(); MgCoordinateSystemTransform coordTransform = fact.GetTransform(coordinateSystemSource, coordinateSystemTarget); MgCoordinate coord = coordTransform.Transform(x, y); return(coord.X.ToString().Replace(',', '.') + ";" + coord.Y.ToString().Replace(',', '.')); }
public MarkupEditor(NameValueCollection incomingArgs) { this.args = incomingArgs; this.site = new MgSiteConnection(); this.site.Open(new MgUserInformation(GetParameter(this.args, "SESSION"))); _resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService); _featureService = (MgFeatureService)this.site.CreateService(MgServiceType.FeatureService); if (!string.IsNullOrEmpty(GetParameter(this.args, "DIR"))) libraryPath = GetParameter(this.args, "DIR"); else { MgMap map = new MgMap(); map.Open(_resourceService, GetParameter(this.args, "MAPNAME")); string path = map.MapDefinition.Path; if (path.ToLower().EndsWith("maps")) path = path.Substring(0, path.Length - 4); /*libraryPath = Path.Combine(String.Format("Library://{0}", path), "Markup/");*/ libraryPath = ConfigurationManager.AppSettings["MarkupLibraryPath"].ToString(); } FeatureHasProjectIdField(); }
protected void Page_Load(object sender, EventArgs e) { MgUserInformation user = new MgUserInformation("Anonymous", ""); MgSite site = new MgSite(); site.Open(user); string sessionId = site.CreateSession(); user.SetMgSessionId(sessionId); MgSiteConnection siteConn = new MgSiteConnection(); siteConn.Open(user); MgResourceIdentifier mdfId = new MgResourceIdentifier("Library://Samples/Sheboygan/Maps/Sheboygan.MapDefinition"); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); MgMap map1 = new MgMap(siteConn); map1.Create(mdfId, "ColdStart"); sw.Stop(); Trace.Write("ColdStart - " + sw.ElapsedMilliseconds + "ms"); sw.Reset(); sw.Start(); MgMap map2 = new MgMap(siteConn); map2.Create(mdfId, "WarmStart"); sw.Stop(); Trace.Write("WarmStart - " + sw.ElapsedMilliseconds + "ms"); sw.Start(); MgMap map3 = new MgMap(siteConn); map3.Create(mdfId, "WarmStart2"); sw.Stop(); Trace.Write("WarmStart2 - " + sw.ElapsedMilliseconds + "ms"); }
public void MapCollection() { string coordsys = "GEOGCS[\"LL84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9108\"]],AXIS[\"Lat\",NORTH],AXIS[\"Long\",EAST],AUTHORITY[\"EPSG\",\"4326\"]]"; MgEnvelope env = new MgEnvelope(10,10,20,20); MgMap map1 = new MgMap(); map1.Create(coordsys, env, "map1"); MgMap map2 = new MgMap(); map2.Create(coordsys, env, "map2"); MgMap map3 = new MgMap(); map3.Create(coordsys, env, "map3"); MgMap map4 = new MgMap(); map4.Create(coordsys, env, "map4"); MgMapCollection coll = new MgMapCollection(); coll.Add(map1); coll.Insert(1, map2); coll.Add(map3); Assert.AreEqual(3, coll.Count); Assert.AreEqual(coll[2].GetName(), "map3"); coll[1] = map4; string txt = ""; foreach (MgMap map in coll) { txt += "[" + map.GetName() + "]"; } Assert.AreEqual("[map1][map4][map3]", txt); }
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); }
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); }
public Hashtable GetOpenMarkup() { Hashtable openMarkup = new Hashtable(); MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService); MgMap map = new MgMap(); map.Open(resourceService, GetParameter(this.args, "MAPNAME")); MgLayerGroupCollection layerGroups = map.GetLayerGroups(); if (layerGroups.Contains("_Markup")) { MgLayerCollection layers = map.GetLayers(); for (int i = 0; i < layers.GetCount(); i++) { MgLayer layer = (MgLayer)layers.GetItem(i); if ((layer.GetGroup() != null) && (layer.GetGroup().GetName().Equals("_Markup"))) { openMarkup[libraryPath + layer.GetLegendLabel() + ".LayerDefinition"] = layer.GetLegendLabel(); } } } return openMarkup; }
public bool DeleteMarkup() { bool result = false; MgResourceService resourceService = (MgResourceService)this.site.CreateService(MgServiceType.ResourceService); MgFeatureService featureService = (MgFeatureService)this.site.CreateService(MgServiceType.FeatureService); MgResourceIdentifier markupLayerResId = new MgResourceIdentifier(GetParameter(args, "MARKUPLAYER")); MgResourceIdentifier markupSdfResId = new MgResourceIdentifier(libraryPath + markupLayerResId.GetName() + ".FeatureSource"); //Check related entries in maintenance MgMap map = new MgMap(); map.Open(resourceService, GetParameter(this.args, "MAPNAME")); /* string path = map.MapDefinition.Path; if (path.ToLower().EndsWith("maps")) path = path.Substring(0, path.Length - 4); path = Path.Combine(String.Format("Library://{0}", path), "Maintenance/Data/Maintenance.FeatureSource"); MgResourceIdentifier maintenanceResId = new MgResourceIdentifier(path); MgLayer layer = new MgLayer(markupLayerResId, resourceService); if (!map.GetLayers().Contains(layer)) { if (resourceService.ResourceExists(maintenanceResId)) { MgFeatureQueryOptions opt = new MgFeatureQueryOptions(); opt.SetFilter(String.Format("FeatureSource='{0}'", markupSdfResId.ToString())); MgFeatureReader reader = featureService.SelectFeatures(maintenanceResId, "Maintenance:Maintenance", opt); if (!reader.ReadNext()) { resourceService.DeleteResource(markupLayerResId); resourceService.DeleteResource(markupSdfResId); result = true; } } else {*/ resourceService.DeleteResource(markupLayerResId); resourceService.DeleteResource(markupSdfResId); result = true; /* } }*/ //================================================ return result; }
public void CreateMarkup(string mgSessionId,string mgMap) { //Response.Write("CreateMarkup" ); 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); // map.Open(resourceService, GetParameter(args, "MAPNAME")); // Create the Markup Feature Source (SDF) MgResourceIdentifier markupSdfResId = new MgResourceIdentifier(libraryPath + GetParameter(this.args, "MARKUPNAME") + ".FeatureSource"); MgFeatureSchema markupSchema = MarkupSchemaFactory.CreateMarkupSchema(); MgCreateSdfParams sdfParams = new MgCreateSdfParams("XY-M", map.MapSRS, markupSchema); featureService.CreateFeatureSource(markupSdfResId, sdfParams); String url = "concat('" + GetParameter(this.args, "MARKUPURL") + "', concat('?key=', "ID"))"; //Link to ProjectManager /* if (GetParameter(this.args, "LINKTOPROJECTMANAGER").ToLower() == "on" && !String.IsNullOrEmpty(GetParameter(this.args, "ProjectCollectionName")) && GetParameter(this.args, "ProjectCollectionName") != "áçø îøùéîä") { string projectCollectionName = GetParameter(this.args, "ProjectCollectionName"); if (projectCollectionName == "àçø...") { projectCollectionName = GetParameter(this.args, "ProjectCollectionOtherName"); } int projectId = 0; using (var conn = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["ProjectManagerConnectionString"].ConnectionString)) { var cmd = conn.CreateCommand(); cmd.CommandText = "INSERT INTO ProjectCollections(LayoutId, FeatureId, ProjectCollectionName) VALUES(@LayoutId, @FeatureId, @ProjectCollectionName); SELECT @@IDENTITY AS [NEWID]"; cmd.CommandType = System.Data.CommandType.Text; var layoutIdParam = new System.Data.SqlClient.SqlParameter("@LayoutId", System.Data.SqlDbType.NVarChar, 255); layoutIdParam.Value = GetParameter(args, "LAYOUT"); cmd.Parameters.Add(layoutIdParam); var featureIdParam = new System.Data.SqlClient.SqlParameter("@FeatureId", System.Data.SqlDbType.NVarChar, 255); featureIdParam.Value = markupSdfResId.ToString(); cmd.Parameters.Add(featureIdParam); var pcNameParam = new System.Data.SqlClient.SqlParameter("@ProjectCollectionName", System.Data.SqlDbType.NVarChar, 50); pcNameParam.Value = projectCollectionName; cmd.Parameters.Add(pcNameParam); conn.Open(); //projectId = (int)cmd.ExecuteScalar(); using (var reader = cmd.ExecuteReader()) { if (reader.Read()) { projectId = Convert.ToInt32(reader[0]); } } } string host = HttpContext.Current.Request.Url.Host; url = String.Format("concat('http://{0}/MgExtensions/ProjectManager/default.aspx?ProjectId={1}&UID=', \"UID\")", host, projectId); } */ // Create the Markup Layer Definition String hexFgTransparency = String.Format("{0:X2}", 255 * (100 - Int32.Parse(GetParameter(this.args, "FILLTRANSPARENCY"))) / 100); // Convert % to an alpha value String hexBgTransparency = GetParameter(this.args, "FILLBACKTRANS").Length > 0 ? "FF" : "00"; // All or nothing String bold = GetParameter(this.args, "LABELBOLD").Length > 0 ? "true" : "false"; String italic = GetParameter(this.args, "LABELITALIC").Length > 0 ? "true" : "false"; String underline = GetParameter(this.args, "LABELUNDERLINE").Length > 0 ? "true" : "false"; String markupLayerDefinition = File.ReadAllText(HttpContext.Current.Request.ServerVariables["APPL_PHYSICAL_PATH"] + "Extensions\\markup\\templates\\markuplayerdefinition.xml"); markupLayerDefinition = String.Format(markupLayerDefinition, markupSdfResId.ToString(), //<ResourceId> - Feature Source GetParameter(this.args, "LABELSIZEUNITS"), //<Unit> - Mark Label GetParameter(this.args, "LABELFONTSIZE"), //<SizeX> - Mark Label Size GetParameter(this.args, "LABELFONTSIZE"), //<SizeY> - Mark Label Size "FF" + GetParameter(this.args, "LABELFORECOLOR"), //<ForegroundColor> - Mark Label "FF" + GetParameter(this.args, "LABELBACKCOLOR"), //<BackgroundColor> - Mark Label GetParameter(this.args, "LABELBACKSTYLE"), //<BackgroundStyle> - Mark Label bold, //<Bold> - Mark Label italic, //<Bold> - Mark Label underline, //<Underlined> - Mark Label GetParameter(this.args, "MARKERSIZEUNITS"), //<Unit> - Mark GetParameter(this.args, "MARKERSIZE"), //<SizeX> - Mark GetParameter(this.args, "MARKERSIZE"), //<SizeY> - Mark GetParameter(this.args, "MARKERTYPE"), //<Shape> - Mark "FF" + GetParameter(this.args, "MARKERCOLOR"), //<ForegroundColor> - Mark "FF" + GetParameter(this.args, "MARKERCOLOR"), //<Color> - Mark GetParameter(this.args, "LABELSIZEUNITS"), //<Unit> - Line Label GetParameter(this.args, "LABELFONTSIZE"), //<SizeX> - Line Label Size GetParameter(this.args, "LABELFONTSIZE"), //<SizeY> - Line Label Size "FF" + GetParameter(this.args, "LABELFORECOLOR"), //<ForegroundColor> - Line Label "FF" + GetParameter(this.args, "LABELBACKCOLOR"), //<BackgroundColor> - Line Label GetParameter(this.args, "LABELBACKSTYLE"), //<BackgroundStyle> - Line Label bold, //<Bold> - Line Label italic, //<Bold> - Line Label underline, //<Underlined> - Line Label GetParameter(this.args, "LINEPATTERN"), //<LineStyle> - Line GetParameter(this.args, "LINETHICKNESS"), //<Thickness> - Line "FF" + GetParameter(this.args, "LINECOLOR"), //<Color> - Line GetParameter(this.args, "LINESIZEUNITS"), //<Unit> - Line GetParameter(this.args, "LABELSIZEUNITS"), //<Unit> - Polygon Label GetParameter(this.args, "LABELFONTSIZE"), //<SizeX> - Polygon Label Size GetParameter(this.args, "LABELFONTSIZE"), //<SizeY> - Polygon Label Size "FF" + GetParameter(this.args, "LABELFORECOLOR"), //<ForegroundColor> - Polygon Label "FF" + GetParameter(this.args, "LABELBACKCOLOR"), //<BackgroundColor> - Polygon Label GetParameter(this.args, "LABELBACKSTYLE"), //<BackgroundStyle> - Polygon Label bold, //<Bold> - Polygon Label italic, //<Bold> - Polygon Label underline, //<Underlined> - Polygon Label GetParameter(this.args, "FILLPATTERN"), //<FillPattern> - Fill hexFgTransparency + GetParameter(this.args, "FILLFORECOLOR"), //<ForegroundColor> - Fill hexBgTransparency + GetParameter(this.args, "FILLBACKCOLOR"), //<BackgroundColor> - Fill GetParameter(this.args, "BORDERPATTERN"), //<LineStyle> - Fill GetParameter(this.args, "BORDERTHICKNESS"), //<Thickness> - Fill "FF" + GetParameter(this.args, "BORDERCOLOR"), //<Color> - Fill GetParameter(this.args, "BORDERSIZEUNITS"), //<Unit> - Fill HttpContext.Current.Server.HtmlEncode(url)); //<Url> - url link MgByteReader byteReader = new MgByteReader(markupLayerDefinition, "text/xml"); resourceService.SetResource(new MgResourceIdentifier(libraryPath + GetParameter(this.args, "MARKUPNAME") + ".LayerDefinition"), byteReader, null); }
//---------------------------------------------------------------------------------------- // �� �ܣ� ����ͼ���ΪDWF�ļ� // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public bool PlotMap() { // ��ȡ��Դ����͵�ͼ������� MgResourceService resourceService = (MgResourceService)siteConnection.CreateService(MgServiceType.ResourceService); MgMappingService mappingService = (MgMappingService)siteConnection.CreateService(MgServiceType.MappingService); // ��ͼ MgMap map = new MgMap(); map.Open(resourceService, "Sheboygan"); // ����DWF��������Ϣ MgDwfVersion dwfVer = new MgDwfVersion("6.01", "1.2"); MgPlotSpecification plotSpec = new MgPlotSpecification(8.5f, 11.0f, MgPageUnitsType.Inches, 0f, 0f, 0f, 0f); plotSpec.SetMargins(0.5f, 0.5f, 0.5f, 0.5f); // ���DWF�ļ� MgResourceIdentifier layoutRes = new MgResourceIdentifier("Library://MgTutorial/Layouts/SheboyganMap.PrintLayout"); MgLayout layout = new MgLayout(layoutRes, " DWF�ļ�����ʾ��", MgPageUnitsType.Inches); MgByteReader byteReader = mappingService.GeneratePlot(map, plotSpec, layout, dwfVer); //�����ļ� MgByteSink byteSink = new MgByteSink(byteReader); string filePath = "C:\\Temp\\Map.DWF"; byteSink.ToFile(filePath); return true; }
//---------------------------------------------------------------------------------------- // �� �ܣ� ��Ӳ㵽���飬������鲻���ڣ��� // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public MgLayer CreateLayerResource(MgResourceIdentifier layerResourceID, MgResourceService resourceService, string layerName, string layerLegendLabel, MgMap map) { MgLayer newLayer = new MgLayer(layerResourceID, resourceService); // �����㲢��Ӽҵ���ͼ�� newLayer.SetName(layerName); newLayer.SetVisible(true); newLayer.SetLegendLabel(layerLegendLabel); newLayer.SetDisplayInLegend(true); MgLayerCollection layerCollection = map.GetLayers(); if (!layerCollection.Contains(layerName)) { // ��Insert��������㣬�´����IJ�λ�ڻ��ƴ������� layerCollection.Insert(0, newLayer); } newLayer.SetDisplayInLegend(true); return newLayer; }
//---------------------------------------------------------------------------------------- // �� �ܣ� ������ʱ�� // // �� �ߣ� // // // �� �ڣ�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; }
//---------------------------------------------------------------------------------------- // �� �ܣ� ��ȡ��ͼ������ϵͳ // // �� �ߣ� // // // �� �ڣ�2007.05.# // //----------------------------------------------------------------------------------------- public String GetMapSrs(MgMap map) { String srs = map.GetMapSRS(); if (srs != "") return srs; return "LOCALCS[\"*XY-MT*\",LOCAL_DATUM[\"*X-Y*\",10000],UNIT[\"Meter\", 1],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH]]"; }
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; }
public void MapPlotCollection() { string coordsys = "GEOGCS[\"LL84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9108\"]],AXIS[\"Lat\",NORTH],AXIS[\"Long\",EAST],AUTHORITY[\"EPSG\",\"4326\"]]"; MgEnvelope env = new MgEnvelope(10,10,20,20); MgMap map1 = new MgMap(); map1.Create(coordsys, env, "map1"); MgMap map2 = new MgMap(); map2.Create(coordsys, env, "map2"); MgMap map3 = new MgMap(); map3.Create(coordsys, env, "map3"); MgPlotSpecification spec = new MgPlotSpecification((float)8.0, (float)11.0, "in", (float)0.0, (float)0.0, (float)5.0, (float)5.0); MgResourceIdentifier resId = new MgResourceIdentifier("Library://test.WebLayout"); MgLayout layout1 = new MgLayout(resId, "Title1", "in"); MgMapPlot plot1 = new MgMapPlot(map1, spec, layout1); MgLayout layout2 = new MgLayout(resId, "Title2", "in"); MgMapPlot plot2 = new MgMapPlot(map2, spec, layout2); MgLayout layout3 = new MgLayout(resId, "Title3", "in"); MgMapPlot plot3 = new MgMapPlot(map3, spec, layout3); MgMapPlotCollection coll = new MgMapPlotCollection(); coll.Add(plot1); coll.Add(plot2); coll.Remove(plot1); Assert.AreEqual(1, coll.Count); coll.Insert(0, plot1); coll.Insert(2, plot3); MgMapPlot tmp = coll[2]; coll[2] = tmp; Assert.AreEqual(3, coll.Count); string txt = ""; foreach (MgMapPlot plot in coll) { txt += "[" + plot.GetLayout().GetTitle() + "]"; } Assert.AreEqual("[Title1][Title2][Title3]", txt); }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { string sessionId = GetRequestParameters(Request)["SESSION"]; string mapName = GetRequestParameters(Request)["MAPNAME"]; string locale = GetRequestParameters(Request)["LOCALE"]; if (string.IsNullOrEmpty(sessionId)) { Response.Clear(); Response.End(); return; } if (string.IsNullOrEmpty(mapName)) { Response.Clear(); Response.End(); return; } MgResourceService resourceSrvc = GetMgResurceService(sessionId); MgFeatureService featureSrvc = GetMgFeatureService(sessionId); MgMap map = new MgMap(); map.Open(resourceSrvc, mapName); string layernames = GetRequestParameters(Request)["LAYERNAMES"]; string GEOMETRY = GetRequestParameters(Request)["GEOMETRY"]; string selVar = GetRequestParameters(Request)["SELECTIONVARIANT"]; string type = GetRequestParameters(Request)["tp"]; string inputSel = GetRequestParameters(Request)["SELECTION"]; bool hasInputGeom = false; if (!string.IsNullOrEmpty(GEOMETRY)) { hasInputGeom = true; } //selection ima prednost pred podano geometrijo ... MgWktReaderWriter wktrw = new MgWktReaderWriter(); if (!string.IsNullOrEmpty(inputSel)) { MgGeometry inputGeom = MultiGeometryFromSelection(featureSrvc, map, inputSel); GEOMETRY = wktrw.Write(inputGeom); } MgAgfReaderWriter agfRW = new MgAgfReaderWriter(); int nLayer = 0; // pobrišem in zgradim na novo samo tiste, ki imajo zadetke ... int nSloj = 0; string filter = ""; StringBuilder sbOut = new StringBuilder(); sbOut.Append("<table width=\"100%\" class=\"results\">"); sbOut.Append("<tr><td class='header'></td><td class='header'>" + "Layer" + "</td><td class='header' align=\"center\">" + "Select" + "</td><td class='header' align=\"center\">" + "Report" + "</td></tr>"); MgSelection selAll = new MgSelection(map); foreach (MgLayer layer in map.GetLayers()) { if (type != "2") { if (!layer.IsVisible()) { goto nextlay; } } if (layer.LegendLabel == "") { goto nextlay; } try { nLayer++; filter = String.Format("{0} {1} GeomFromText('{2}')", layer.GetFeatureGeometryName(), selVar, GEOMETRY); //preveriti še filter na Layerju. Ker ne gre drugače, je potrebno pogledati v XML MgResourceIdentifier layerDefResId = layer.GetLayerDefinition(); MgByteReader byteReader = resourceSrvc.GetResourceContent(layerDefResId); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); String xmlLayerDef = byteReader.ToString(); doc.LoadXml(xmlLayerDef); KALI.MGE.Objects.KALILayerDefinition.LayerDefinition ld = KALI.MGE.Objects.KALILayerDefinition.LayerDefinition.Parse(xmlLayerDef); if (!string.IsNullOrEmpty(ld.VectorLayerDefinition.Filter)) { filter += " AND (" + ld.VectorLayerDefinition.Filter + ")"; } //query the features MgFeatureQueryOptions opts = new MgFeatureQueryOptions(); opts.SetFilter(filter); String featureClassName = layer.GetFeatureClassName(); MgResourceIdentifier srcId = new MgResourceIdentifier(layer.GetFeatureSourceId()); MgFeatureReader features = featureSrvc.SelectFeatures(srcId, featureClassName, opts); bool hasResult = features.ReadNext(); if (hasResult) { nSloj++; int n = 0; MgClassDefinition classDef = features.GetClassDefinition(); MgPropertyDefinitionCollection classDefProps = classDef.GetIdentityProperties(); ArrayList idPropNames = new ArrayList(classDefProps.GetCount()); for (int j = 0; j < classDefProps.GetCount(); j++) { MgPropertyDefinition idProp = classDefProps.GetItem(j); idPropNames.Add(idProp.GetName()); } MgSelection sel = new MgSelection(map); do { // Generate XML to selection this feature MgPropertyCollection idProps = new MgPropertyCollection(); foreach (string id in idPropNames) { int idPropType = features.GetPropertyType(id); switch (idPropType) { case MgPropertyType.Int32: idProps.Add(new MgInt32Property(id, features.GetInt32(id))); break; case MgPropertyType.String: idProps.Add(new MgStringProperty(id, features.GetString(id))); break; case MgPropertyType.Int64: idProps.Add(new MgInt64Property(id, features.GetInt64(id))); break; case MgPropertyType.Double: idProps.Add(new MgDoubleProperty(id, features.GetDouble(id))); break; case MgPropertyType.Single: idProps.Add(new MgSingleProperty(id, features.GetSingle(id))); break; case MgPropertyType.DateTime: idProps.Add(new MgDateTimeProperty(id, features.GetDateTime(id))); break; default: //throw new SearchError(String.Format(MgLocalizer.GetString("SEARCHTYYPENOTSUP", locale), new Object[] { idPropType.ToString() }), searchError); break; } } sel.AddFeatureIds(layer, featureClassName, idProps); selAll.AddFeatureIds(layer, featureClassName, idProps); n++; //if (n > 1000) break; } while (features.ReadNext()); features.Close(); features.Dispose(); string selText = EscapeForHtml(sel.ToXml()); string seljs = "<div class=\"allLay\" onclick=\"parent.SetSelectionXML('" + selText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionZoomToSelected.png\"/></div>"; string seljs3 = "<div class=\"allLay\" onclick=\"parent.MultiGridShow('" + selText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionOpenTable.png\"/></div>"; string linfo = "<b>" + layer.LegendLabel + "</b><br />" + n.ToString() + " " + "Hits"; sbOut.Append("<tr><td class=\"results\">" + nSloj.ToString() + "</td><td class=\"results\">" + linfo + "</td><td align=\"center\" class=\"results\">" + seljs + "</td><td align=\"center\" class=\"results\">" + seljs3 + "</td></tr>"); } } catch (Exception) { continue; } nextlay: continue; } sbOut.Append("</table>"); string selAllText = EscapeForHtml(selAll.ToXml()); string seljsAll = "<div class=\"allLay\" onclick=\"parent.SetSelectionXML('" + selAllText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionZoomToSelected.png\"/>" + "Select All" + "</div>"; string seljsAll3 = "<div class=\"allLay\" onclick=\"parent.MultiGridShow('" + selAllText + "');\"><img width=\"16\" height=\"16\" style=\"border:0\" src=\"images/mActionOpenTable.png\"/>" + "Report All" + "</div>"; sbOut.Append(string.Format("<br /><table width=\"100%\" class=\"results\"><tr><td class=\"results\">{0}</td><td class=\"results\">{1}</td></tr></table>", seljsAll, seljsAll3)); featureSrvc.Dispose(); resourceSrvc.Dispose(); if (nSloj > 0) { litPrebodi.Text = sbOut.ToString(); } else { litPrebodiTitle.Visible = false; litPrebodi.Text = "<b>" + "None layer lies below the selected item/area!" + "</b>"; } MgGeometry inGeom = wktrw.Read(GEOMETRY); double rw = map.ViewScale / Math.Sqrt(inGeom.Area); //koordinate if (hasInputGeom & rw > 400) { string output = ""; output = pointTransformAndWriteZ(GEOMETRY, map); litKoordinate.Text = output; litKoordinateTitle.Text = "Coordinates of selected points:"; } } }
MgGeometry MultiGeometryFromSelection(MgFeatureService featureSrvc, MgMap map, String selText) { MgSelection sel = new MgSelection(map); sel.FromXml(selText); MgReadOnlyLayerCollection selLayers = sel.GetLayers(); if (selLayers == null) { return(null); } MgGeometryCollection geomColl = new MgGeometryCollection(); MgAgfReaderWriter agfRW = new MgAgfReaderWriter(); bool polyOnly = true; for (int i = 0; i < selLayers.GetCount(); i++) { MgLayer layer = (MgLayer)selLayers.GetItem(i); // TODO: How to get selectionSize? //int selectionSize = 20; string filter = sel.GenerateFilter(layer, layer.GetFeatureClassName()); if (filter == "") { continue; } MgFeatureQueryOptions query = new MgFeatureQueryOptions(); query.SetFilter(filter); MgResourceIdentifier featureSource = new MgResourceIdentifier(layer.GetFeatureSourceId()); MgFeatureReader features = featureSrvc.SelectFeatures(featureSource, layer.GetFeatureClassName(), query); if (features != null) { MgClassDefinition classDef = features.GetClassDefinition(); String geomPropName = classDef.GetDefaultGeometryPropertyName(); int j = 0; //bool isPoly = true; while (features.ReadNext()) { MgByteReader geomReader = features.GetGeometry(geomPropName); MgGeometry geom = agfRW.Read(geomReader); if (j++ == 0) { int type = geom.GetGeometryType(); if (type == MgGeometryType.MultiPolygon || type == MgGeometryType.CurvePolygon || type == MgGeometryType.MultiCurvePolygon) { //isPoly = false; polyOnly = false; } else if (type != MgGeometryType.Polygon) { break; } } geomColl.Add(geom); } features.Close(); features.Dispose(); } } if (geomColl.GetCount() == 0) { return(null); } MgGeometryFactory gf = new MgGeometryFactory(); if (polyOnly) { MgPolygonCollection polyColl = new MgPolygonCollection(); for (int j = 0; j < geomColl.GetCount(); j++) { polyColl.Add((MgPolygon)geomColl.GetItem(j)); } return(gf.CreateMultiPolygon(polyColl)); } else { return(gf.CreateMultiGeometry(geomColl)); } }