Example #1
0
        /// <summary>
        /// 获取实体
        /// </summary>
        /// <param name="GUID"></param>
        /// <returns></returns>
        public ThreadTaskLogEntity GetEntity(string GUID)
        {
            try
            {
                ThreadTaskLogEntity entity = new ThreadTaskLogEntity();

                DataTable dt = AccessHelper.ExecuteDataSet(AccessHelper.conn, "select * from ThreadLog where [GUID]=@GUID", new OleDbParameter("@GUID", GUID)).Tables[0];

                if (dt.Rows.Count > 0)
                {
                    PropertyInfo[] properties = entity.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
                    foreach (PropertyInfo item in properties)
                    {//循环遍历实体,取出字段和字段对应的值
                        if (item.GetValue(entity, null) != null)
                        {
                            item.SetValue(entity, dt.Rows[0][item.Name].ToString(), null);
                        }
                    }


                    return(entity);
                }
            }
            catch (Exception ex)
            {
            }

            return(null);
        }
Example #2
0
 public Log(ThreadTaskLogEntity entity)
 {
     try
     {
         System.Data.DataTable dt = AccessHelper.ExecuteDataSet(AccessHelper.conn, "select * from ThreadLog where [GUID]=@GUID", new OleDbParameter("@GUID", entity.GUID)).Tables[0];
         if (dt.Rows.Count > 0)
         {
             int mm = AccessHelper.ExecuteNonQuery(AccessHelper.conn, "update ThreadLog set ThreadLog.[TaskLog_GUID]=@TaskLog_GUID,[Current]=@Current,[Total]=@Total,[Status]=@Status,[Current_loc]=@Current_loc,[ErrorMsg]=@ErrorMsg,[AddTime]=@AddTime,[IsPaused]=@IsPaused,[TName]=@TName,[TStatus]=@TStatus,[Parameter]=@Parameter,[URL]=@URL where [GUID]=@GUID ", new OleDbParameter("@TaskLog_GUID", entity.TaskLog_GUID), new OleDbParameter("@Current", entity.Current), new OleDbParameter("@Total", entity.Total), new OleDbParameter("@Status", entity.Status), new OleDbParameter("@Current_loc", entity.Current_loc), new OleDbParameter("@ErrorMsg", entity.ErrorMsg), new OleDbParameter("@AddTime", entity.AddTime), new OleDbParameter("@IsPaused", entity.IsPaused), new OleDbParameter("@TName", entity.TName), new OleDbParameter("@TStatus", entity.TStatus), new OleDbParameter("@Parameter", entity.Parameter), new OleDbParameter("@URL", entity.URL), new OleDbParameter("@GUID", entity.GUID));
         }
         else
         {
             int mm = AccessHelper.ExecuteNonQuery(AccessHelper.conn, "insert into ThreadLog([GUID],[TaskLog_GUID],[Current],[Total],[Status],[Current_loc],[ErrorMsg],[AddTime],[IsPaused],[TName],[TStatus],[Parameter],[URL]) values(@GUID,@TaskLog_GUID,@Current,@Total,@Status,@Current_loc,@ErrorMsg,@AddTime,@IsPaused,@TName,@TStatus,@Parameter,@URL)", new OleDbParameter("@GUID", entity.GUID), new OleDbParameter("@TaskLog_GUID", entity.TaskLog_GUID), new OleDbParameter("@Current", entity.Current), new OleDbParameter("@Total", entity.Total), new OleDbParameter("@Status", entity.Status), new OleDbParameter("@Current_loc", entity.Current_loc), new OleDbParameter("@ErrorMsg", entity.ErrorMsg), new OleDbParameter("@AddTime", entity.AddTime), new OleDbParameter("@IsPaused", entity.IsPaused), new OleDbParameter("@TName", entity.TName), new OleDbParameter("@TStatus", entity.TStatus), new OleDbParameter("@Parameter", entity.Parameter), new OleDbParameter("@URL", entity.URL));
         }
     }
     catch (Exception ex)
     {
     }
 }
Example #3
0
        /// <summary>
        /// 百度矢量要素下载(数据下载写入shp文件的时候可能出现问题,比如下载网络波动中断到时系统无法识别(解决办法先吧数据下载到数据在写入shp文件))
        /// </summary>
        /// <param name="Result"></param>
        /// <returns></returns>
        public WebApiResult <string> BaiduDownload(BaiduMapFeatureDownloadResult Result)
        {
            this.countdown       = new CountdownEvent(Result.TaskCount);
            this.Result_BFeature = Result;
            this.N = Result.TaskCount;

            UpdateLastLoc <BaiduMapFeatureDownloadResult>(Result.GUID);

            log = new TaskLogEntity()
            {
                GUID = Result.GUID, Name = Result.TName, Type = "矢量要素", Description = "BaiduDownload", Status = "进行中", Parameter = JsonHelper.ToJson(Result), SavePath = Result.SavePathText
            };
            //操作日志
            new Log <BaiduMapFeatureDownloadResult>(log);

            if (Result.LayerName == "道路")
            {
                xmlDoc.Load(MapFeatureConfig);

                ///////////////////////////////////////////////////////////////////////////////
                // GDAL创建shp文件
                // 注册所有的驱动
                Ogr.RegisterAll();
                // GDAL中文路径支持
                OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
                // 属性表字段中文支持
                OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", "CP936");
                // 设置坐标系存储文件夹gdal-data路径
                OSGeo.GDAL.Gdal.SetConfigOption("GDAL_DATA", System.Windows.Forms.Application.StartupPath + "\\gdal-data");
                Driver oDriver = Ogr.GetDriverByName("ESRI Shapefile");
                if (oDriver == null)
                {
                    return(new WebApiResult <string>()
                    {
                        success = 0, msg = "GDAL驱动不可用,请检查!"
                    });
                }
                // 创建数据源
                DataSource oDS = oDriver.CreateDataSource(Result.SavePathText, null);
                if (oDS == null)
                {
                    return(new WebApiResult <string>()
                    {
                        success = 0, msg = "创建数据源失败,请检查!"
                    });
                }
                oLayer = oDS.GetLayerByName(Result.TName);
                if (oLayer == null)
                {
                    // 创建图层,创建一个多线图层,并指定空间参考
                    OSGeo.OSR.SpatialReference oSRS = new OSGeo.OSR.SpatialReference("PROJCS[\"WGS_1984_Pseudo_Mercator\",GEOGCS[\"GCS_WGS_1984\",DATUM[\"D_WGS_1984\",SPHEROID[\"WGS_1984\",6378137.0,298.257223563]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Mercator\"],PARAMETER[\"false_easting\",0.0],PARAMETER[\"false_northing\",0.0],PARAMETER[\"central_meridian\",0.0],PARAMETER[\"standard_parallel_1\",0.0],UNIT[\"Meter\",1.0]]");
                    //OSGeo.OSR.SpatialReference oSRS = new OSGeo.OSR.SpatialReference("");
                    //oSRS.SetWellKnownGeogCS("EPSG:4326");
                    oLayer = oDS.CreateLayer(Result.TName, oSRS, wkbGeometryType.wkbMultiLineString, null);
                    if (oLayer == null)
                    {
                        return(new WebApiResult <string>()
                        {
                            success = 0, msg = "创建图层失败,请检查!"
                        });
                    }

                    // 创建属性表
                    // 先创建一个叫Name的字符型属性,字符长度为100
                    FieldDefn oFieldName = new FieldDefn("Name", FieldType.OFTString);
                    oFieldName.SetWidth(100);
                    oLayer.CreateField(oFieldName, 1);
                    // 再创建一个叫Type的字符型属性,字符长度为50
                    FieldDefn oFieldType = new FieldDefn("Type", FieldType.OFTString);
                    oFieldType.SetWidth(50);
                    oLayer.CreateField(oFieldType, 1);
                    // 再创建一个叫UID的字符型属性,字符长度为50
                    FieldDefn oFieldUID = new FieldDefn("UID", FieldType.OFTString);
                    oFieldUID.SetWidth(50);
                    oLayer.CreateField(oFieldUID, 1);
                }

                /////////////////////////////////////////////////////////////////////////////////
                threadlog = new ThreadTaskLogEntity()
                {
                    GUID = Result.GUID, TaskLog_GUID = Result.GUID, Status = "进行中", TStatus = 1, TName = Result.TName, IsPaused = false, URL = Result.URL, Parameter = JsonHelper.ToJson(Result)
                };
                //计算Total并更新
                threadlog.Total = GetList("SELECT KWName FROM mapbar_poi WHERE KWType = '道路'", "KWName").Count;
                new Log <BaiduMapFeatureDownloadResult>(threadlog);
                log.Count = threadlog.Total;
                new Log <BaiduMapFeatureDownloadResult>(log);

                Thread[] t = new Thread[Result.TaskCount];
                for (int num = 0; num < Result.TaskCount; num++)
                {
                    try
                    {
                        t[num] = new Thread(new ParameterizedThreadStart(run_BFeature))
                        {
                            Name = "Thread " + num.ToString()
                        };
                        t[num].Start(num);
                    }
                    catch (Exception ex)
                    {
                        threadlog.Status   = "错误";
                        threadlog.ErrorMsg = ex.ToString();
                        threadlog.TStatus  = 3;
                        new Log <BaiduMapFeatureDownloadResult>(threadlog);

                        log.Status    = "错误";
                        log.ErrorMsg  = ex.ToString();
                        log.ErrorDate = DateTime.Now.ToString();
                        //操作日志
                        new Log <BaiduMapFeatureDownloadResult>(log);

                        return(new WebApiResult <string>()
                        {
                            success = 0, msg = ex.ToString()
                        });
                    }
                }
                countdown.Wait();
                oLayer.Dispose();
                oDS.Dispose();
                for (int num = 0; num < Result.TaskCount; num++)
                {
                    t[num].Abort();
                }
                lock (obj)
                {
                    if (!Log <BaiduMapFeatureDownloadResult> .GetThreadLogEntity(this.Result_BFeature.GUID).IsPaused)
                    {
                        //配置文件参数信息更新
                        xmlDoc["MapFeature"]["bmap"]["dict_index"].InnerText = "0";
                        xmlDoc.Save(MapFeatureConfig);

                        log.Status            = "已完成";
                        log.CompleteTime      = DateTime.Now.ToString();
                        log.Current           = log.Count;
                        threadlog.Status      = "已完成";
                        threadlog.TStatus     = 2;
                        threadlog.Current     = threadlog.Total;
                        threadlog.Current_loc = List2Str(current_loc);
                        //操作日志
                        new Log <BaiduMapFeatureDownloadResult>(threadlog);
                        new Log <BaiduMapFeatureDownloadResult>(log);
                        return(new WebApiResult <string>()
                        {
                            success = 1, msg = "百度地图要素下载完成!"
                        });
                    }
                }
            }
            else
            {
                return(new WebApiResult <string>()
                {
                    success = 2, msg = "图层类型不符合"
                });
            }
            return(null);
        }
Example #4
0
        //StreamWriter watch;

        #region 百度瓦片地图个性化下载

        /// <summary>
        /// 百度瓦片地图个性化下载(暂时不使用)
        /// </summary>
        /// <returns></returns>
        //public WebApiResult<string> BaiduMapTileDownload(BaiduMapTileDownloadRequest Request)
        //{
        //    var log = new TaskLogEntity() { GUID = Request.GUID, Name = "百度瓦片下载", Type = "瓦片下载", Description = "BaiduMapTileDownload1", Status = "进行中", Parameter = JsonHelper.ToJson(Request) };
        //    //操作日志
        //    new Log<BaiduMapTileDownloadRequest>(log);

        //    try
        //    {
        //        string URLtextBox = GetDownloadUrl(Request.List_TreeNode);
        //        //检查URL地址栏
        //        if (URLtextBox == "")
        //        {
        //            //MessageBox.Show(this, "URL地址为空,请检查!", "提示");
        //            return new WebApiResult<string>() { success = 2, msg = "URL地址为空,请检查!" };
        //        }

        //        //确定要下载的坐标范围信息,起始坐标为左下角,终点坐标为右上角
        //        double startcoord_x = Request.LefttextBox;
        //        double startcoord_y = Request.BottomtextBox;
        //        double endcoord_x = Request.RighttextBox;
        //        double endcoord_y = Request.UptextBox;
        //        LatLngPoint startcoord, endcoord;

        //        //if (startcoord_x > 0 && startcoord_x < endcoord_x && endcoord_x < 180 && startcoord_y > 0 && startcoord_y < endcoord_x && endcoord_y < 90)
        //        {
        //            startcoord = new LatLngPoint(startcoord_y, startcoord_x);
        //            endcoord = new LatLngPoint(endcoord_y, endcoord_x);
        //        }
        //        //else
        //        //{
        //        //    return new WebApiResult<string>() { success = 2, msg = "输入坐标值不正确,请检查!" };
        //        //}

        //        //检查下载层级是否勾选
        //        if (Request.LevelList.Length == 0)
        //        {
        //            return new WebApiResult<string>() { success = 2, msg = "下载地图层级未选择,请检查!" };
        //        }
        //        //获取要下载的地图层级
        //        foreach (int Level in Request.LevelList)
        //        {
        //            //int z = Level;
        //            Tuple<int, int, int, int> BoundTup = GetTileBound(startcoord, endcoord, Level);
        //            for (int i = BoundTup.Item1; i <= BoundTup.Item3; i++)
        //            {
        //                for (int j = BoundTup.Item2; j <= BoundTup.Item4; j++)
        //                {
        //                    try
        //                    {
        //                        String link = String.Format(URLtextBox, Math.Abs(i + j) % 3, i, j, Level);
        //                        String localpath = Request.SavePathText + String.Format("\\{0}\\{1}\\", Level, i);
        //                        String filename = String.Format("{0}.png", j);
        //                        //判断文件是否存在,若存在,直接下载下一个文件
        //                        if (File.Exists(localpath + filename)) continue;
        //                        //下载文件
        //                        String downloadedfile = "";
        //                        do
        //                        {
        //                            downloadedfile = DownloadFile(link, localpath, filename);
        //                            Thread.Sleep(100);
        //                            try
        //                            {
        //                                Image img = Image.FromFile(localpath + filename);
        //                            }
        //                            catch (Exception)
        //                            {
        //                                File.Delete(localpath + filename);
        //                                downloadedfile = "";
        //                            }
        //                        } while (downloadedfile == "");
        //                    }
        //                    catch (Exception ex)
        //                    {
        //                        log.Status = "错误";
        //                        log.ErrorMsg = ex.ToString();
        //                        log.ErrorDate = DateTime.Now.ToString();
        //                        new Log<BaiduMapTileDownloadRequest>(log);
        //                        return null;
        //                    }
        //                }
        //            }
        //        }

        //        log.Status = "已完成";
        //        log.CompleteTime = DateTime.Now.ToString();
        //        new Log<BaiduMapTileDownloadRequest>(log);
        //    }
        //    catch (Exception ex)
        //    {
        //        log.Status = "错误";
        //        log.ErrorMsg = ex.ToString();
        //        log.ErrorDate = DateTime.Now.ToString();
        //        new Log<BaiduMapTileDownloadRequest>(log);
        //    }
        //    return null;
        //}

        /// <summary>
        /// 百度瓦片地图个性化下载(当前使用)
        /// </summary>
        /// <returns></returns>
        public WebApiResult <string> BaiduMapTileDownload1(BaiduMapTileDownloadRequest Request)
        {
            //watch = new StreamWriter(new FileStream(System.AppDomain.CurrentDomain.BaseDirectory + "\\App_Data\\ThreadLog.txt", FileMode.Create));
            this.countdown = new CountdownEvent(Request.TaskCount);
            this.request   = Request;

            UpdateLastLoc(Request.GUID);

            log = new TaskLogEntity()
            {
                GUID = Request.GUID, Name = Request.TName, Type = "百度瓦片下载", Description = "BaiduMapTileDownload1", Status = "进行中", Parameter = JsonHelper.ToJson(Request), SavePath = request.SavePathText
            };
            //操作日志
            new Log <BaiduMapTileDownloadRequest>(log);
            try
            {
                if (Request.LayerStr == "sate")
                {
                    this.URLtextBox = "https://ss{0}.bdstatic.com/8bo_dTSlR1gBo1vgoIiO_jowehsv/starpic/?qt=satepc&u=x={1};y={2};z={3};v=009;type=sate";
                }
                else
                {
                    this.URLtextBox = "http://api{0}.map.bdimg.com/customimage/tile?&x={1}&y={2}&z={3}&scale=1&ak=8d6c8b8f3749aed6b1aff3aad6f40e37&" + Request.LayerStr; //GetDownloadUrl(Request.List_TreeNode);
                                                                                                                                                                         //检查URL地址栏http://api{0}.map.bdimg.com/customimage/tile?&x={1}&y={2}&z={3}&scale=1&ak=8d6c8b8f3749aed6b1aff3aad6f40e37&styles=t:background|e:all|v:off,t:poi|e:all|v:off,t:administrative|e:all|v:off
                }
                if (URLtextBox == "")
                {
                    //MessageBox.Show(this, "URL地址为空,请检查!", "提示");
                    return(new WebApiResult <string>()
                    {
                        success = 2, msg = "URL地址为空,请检查!"
                    });
                }

                //确定要下载的坐标范围信息,起始坐标为左下角,终点坐标为右上角
                double startcoord_x = Request.LefttextBox;
                double startcoord_y = Request.BottomtextBox;
                double endcoord_x   = Request.RighttextBox;
                double endcoord_y   = Request.UptextBox;

                //if (startcoord_x > 0 && startcoord_x < endcoord_x && endcoord_x < 180 && startcoord_y > 0 && startcoord_y < endcoord_y && endcoord_y < 90)
                //{
                this.startcoord = new LatLngPoint(startcoord_y, startcoord_x);
                this.endcoord   = new LatLngPoint(endcoord_y, endcoord_x);
                //}
                //else
                //{
                //    return new WebApiResult<string>() { success = 2, msg = "输入坐标值不正确,请检查!" };
                //}
                //检查下载层级是否勾选
                if (Request.LevelList.Length == 0)
                {
                    return(new WebApiResult <string>()
                    {
                        success = 2, msg = "下载地图层级未选择,请检查!"
                    });
                }

                threadlog = new ThreadTaskLogEntity()
                {
                    GUID = Request.GUID, TaskLog_GUID = Request.GUID, Status = "进行中", TStatus = 1, Total = 0, TName = Request.TName, IsPaused = false, Parameter = JsonHelper.ToJson(Request), URL = Request.URL
                };
                //计算Total并更新
                foreach (int Level in Request.LevelList)
                {
                    Tuple <int, int, int, int> BoundTup = GetTileBound(startcoord, endcoord, Level);
                    threadlog.Total += (BoundTup.Item3 - BoundTup.Item1 + 1) * (BoundTup.Item4 - BoundTup.Item2 + 1);
                }
                log.Count = threadlog.Total;
                new Log <BaiduMapTileDownloadRequest>(log);
                new Log <BaiduMapTileDownloadRequest>(threadlog);

                interval = new double[] { (endcoord.Lat - startcoord.Lat) / Request.TaskCount, (endcoord.Lng - startcoord.Lng) / Request.TaskCount };

                Thread[] t = new Thread[Request.TaskCount];
                for (int num = 0; num < Request.TaskCount; num++)
                {
                    try
                    {
                        t[num] = new Thread(new ParameterizedThreadStart(run))
                        {
                            Name = "Thread " + num.ToString()
                        };
                        t[num].Start(num);
                    }
                    catch (Exception ex)
                    {
                        threadlog.Status   = "错误";
                        threadlog.ErrorMsg = ex.ToString();
                        threadlog.TStatus  = 3;
                        new Log <BaiduMapTileDownloadRequest>(threadlog);

                        log.Status    = "错误";
                        log.ErrorMsg  = ex.ToString();
                        log.ErrorDate = DateTime.Now.ToString();
                        //操作日志
                        new Log <BaiduMapTileDownloadRequest>(log);

                        return(new WebApiResult <string>()
                        {
                            success = 0, msg = ex.ToString()
                        });
                    }
                }
                countdown.Wait();

                //watch.Close();
                for (int num = 0; num < Request.TaskCount; num++)
                {
                    t[num].Abort();
                }
                lock (obj)
                {
                    if (!Log <BaiduMapTileDownloadRequest> .GetThreadLogEntity(this.request.GUID).IsPaused)
                    {
                        log.Status            = "已完成";
                        log.CompleteTime      = DateTime.Now.ToString();
                        log.Current           = log.Count;
                        threadlog.Status      = "已完成";
                        threadlog.TStatus     = 2;
                        threadlog.Current     = threadlog.Total;
                        threadlog.Current_loc = List2Str(current_loc);
                        //操作日志
                        new Log <BaiduMapTileDownloadRequest>(threadlog);
                        new Log <BaiduMapTileDownloadRequest>(log);
                        return(new WebApiResult <string>()
                        {
                            success = 1, msg = "百度瓦片下载完成!"
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                log.Status    = "错误";
                log.ErrorMsg  = ex.ToString();
                log.ErrorDate = DateTime.Now.ToString();
                new Log <BaiduMapTileDownloadRequest>(log);
                return(new WebApiResult <string>()
                {
                    success = 0, msg = ex.ToString()
                });
            }

            return(null);
        }
Example #5
0
        /// <summary>
        /// 百度瓦片地图拼接
        /// </summary>
        /// <param name="Result"></param>
        /// <returns></returns>
        public WebApiResult <string> BaiduTileSplicing(BaiduTileSplicingResult Result)
        {
            this.Result_baidu = Result;
            UpdateLastLoc <BaiduTileSplicingResult>(Result.GUID);

            log = new TaskLogEntity()
            {
                GUID = Result.GUID, Name = Result.TName, Type = "瓦片拼接", Description = "BaiduTileSplicing", Status = "进行中", Parameter = JsonHelper.ToJson(Result), SavePath = Result.SavePath
            };
            //操作日志
            new Log <BaiduTileSplicingResult>(log);
            threadlog = new ThreadTaskLogEntity()
            {
                GUID = this.Result_baidu.GUID, TaskLog_GUID = this.Result_baidu.GUID, Status = "进行中", Current = current, TStatus = 1, TName = Result_baidu.TName, IsPaused = false, URL = Result_baidu.URL, Parameter = JsonHelper.ToJson(Result_baidu)
            };
            new Log <BaiduTileSplicingResult>(threadlog);

            try
            {
                //监测瓦片地图拼接耗时
                //Stopwatch stopwatch = new Stopwatch();
                //stopwatch.Start();

                //百度地图瓦片相关信息获取,文件路径必须选取到z级(缩放层级)文件夹
                String          FilePath    = Result.FilePath;
                DirectoryInfo   TheFolder   = new DirectoryInfo(FilePath);
                DirectoryInfo[] folder_list = TheFolder.GetDirectories();
                ////百度瓦片地图拼接
                String savepath = Result.SavePath;
                var    restuls  = ParallelWriteImage(folder_list, savepath, 0, Result.crstype, Result.Size);

                if (restuls != null)
                {
                    log.Status       = "已完成";
                    log.CompleteTime = DateTime.Now.ToString();
                    log.Current      = log.Count;

                    threadlog.TStatus = 2;
                    threadlog.Status  = "已完成";
                    threadlog.Current = threadlog.Total;
                    //操作日志
                    new Log <BaiduTileSplicingResult>(threadlog);
                    new Log <BaiduTileSplicingResult>(log);

                    return(restuls);
                }
                //stopwatch.Stop();
            }
            catch (Exception ex)
            {
                threadlog.Status   = "错误";
                threadlog.ErrorMsg = ex.ToString();
                threadlog.TStatus  = 3;
                new Log <BaiduTileSplicingResult>(threadlog);

                log.Status    = "错误";
                log.ErrorMsg  = ex.ToString();
                log.ErrorDate = DateTime.Now.ToString();
                new Log <BaiduTileSplicingResult>(log);

                return(new WebApiResult <string>()
                {
                    success = 0, msg = ex.ToString()
                });
            }
            return(null);
        }
Example #6
0
        /// <summary>
        /// 瓦片地图拼接函数
        /// 百度地图和高德地图瓦片地图组织形式不一样,用maptype加以区别
        /// </summary>
        /// <param name="folder_list">文件夹列表</param>
        /// <param name="savepath">保存路径</param>
        /// <param name="maptype">0为百度地图,1为高德地图</param>
        WebApiResult <string> ParallelWriteImage(DirectoryInfo[] folder_list, String savepath, int maptype, string crstype, int maxSize)
        {
            FileInfo[] file = new FileInfo[] { };
            foreach (var folder in folder_list)
            {
                FileInfo[] a = GetFileList(folder);
                file = JoinArray(file, a);
            }

            List <List <FileInfo> > file_list_blocks = new List <List <FileInfo> >();

            deSplice(file, maxSize, ref file_list_blocks);
            var count = file_list_blocks.Count;

            //计算Total并更新
            threadlog.Total = file_list_blocks.Count;
            new Log <BaiduTileSplicingResult>(threadlog);
            log.Count = threadlog.Total;
            new Log <BaiduTileSplicingResult>(log);

            //利用GDAL创建结果影像,并写入瓦片数据
            Gdal.AllRegister();                                   //驱动注册
            Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES"); //中文路径支持
            Driver pDriver = Gdal.GetDriverByName("GTIFF");

            int num = 0;

            //分块拼接影像
            foreach (var file_list_block in file_list_blocks)
            {
                if (num < current)
                {
                    num++;
                    continue;
                }
                //if (num == 6) Pause<BaiduTileSplicingResult>(this.Result_gaode.GUID);

                if (maptype == 0)
                {
                    if (Log <BaiduTileSplicingResult> .GetThreadLogEntity(this.Result_baidu.GUID).IsPaused)
                    {
                        threadlog.Current  = current;
                        threadlog.Status   = "暂停";
                        threadlog.TStatus  = 4;
                        threadlog.IsPaused = true;
                        new Log <BaiduTileSplicingResult>(threadlog);

                        log.Status  = "未完成";
                        log.Current = current;
                        new Log <BaiduTileSplicingResult>(log);
                        return(null);
                    }
                }
                else
                {
                    if (Log <BaiduTileSplicingResult> .GetThreadLogEntity(this.Result_gaode.GUID).IsPaused)
                    {
                        threadlog.Current  = current;
                        threadlog.Status   = "暂停";
                        threadlog.TStatus  = 4;
                        threadlog.IsPaused = true;
                        new Log <BaiduTileSplicingResult>(threadlog);

                        log.Status  = "未完成";
                        log.Current = current;
                        new Log <BaiduTileSplicingResult>(log);
                        return(null);
                    }
                }

                FileInfo[] file_list_array = file_list_block.ToArray <FileInfo>();
                if (file_list_array.Length > 1)
                {
                    //获取分块的坐标信息和范围信息
                    List <Point> TilePoints = GetTileCoor(file_list_array);
                    Tuple <int, int, int, int> TileBoundary = GetBoundary(TilePoints);

                    //定义存储文件名
                    string level = file_list_block[0].DirectoryName.Substring(0, file_list_block[0].DirectoryName.LastIndexOf("\\")).Split('$')[0];
                    level = level.Substring(level.LastIndexOf("\\"));
                    string savedir = savepath + level;

                    //判断存储路径是否存在
                    if (!Directory.Exists(savedir))
                    {
                        Directory.CreateDirectory(savedir);
                    }
                    string dstPath = savedir + '\\' + file_list_block.First <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.First <FileInfo>().Name.Split('.').First() + "_" + file_list_block.Last <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.Last <FileInfo>().Name.Split('.').First() + ".tif";
                    if (File.Exists(dstPath))
                    {
                        continue;
                    }
                    string tfwPath = savedir + '\\' + file_list_block.First <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.First <FileInfo>().Name.Split('.').First() + "_" + file_list_block.Last <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.Last <FileInfo>().Name.Split('.').First() + ".tfw";
                    if (File.Exists(tfwPath))
                    {
                        continue;
                    }

                    //计算图像的宽度和高度,定义图像的Dataset
                    int     bufWidth   = (TileBoundary.Item3 - TileBoundary.Item1 + 1) * 256;
                    int     bufHeight  = (TileBoundary.Item4 - TileBoundary.Item2 + 1) * 256;
                    Dataset dstDataset = pDriver.Create(dstPath, bufWidth, bufHeight, 3, DataType.GDT_Byte, new String[] { "BIGTIFF=IF_NEEDED" });

                    //生成.tfw文件
                    StreamWriter writer = new StreamWriter(new FileStream(tfwPath, FileMode.Create, FileAccess.Write), Encoding.ASCII);
                    if (maptype == 0)
                    {
                        int z = int.Parse(level.Substring(1));
                        //计算瓦片地图左上角墨卡托坐标
                        double mcx   = TileBoundary.Item1 * 256 * Math.Pow(2, (18 - z));
                        double mcy   = (TileBoundary.Item4 + 1) * 256 * Math.Pow(2, (18 - z));
                        double sizex = 256 * Math.Pow(2, (18 - z));
                        double sizey = sizex;

                        if (crstype == "BD09")
                        {
                            var F = CoordTransferHelper.Mercator2LatLng(new PointF((float)mcx, (float)mcy));
                            mcx = F.Lat;
                            mcy = F.Lng;
                            double r1 = (TileBoundary.Item3 + 1) * 256 * Math.Pow(2, (18 - z));
                            double r2 = TileBoundary.Item2 * 256 * Math.Pow(2, (18 - z));
                            F     = CoordTransferHelper.Mercator2LatLng(new PointF((float)r1, (float)r2));
                            sizex = Math.Abs(mcx - F.Lat) / (TileBoundary.Item3 - TileBoundary.Item1 + 1);
                            sizey = Math.Abs(mcy - F.Lng) / (TileBoundary.Item4 - TileBoundary.Item2 + 1);
                        }

                        writer.WriteLine(sizex);
                        writer.WriteLine(0.000000);
                        writer.WriteLine(0.000000);
                        writer.WriteLine(-1 * sizey);
                        writer.WriteLine(mcx);
                        writer.WriteLine(mcy);
                    }
                    if (maptype == 1)
                    {
                        int    z      = int.Parse(level.Substring(1));
                        Point  TileP  = new Point(TileBoundary.Item1, TileBoundary.Item2);
                        Point  PixelP = new Point(0, 0);
                        var    P      = CoordTransferHelper.PixelXY2LatLng(TileP, PixelP, z);
                        double mcx    = P.Lat;
                        double mcy    = P.Lng;

                        P = CoordTransferHelper.PixelXY2LatLng(new Point(TileBoundary.Item3, TileBoundary.Item4), new Point(256, 256), z);
                        double sizex = Math.Abs(mcx - P.Lat) / (TileBoundary.Item3 - TileBoundary.Item1 + 1);
                        double sizey = Math.Abs(mcy - P.Lng) / (TileBoundary.Item4 - TileBoundary.Item2 + 1);

                        writer.WriteLine(sizex);
                        writer.WriteLine(0.000000);
                        writer.WriteLine(0.000000);
                        writer.WriteLine(sizey);
                        writer.WriteLine(mcx);
                        writer.WriteLine(mcy);
                    }
                    writer.Close();

                    //遍历分块列表中所有影像,读取瓦片图像信息写入分块影像
                    for (int i = 0; i < file_list_array.Length; i++)
                    {
                        //打开瓦片地图,获取瓦片地图的宽度、高度、波段、位数信息
                        Dataset img     = Gdal.Open(file_list_array[i].FullName, Access.GA_ReadOnly);
                        int     Width   = img.RasterXSize;
                        int     Height  = img.RasterYSize;
                        int     BandNum = img.RasterCount;
                        int     Depth   = Gdal.GetDataTypeSize(img.GetRasterBand(1).DataType);

                        //读取瓦片地图的数据信息
                        Byte[] buf = new Byte[Width * Height * BandNum];
                        CPLErr err = img.ReadRaster(0, 0, Width, Height, buf, Width, Height, BandNum, null, 0, 0, 0);
                        if (err == CPLErr.CE_Failure)
                        {
                            string message = string.Format("{0}图像读取失败!", file_list_array[i].Name);

                            return(new WebApiResult <string>()
                            {
                                success = 1, msg = message
                            });
                        }

                        //获取瓦片地图在拼接影像中的起始坐标信息
                        int OrgX = -9999, OrgY = -9999;
                        if (maptype == 0)
                        {
                            OrgX = (TilePoints[i].X - TileBoundary.Item1) * 256;
                            OrgY = (TileBoundary.Item4 - TilePoints[i].Y) * 256;
                        }
                        else if (maptype == 1)
                        {
                            OrgX = (TilePoints[i].X - TileBoundary.Item1) * 256;
                            OrgY = (TilePoints[i].Y - TileBoundary.Item2) * 256;
                        }
                        if (OrgX == -9999 || OrgY == -9999)
                        {
                            return new WebApiResult <string>()
                                   {
                                       success = 1, msg = "坐标错误"
                                   }
                        }
                        ;;
                        err = dstDataset.WriteRaster(OrgX, OrgY, Width, Height, buf, Width, Height, BandNum, null, 0, 0, 0);
                        if (err == CPLErr.CE_Failure)
                        {
                            string message = string.Format("结果图像{0}输出数据失败!", file_list_block.First <FileInfo>().Name + "_" + file_list_block.Last <FileInfo>().Name + ".tif");

                            return(new WebApiResult <string>()
                            {
                                success = 1, msg = message
                            });
                        }
                        img.Dispose();
                    }
                    dstDataset.Dispose();
                }
                else
                {
                    //定义存储文件名
                    string level = file_list_block[0].DirectoryName.Substring(0, file_list_block[0].DirectoryName.LastIndexOf("\\")).Split('_')[0];
                    level = level.Substring(level.LastIndexOf("\\"));
                    string savedir = savepath + level;

                    //判断存储路径是否存在
                    if (!Directory.Exists(savedir))
                    {
                        Directory.CreateDirectory(savedir);
                    }
                    string dstPath = savedir + '\\' + file_list_block.First <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.First <FileInfo>().Name.Split('.').First() + "_" + file_list_block.Last <FileInfo>().DirectoryName.Split('\\').Last() + "-" + file_list_block.Last <FileInfo>().Name.Split('.').First() + ".tif";
                    if (File.Exists(dstPath))
                    {
                        continue;
                    }

                    File.Copy(file_list_array[0].FullName.ToString(), dstPath);
                }

                current++;
                num++;
                if (maptype == 0)
                {
                    threadlog = Log <BaiduTileSplicingResult> .GetThreadLogEntity(this.Result_baidu.GUID);
                }
                else
                {
                    threadlog = Log <BaiduTileSplicingResult> .GetThreadLogEntity(this.Result_gaode.GUID);
                }
                threadlog.Current = current;
                new Log <BaiduTileSplicingResult>(threadlog);
            }
            pDriver.Deregister();
            Gdal.GDALDestroyDriverManager();

            return(new WebApiResult <string>()
            {
                success = 1, msg = "瓦片拼接完成!"
            });
        }
Example #7
0
        /// <summary>
        /// 高德瓦片地图拼接
        /// </summary>
        /// <param name="Result"></param>
        /// <returns></returns>
        public WebApiResult <string> GaodeTileSplicing(GaodeTileSplicingResult Result)
        {
            this.Result_gaode = Result;
            UpdateLastLoc <GaodeTileSplicingResult>(Result.GUID);

            log = new TaskLogEntity()
            {
                GUID = Result.GUID, Name = Result.TName, Type = "瓦片拼接", Description = "GaodeTileSplicing", Status = "进行中", Parameter = JsonHelper.ToJson(Result), SavePath = Result.SavePath
            };
            //操作日志
            new Log <GaodeTileSplicingResult>(log);

            threadlog = new ThreadTaskLogEntity()
            {
                GUID = this.Result_gaode.GUID, TaskLog_GUID = this.Result_gaode.GUID, Status = "进行中", TStatus = 1, TName = Result_gaode.TName, IsPaused = false, URL = Result_gaode.URL, Parameter = JsonHelper.ToJson(Result_gaode)
            };
            new Log <BaiduTileSplicingResult>(threadlog);

            try
            {
                //耗时统计
                //Stopwatch stopwatch = new Stopwatch();
                //stopwatch.Start();

                //高德地图瓦片相关信息获取,文件路径必须选取到z级(缩放层级)文件夹
                String          FilePath    = Result.FilePath;
                DirectoryInfo   TheFolder   = new DirectoryInfo(FilePath);
                DirectoryInfo[] folder_list = TheFolder.GetDirectories();
                ////整个瓦片地图范围,用于创建拼接大影像
                //FileInfo[] file_list = GetFileList(TheFolder);
                //List<Point> TilePoints = GetTileCoor(file_list);
                //Tuple<int, int, int, int> TileBoundary = GetBoundary(TilePoints);

                ////高德瓦片地图拼接
                String savepath = Result.SavePath;
                var    restuls  = ParallelWriteImage(folder_list, savepath, 1, "", Result.Size);

                if (restuls != null)
                {
                    log.Status       = "已完成";
                    log.CompleteTime = DateTime.Now.ToString();
                    log.Current      = log.Count;

                    threadlog.TStatus = 2;
                    threadlog.Status  = "已完成";
                    threadlog.Current = threadlog.Total;
                    //操作日志
                    new Log <GaodeTileSplicingResult>(threadlog);
                    new Log <GaodeTileSplicingResult>(log);

                    string dir = FilePath;
                    FileDelete(dir);

                    return(restuls);
                }
                //stopwatch.Stop();
            }
            catch (Exception ex)
            {
                threadlog.Status   = "错误";
                threadlog.ErrorMsg = ex.ToString();
                threadlog.TStatus  = 3;
                new Log <GaodeTileSplicingResult>(threadlog);

                log.Status    = "错误";
                log.ErrorMsg  = ex.ToString();
                log.ErrorDate = DateTime.Now.ToString();
                new Log <GaodeTileSplicingResult>(log);

                return(new WebApiResult <string>()
                {
                    success = 0, msg = ex.ToString()
                });
            }
            return(null);
        }