├── .gitignore ├── jts-core-1.18.2.jar ├── scripts ├── 生成jar包.bat └── 生成jar包.sh ├── images ├── use-console.png ├── use-http-api.png ├── use-map-echarts.png ├── use-map-echarts2.png └── use-debug-grid-split.png ├── 编译和运行Test.java直接测试.bat ├── 编译和运行Test.java直接测试.sh ├── LICENSE ├── README.md ├── Test_HttpApiServer.java ├── Test.java └── AreaCityQuery.java /.gitignore: -------------------------------------------------------------------------------- 1 | /com 2 | /target 3 | /*.wkbs 4 | -------------------------------------------------------------------------------- /jts-core-1.18.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiangyuecn/AreaCity-Query-Geometry/HEAD/jts-core-1.18.2.jar -------------------------------------------------------------------------------- /scripts/生成jar包.bat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiangyuecn/AreaCity-Query-Geometry/HEAD/scripts/生成jar包.bat -------------------------------------------------------------------------------- /images/use-console.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiangyuecn/AreaCity-Query-Geometry/HEAD/images/use-console.png -------------------------------------------------------------------------------- /images/use-http-api.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiangyuecn/AreaCity-Query-Geometry/HEAD/images/use-http-api.png -------------------------------------------------------------------------------- /编译和运行Test.java直接测试.bat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiangyuecn/AreaCity-Query-Geometry/HEAD/编译和运行Test.java直接测试.bat -------------------------------------------------------------------------------- /images/use-map-echarts.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiangyuecn/AreaCity-Query-Geometry/HEAD/images/use-map-echarts.png -------------------------------------------------------------------------------- /images/use-map-echarts2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiangyuecn/AreaCity-Query-Geometry/HEAD/images/use-map-echarts2.png -------------------------------------------------------------------------------- /images/use-debug-grid-split.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/xiangyuecn/AreaCity-Query-Geometry/HEAD/images/use-debug-grid-split.png -------------------------------------------------------------------------------- /编译和运行Test.java直接测试.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | #在Linux、macOS系统终端中运行这个文件,自动完成java文件编译和运行 3 | 4 | clear 5 | 6 | #修改这里指定需要使用的JDK(/结尾bin目录完整路径),否则将使用已安装的默认JDK 7 | jdkBinDir="" 8 | #jdkBinDir="/home/download/jdk-19.0.1/bin/" 9 | 10 | if [ "$jdkBinDir" == "" ]; then 11 | echo "正在读取JDK版本(如需指定JDK为特定版本或目录,请修改本sh文件内jdkBinDir为JDK bin目录):" 12 | else 13 | echo "正在读取JDK(${jdkBinDir})版本:" 14 | fi 15 | function err(){ echo -e "\e[31m$1\e[0m"; } 16 | 17 | ${jdkBinDir}javac -version 18 | [ ! $? -eq 0 ] && { err "需要安装JDK才能编译运行java文件"; exit; } 19 | 20 | ${jdkBinDir}javac -encoding utf-8 -cp "./*" *.java 21 | [ ! $? -eq 0 ] && { err "java文件编译失败"; exit; } 22 | 23 | dir="com/github/xiangyuecn/areacity/query" 24 | if [ ! -e $dir ]; then 25 | mkdir -p $dir 26 | else 27 | rm ${dir}/*.class > /dev/null 2>&1 28 | fi 29 | mv *.class ${dir} 30 | 31 | echo "java -Xmx300m Test -cmd 已限制java最大允许使用300M内存" 32 | ${jdkBinDir}java -cp "./:./*" -Xmx300m com.github.xiangyuecn.areacity.query.Test -cmd 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 xiangyuecn 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /scripts/生成jar包.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | #在Linux、macOS系统终端中运行这个文件,自动完成java文件编译和打包成jar 3 | 4 | dir=`pwd`; dir=`basename $dir`; 5 | if [ "$dir" != "scripts" ]; then echo "请到scripts目录中运行本脚本。"; exit; fi 6 | 7 | clear 8 | cd ../ 9 | 10 | #修改这里指定需要使用的JDK(/结尾bin目录完整路径),否则将使用已安装的默认JDK 11 | jdkBinDir="" 12 | #jdkBinDir="/home/download/jdk-19.0.1/bin/" 13 | 14 | if [ "$jdkBinDir" == "" ]; then 15 | echo "正在读取JDK版本(如需指定JDK为特定版本或目录,请修改本sh文件内jdkBinDir为JDK bin目录):" 16 | else 17 | echo "正在读取JDK(${jdkBinDir})版本:" 18 | fi 19 | function err(){ echo -e "\e[31m$1\e[0m"; } 20 | 21 | ${jdkBinDir}javac -version 22 | [ ! $? -eq 0 ] && { err "需要安装JDK才能编译java文件"; exit; } 23 | 24 | 25 | function JarN(){ 26 | echo "" 27 | echo "请选择需要的生成操作:" 28 | echo " 1. 仅生成依赖jar文件(放到其他项目中Java代码调用,不含Test.java)" 29 | echo " 2. 生成可运行jar文件(包含Test.java控制台程序)" 30 | echo " 3. 退出" 31 | read -p "请输入序号:" step 32 | echo "" 33 | if [ "$step" == 1 ]; then Jar1; 34 | elif [ "$step" == 2 ]; then Jar2; 35 | elif [ "$step" == 3 ]; then exit; 36 | else echo "序号无效!请重新输入"; fi 37 | 38 | read -s -n1 -p "按任意键继续..."; 39 | echo "" 40 | JarN; 41 | } 42 | 43 | function Clazz(){ 44 | echo 编译中... 45 | ${jdkBinDir}javac -encoding utf-8 -cp "./*" $1 46 | [ ! $? -eq 0 ] && { err "java文件编译失败"; return 1; } 47 | 48 | dir="target/classes/com/github/xiangyuecn/areacity/query" 49 | if [ -e $dir ]; then rm -r target/classes > /dev/null 2>&1; fi 50 | mkdir -p $dir 51 | mv *.class $dir 52 | 53 | echo 编译完成,正在生成jar... 54 | } 55 | 56 | function Jar1(){ 57 | Clazz AreaCityQuery.java 58 | [ ! $? -eq 0 ] && { return 1; } 59 | 60 | dir="target/jarLib/" 61 | if [ ! -e $dir ]; then mkdir -p $dir; fi 62 | jarPath="${dir}areacity-query-geometry.lib.jar" 63 | 64 | ${jdkBinDir}jar cf $jarPath -C target/classes/ com 65 | [ ! $? -eq 0 ] && { err "生成jar失败"; return 1; } 66 | cp jts-core-*.jar $dir 67 | echo "已生成jar,文件在源码根目录:${jarPath},请copy这个jar + jts-core-xxx.jar 到你的项目中使用。" 68 | } 69 | 70 | function Jar2(){ 71 | Clazz "*.java" 72 | [ ! $? -eq 0 ] && { return 1; } 73 | 74 | dir=target/jarConsole/ 75 | dir_libs=${dir}libs/ 76 | [ ! -e $dir ] && { mkdir -p $dir; } 77 | [ ! -e $dir_libs ] && { mkdir -p $dir_libs; } 78 | jarPath=${dir}areacity-query-geometry.console.jar 79 | 80 | cp *.jar $dir_libs 81 | jarArr="" 82 | for a in `ls $dir_libs`; do jarArr="${jarArr} libs/${a}"; done 83 | echo Class-Path: $jarArr 84 | 85 | MANIFEST=target/classes/MANIFEST.MF 86 | echo Manifest-Version: 1.0>$MANIFEST 87 | echo Class-Path:${jarArr}>>$MANIFEST 88 | echo Main-Class: com.github.xiangyuecn.areacity.query.Test>>$MANIFEST 89 | 90 | ${jdkBinDir}jar cfm $jarPath target/classes/MANIFEST.MF -C target/classes/ com 91 | [ ! $? -eq 0 ] && { err "生成jar失败"; return 1; } 92 | echo "已生成jar,文件在源码根目录:${jarPath},libs内已包含依赖的其他jar文件,使用时请全部复制。" 93 | echo "请到这个文件夹里面后,执行命令运行这个jar:" 94 | echo " java -jar areacity-query-geometry.console.jar" 95 | } 96 | 97 | JarN; 98 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | **【[源GitHub仓库](https://github.com/xiangyuecn/AreaCity-Query-Geometry)】 | 【[Gitee镜像库](https://gitee.com/xiangyuecn/AreaCity-Query-Geometry)】** 2 | 3 | # :open_book:AreaCity-Query-Geometry坐标边界查询工具 4 | 5 | **本工具核心功能:使用`jts库`从`省市区县乡镇边界数据`([AreaCity-JsSpider-StatsGov开源库](https://github.com/xiangyuecn/AreaCity-JsSpider-StatsGov))或`geojson边界数据`文件中查找出和任意点、线、面有相交的矢量边界,内存占用低,性能优良(1秒可查1万个以上坐标对应的城市信息)。** 6 | 7 | - 查询一个坐标点对应的城市信息; 8 | - 查询一条路径经过的所有城市; 9 | - 查询一个矢量范围覆盖的所有城市; 10 | - 查询一个城市或下一级所有边界数据(WKT格式); 11 | - 支持通过HTTP API服务进行查询调用; 12 | - 支持通过Java代码进行查询调用; 13 | - 源码简单,包括测试`.bat|.sh`脚本共5个文件,无需IDE即可修改和运行,copy即用。 14 | 15 | 16 | [​](?) 17 | 18 | 你可以只copy `AreaCityQuery.java` 文件到你的项目中使用(建好package目录或者修改一下package),项目中引入`jts库`,就能使用 `AreaCityQuery` 中的所有查找功能了。也可以clone整个项目代码双击 `编译和运行Test.java直接测试.bat` 即可直接运行测试(macOS、linux用终端运行`.sh`的);`scripts`里面有生成jar包的命令行脚本。 19 | 20 | **API和图形界面**:本工具已自带了一个HTTP API服务,运行测试然后通过菜单启动此服务,然后就可以直接在浏览器上访问这些接口;此API接口可以直接在 [ECharts Map四级下钻在线测试和预览](https://xiangyuecn.github.io/AreaCity-JsSpider-StatsGov/assets/geo-echarts.html) 页面的`自定义数据源`中进行调用测试,页面会立即绘制查询出来的边界图形。 21 | 22 | [​](?) 23 | 24 | 源文件|是否必须|说明 25 | :-:|:-:|:- 26 | **AreaCityQuery.java**|必须|核心功能类,封装了所有核心功能,支持从`geojson`文件初始化。 27 | **jts-core-1.18.2.jar**|必须|唯一依赖的jts库,从[maven此链接](https://mvnrepository.com/artifact/org.locationtech.jts/jts-core/1.18.2)下载来的;
如需在pom.xml中引入,请参考maven链接页面内xml代码。 28 | Test_HttpApiServer.java|可选|测试用的HTTP API服务实现(可以删除此文件,不影响Test.java运行)。 29 | Test.java|可选|测试控制台程序,包含了所有功能的测试,包括启动HTTP API服务;
双击 `编译和运行Test.java直接测试.bat` 即可直接编译和运行此控制台程序(需装了jdk,macOS、linux用终端运行`.sh`的)。 30 | 31 | 32 | **如需功能定制,网站、App、小程序、前端后端开发等需求,请加下面的QQ群,联系群主(即作者),谢谢~** 33 | 34 | 35 | [​](?) 36 | 37 | [​](?) 38 | 39 | ## 【QQ群】交流与支持 40 | 41 | 欢迎加QQ群:①群 `484560085(满)`、②群 `626141661(满)`、③群 `346847528(满)`、④群 `514420754`,纯小写口令:`areacity` 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | [​](?) 52 | 53 | [​](?) 54 | 55 | [​](?) 56 | 57 | [​](?) 58 | 59 | ## 如何使用 60 | 61 | ### 前期准备:生成GeoJSON文件 62 | 程序初始化时,需要提供一个geojson文件(.json|.geojson),如果你没有此文件,可以按以下步骤获得最新的全国省市区县乡镇边界数据json文件: 63 | 1. 请到开源库下载省市区边界数据ok_geo.csv文件: https://github.com/xiangyuecn/AreaCity-JsSpider-StatsGov (github可换成gitee); 64 | 2. 下载开源库里面的[AreaCity-Geo格式转换工具软件](https://xiangyuecn.github.io/AreaCity-JsSpider-StatsGov/assets/AreaCity-Geo-Transform-Tools.html)(工具的高级中`文件格式批量互转`功能支持将shp kml gpkg等文件转成geojson); 65 | 3. 打开转换工具软件,选择ok_geo.csv,然后导出成geojson文件即可(默认会导出全国的省级数据,通过填写不同城市名前缀可以导出不同城市)。 66 | 67 | > AreaCityQuery支持使用多个数据文件来分别创建多个查询实例,比如省、市、区分别导出一个geojson文件,需要查询哪个级别的数据就调用对应实例进行查询;但如果你有多个性质相同geojson文件时,也可以合并成一个文件来只创建一个查询实例使用,可以通过上面下载的 `AreaCity-Geo格式转换工具软件` 中的 `高级功能`-`GeoJSON多个文件合并成一个文件` 来合并。 68 | 69 | > 通过ok_geo.csv生成的geojson文件的坐标系默认是`GCJ-02`火星坐标系,查询时所有输入坐标参数的坐标系必须也是`GCJ-02`,否则坐标可能会有比较大的偏移,导致查询结果不正确;可以在转换工具的高级功能中使用坐标系转换,比如转成`WGS-84`GPS坐标系,重新导出geojson文件,这样查询时就能准确的查询GPS坐标了。 70 | 71 | > 源码内已提供了一个 `仅供测试-全国省级GeoJSON数据-大幅简化粗略版.json` 文件(为了大幅减小文件体积,已严重精简过了,不可在其它地方使用),可以直接使用此文件测试,但只能测试到省级边界,如需正式测试或使用,请参考上面方法自行生成geojson文件;另提供了一个 `仅供测试-世界七大洲GeoJSON数据-大幅简化粗略版.json` 文件,可直接测试全球。 72 | > 73 | > 注意:如果是其他地方生成的geojson文件, 要求里面数据**必须是一行一条数据**,第一条数据的上一行必须是`"features": [`,最后一条数据的下一行必须是`]`打头,**否则不支持解析**,可尝试用文本编辑器批量替换添加换行符,改成和 `仅供测试-全国省级GeoJSON数据-大幅简化粗略版.json` 一样内容格式就行;或直接用上面下载的 `AreaCity-Geo格式转换工具软件` 中的 `高级功能`-`文件格式批量互转`,将geojson重新转成geojson即可,简单方便。 74 | 75 | 76 | [​](?) 77 | 78 | ### 使用方式一:通过HTTP API服务使用 79 | 操作步骤: 80 | 1. 双击 `编译和运行Test.java直接测试.bat` 运行测试控制台程序(macOS、linux用终端运行`.sh`的); 81 | 2. 根据控制台菜单命令进行初始化(需先把一个geojson文件放本程序目录内,否则要输入路径); 82 | 3. 进入9号菜单,启动本地轻量HTTP API服务(编辑 Test.java 文件内的`HttpApiServerPort`可修改端口); 83 | 4. 浏览器访问:`http://127.0.0.1:9527/` 查看接口文档和实例状态; 84 | 5. 在需要的地方直接调用http地址接口,得到json响应结果; 85 | 6. 如需外网访问,可以直接暴露端口,或使用Nginx之类的反代此http端口(通过Nginx提供https访问)。 86 | 87 | > 如需直接启动http服务,如服务器中:先解开Test.java中main函数对应的此功能注释,填写实际的json文件路径,然后运行即可;linux服务器中可使用 `nohup bash xxx.sh` 命令执行在后台运行。 88 | > 89 | > 此HTTP API接口可以直接在 [ECharts Map四级下钻在线测试和预览](https://xiangyuecn.github.io/AreaCity-JsSpider-StatsGov/assets/geo-echarts.html) 页面的`自定义数据源`中进行调用测试,页面会立即绘制查询出来的边界图形。 90 | 91 | 92 | [​](?) 93 | 94 | ### 使用方式二:Java直接调用 95 | ``` java 96 | //先获取到查询实例,默认提供的0-9的10个静态实例,每个实例可以分别使用一个数据文件进行初始化和查询,当然自己调用new AreaCityQuery()创建一个新实例使用也是一样的 97 | AreaCityQuery Instance=AreaCityQuery.Instances[0]; 98 | //static public final AreaCityQuery Instance=new AreaCityQuery(); //也可以自己创建静态实例 99 | 100 | //查询前先初始化,每个实例全局只会初始化一次,每次查询前都调用即可(查询会在初始化完成后进行),两种初始化方式根据自己业务情况二选一 101 | //首次初始化会从.json或.geojson文件中读取边界图形数据,速度比较慢,会自动生成.wkbs结尾的结构化文件,下次初始化就很快了 102 | //首次初始化生成了.wkbs文件后,后续初始化可以只使用此wkbs文件,允许不用再提供geojson文件(数据更新时需删除wkbs文件再重新用geojson文件进行初始化),具体请阅读对应初始化方法的注释文档 103 | Instance.Init_StoreInWkbsFile("geojson文件路径", "geojson文件路径.wkbs", true); 104 | //Instance.Init_StoreInMemory("geojson文件路径", "geojson文件路径.wkbs", true); 105 | 106 | //Instance.OnInitProgress=(initInfo)->{ ... } //初始化过程中的回调,可以绑定一个函数,接收初始化进度信息(编写时需在Init之前进行绑定) 107 | System.out.println(Instance.GetInitInfo().toString()); //打印初始化详细信息,包括性能信息 108 | 109 | //注意:以下查询中所有坐标参数的坐标系必须和初始化时使用的geojson数据的坐标系一致,否则坐标可能会有比较大的偏移,导致查询结果不正确 110 | //查询包含一个坐标点的所有边界图形的属性数据,可通过res参数让查询额外返回wkt格式边界数据 111 | //查询结果的判定:请不要假定查询结果的数量(坐标刚好在边界上可能会查询出多个省市区),也不要假定查询结果顺序(结果中省市区顺序是乱序的),请检查判定res1.Result中的结果是否符合查询的城市级别,比如查询省市区三级:结果中必须且仅有3条数据,并且省市区都有(判断deep=0省|1市|2区 来区分数据的级别),其他一律判定为查询无效 112 | QueryResult res1=Instance.QueryPoint(114.044346, 22.691963, null, null); 113 | //当坐标位于界线外侧(如海岸线、境界线)时QueryPoint方法将不会有边界图形能够匹配包含此坐标(就算距离只相差1cm),下面这个方法将能够匹配到附近不远的边界图形数据;2500相当于一个以此坐标为中心点、半径为2.5km的圆形范围,会查询出在这个范围内和此坐标点距离最近的边界 114 | QueryResult res1_2=Instance.QueryPointWithTolerance(121.993491, 29.524288, null, null, 2500); 115 | 116 | //查询和一个图形(点、线、面)有交点的所有边界图形的属性数据,可通过res参数让查询额外返回wkt格式边界数据 117 | Geometry geom=new WKTReader(AreaCityQuery.Factory).read("LINESTRING(114.30115 30.57962, 117.254285 31.824198, 118.785633 32.064869)"); 118 | //Geometry geom=AreaCityQuery.CreateSimpleCircle(114.044346, 22.691963, 10000, 24); //以指定坐标为中心点,创建一个半径为10km的圆面,圆面由24个坐标点粗略构成 119 | QueryResult res2=Instance.QueryGeometry(geom, null, null); 120 | 121 | //读取省市区的边界数据wkt格式,这个例子会筛选出武汉市所有区县 122 | QueryResult res3=Instance.ReadWKT_FromWkbsFile("wkt_polygon", null, (prop)->{return prop.contains("武汉市 ");}, null); 123 | //此方法会遍历所有边界图形的属性列表,因此可以用来遍历所有数据,提取感兴趣的属性内容,比如查询一个区划编号id对应的城市信息(城市名称、中心点) 124 | QueryResult res4=Instance.ReadWKT_FromWkbsFile(null, null, (prop)->{ 125 | prop=(","+prop.substring(1, prop.length()-1)+",").replace("\"", "").replace(" ", ""); //不解析json,简单处理 126 | return prop.contains(",id:42,"); //只查询出id=42(湖北省)的属性数据(注意初始化的geojson中必须要有对应的属性名,这里是id) 127 | }, null); 128 | 129 | 130 | System.out.println(res1+"\n"+res1_2+"\n"+res2+"\n"+res3+"\n"+res4); 131 | //****更多的实例,请阅读 Test.java**** 132 | //****更多功能方法,请阅读 AreaCityQuery.java 源码**** 133 | ``` 134 | 135 | ### 附:生成jar包 136 | `scripts`目录里面有生成jar包的命令行脚本,双击`生成jar包.bat`即可将源码编译成jar文件(macOS、linux用终端运行`.sh`的);脚本支持生成`带Test.java控制台程序`的、和`不带控制台程序`的两种jar,前者可以启动运行,后者可放到其他项目中用Java代码调用。 137 | 138 | ### 附:关于Java程序打包发布 139 | 本程序只支持从文件路径进行初始化,所以请将数据文件放到一个磁盘目录内,不要打包进jar中;如果是docker发布,可以在dockerfile中用VOLUME映射宿主机目录、或直接将数据文件copy进docker镜像内的目录中。 140 | 141 | 142 | [​](?) 143 | 144 | ### 附:查询一个坐标对应城市的结果判定 145 | 省、市、区分成三个geojson文件分别初始化三个查询实例进行查询的结果判断会简单一些;如果省市区三级数据在一个geojson文件中初始化的查询实例,查询结果`res.Result`可通过下面规则进行判断: 146 | - 请不要假定查询结果的数量,比如:坐标刚好在边界上可能会查询出多个省市区,结果中将超过3条数据; 147 | - 请不要假定查询结果顺序,结果中省市区顺序是乱序的,需要判断每条结果是省市区哪一级,通过判断结果中的`deep=0省|1市|2区`来区分这条结果是哪个级别; 148 | - 请检查判定查询结果中的数据是否完全符合查询的城市级别:省市区三级结果中必须且仅有3条数据,并且这3条数据省市区三级都有,否则一律可判定为查询无效。 149 | 150 | 151 | [​](?) 152 | 153 | ### 附:.wkbs文件说明 154 | 初始化时如果提供了`saveWkbsFilePath`参数(为.wkbs结构化文件的路径): 155 | - 如果此文件已存在,将自动从此文件进行初始化,初始化速度会很快(文件只读不写,可以不提供geojson文件); 156 | - 如果此文件不存在,将从.json或.geojson文件中读取边界图形数据,并生成此文件,速度比较慢(文件读写)。 157 | 158 | 因此可以先在本地用json文件进行初始化,自动生成一个wkbs文件,然后copy wkbs文件到别的地方使用(比如服务器、只读环境中)。 159 | 160 | 161 | 162 | 163 | 164 | [​](?) 165 | 166 | [​](?) 167 | 168 | [​](?) 169 | 170 | [​](?) 171 | 172 | ## 性能测试 173 | 174 | > 测试数据源:AreaCity-JsSpider-StatsGov开源库[2021.220321.220428版本](https://github.com/xiangyuecn/AreaCity-JsSpider-StatsGov/releases/tag/2021.220321.220428)下载的ok_geo.csv文件按省市区导出成不同的geojson文件。 175 | > 176 | > 测试采用开启多线程进行随机坐标点的查询(Test.java控制台5号菜单),测试机器配置:8核 2.20GHz CPU,SSD 硬盘。 177 | 178 | 179 | [​](?) 180 | 181 | ### 测试一:Init_StoreInWkbsFile 内存占用很低(性能受IO限制) 182 | 数据源|文件大小|数据量|内存占用|7核QPS|单核QPS|单次查询耗时 183 | :-:|-:|-:|-:|-:|-:|-: 184 | 省市区三级|176MB|3632条|41MB|6212|887|1.13ms 185 | 仅区级|107MB|3208条|24MB|13818|1974|0.51ms 186 | 仅省级|20MB|34条|4MB|19832|2833|0.35ms 187 | 188 | > `Init_StoreInWkbsFile`:用加载数据到结构化数据文件的模式进行初始化,推荐使用本方法初始化,边界图形数据存入结构化数据文件中,内存占用很低,查询时会反复读取文件对应内容,查询性能消耗主要在IO上,IO性能极高问题不大。 189 | 190 | 191 | [​](?) 192 | 193 | ### 测试二:Init_StoreInMemory 内存占用和json文件差不多大(性能豪放) 194 | 数据源|文件大小|数据量|内存占用|7核QPS|单核QPS|单次查询耗时 195 | :-:|-:|-:|-:|-:|-:|-: 196 | 省市区三级|176MB|3632条|161MB|77242|11034|0.091ms 197 | 仅区级|107MB|3208条|96MB|121228|17318|0.058ms 198 | 仅省级|20MB|34条|18MB|465940|66562|0.015ms 199 | 200 | > `Init_StoreInMemory`:用加载数据到内存的模式进行初始化,边界图形数据存入内存中,内存占用和json数据文件大小差不多大,查询性能极高;另外可通过设置 `Instances[0-9].SetInitStoreInMemoryUseObject=true` 来进一步提升性能,但内存占用会增大一倍多,省市区三级单核可达到 15000 QPS。 201 | 202 | 203 | [​](?) 204 | 205 | ### 参考:数据库查询测试对比 206 | 数据源|数据量|查询坐标|MySQL单次查询耗时|SQL Server单次查询耗时 207 | :-:|-:|:-:|-:|-: 208 | 省市区三级|3632条|深圳-龙华区|163ms|25ms 209 | 省市区三级|3632条|北京-房山区|173ms|47ms 210 | 211 | ``` sql 212 | -- 查询坐标点:`POINT(114.044346 22.691963)` 深圳市 龙华区;`POINT(116.055588 39.709385)` 北京市 房山区(查询受内蒙envelope干扰影响性能); 213 | 214 | -- MySQL(8.0.19)使用MyISAM引擎并给polygon创建polygon_envelope列当做索引加速 215 | create procedure ptest() begin declare i int default 0; while i<100 do do (select count(*) from (select id,ext_path from 【表名】 where ST_Intersects(polygon_envelope,ST_GeomFromText('POINT(114.044346 22.691963)',0))=1 and ST_Intersects(polygon,ST_GeomFromText('POINT(114.044346 22.691963)',0))=1) as t); set i=i+1; end while; end; call ptest(); drop procedure if exists ptest; 216 | 217 | -- SQL Server(2008)在polygon列创建空间索引加速 218 | declare @t datetime = getdate(); declare @val varchar; declare @i int =0; while @i<100 begin; set @val=(select id,ext_path from 【表名】 where polygon.STIntersects(geometry::STGeomFromText('POINT(114.044346 22.691963)',0))=1 for xml path('')); set @i=@i+1; end; select DATEDIFF(MS, @t, GETDATE())/100.0 219 | ``` 220 | 221 | 222 | 223 | 224 | 225 | 226 | 227 | 228 | [​](?) 229 | 230 | [​](?) 231 | 232 | [​](?) 233 | 234 | [​](?) 235 | 236 | [​](?) 237 | 238 | [​](?) 239 | 240 | 241 | # :open_book:图例 242 | 243 | 控制台运行: 244 | 245 | ![控制台运行](images/use-console.png) 246 | 247 | HTTP API图形界面-边界查询: 248 | 249 | ![HTTP API图形界面-边界查询](images/use-map-echarts.png) 250 | 251 | HTTP API图形界面-坐标查询: 252 | 253 | ![HTTP API图形界面-坐标查询](images/use-map-echarts2.png) 254 | 255 | HTTP API调用查询: 256 | 257 | ![HTTP API调用查询](images/use-http-api.png) 258 | 259 | 260 | 261 | 262 | [​](?) 263 | 264 | [​](?) 265 | 266 | [​](?) 267 | 268 | # :open_book:知识库 269 | 270 | 本工具的代码 *.java 文件全部被丢到根目录,没有创建包名目录,源码直接根目录裸奔,简单粗暴;这样的项目结构肉眼看去也算是简洁,也方便copy文件使用。 271 | 272 | 编写本查询工具代码的原因是数据库查询坐标点对应的城市速度太慢了,影响数据库运行;群里有用户提到过用未知开源库可达到1ms查询一次坐标点,所以开始了本次探索历程。 273 | 274 | 275 | [​](?) 276 | 277 | ## 关于RTree索引 278 | 研究过程中,群成员已实现1秒几万次查询,介绍使用RTree索引来加速空间数据查找(感谢群成员`QQ: 2668361600`的介绍);通过`com.github.davidmoten:rtree`来给每个图形单独建一个索引,索引内存放此图形的每一条边,计算坐标点几何关系的时候,直接通过射线法用RTree来查找和图形相交的边数,性能极高;相对的内存占用也非常高,测试的省市区三级需要2G多内存,仅区级也需要1.3G内存,因为内存占用过大的问题,目前并未使用本方法,有兴趣可以自行用RTree实现一下,性能可提升10+倍。 279 | 280 | 在[v2ex发的帖子](https://www.v2ex.com/t/863092)也有同学介绍使用`google s2 算法`来进行查询,性能也是极高的,也可以学习研究研究。 281 | 282 | jts库内部已自带了STRtree,目前已用于加速envelope的查找,进行初步数据的筛选,性能也是极高的。 283 | 284 | 285 | [​](?) 286 | 287 | ## 性能优化过程 288 | 对于jts库,单纯的直接用`Geometry.intersects`检测一个坐标点是否在边界图形内,性能是很低的;全国省市区3632条数据,全部检测一遍大约要10ms-15ms,这些性能损耗集中在图形几何计算中;已知intersects方法自带有envelope快速检测,会过滤掉绝大部分不包含此坐标点图形,剩下为数不多的几个图形将进行实质上的几何关系计算,边界图形的坐标点数越多,性能越低(比如内蒙的边界5万多个点,计算非常费时)。 289 | 290 | 因此只要减少边界图形的坐标点,查询性能就会提升,极端的就是4个坐标点,查询性能最高;我们就可以将大的边界图形切割成很小的图形,并且尽量使图形内部大面积的切成矩形(4个坐标点),查询性能就得到很大的提升;`AreaCityQuery`内的`GeometryGridSplit`方法就是按照这个原则对边界图形进行切割拆分的。 291 | 292 | 用`Debug_ReadGeometryGridSplitsWKT`方法、或测试控制台内菜单`查询: Debug 读取边界网格划分图形WKT文本数据`来导出拆分后的图形WKT数据,然后可以直接粘贴到《[ECharts Map四级下钻在线测试和预览+代码生成](https://xiangyuecn.github.io/AreaCity-JsSpider-StatsGov/assets/geo-echarts.html)》页面内渲染显示;比如内蒙的边界图形切割后的样子: 293 | 294 | ![HTTP API调用查询](images/use-debug-grid-split.png) 295 | 296 | 上图中内蒙的边界有5万多个坐标点,切割后生成了839个小图形,很多是矩形4个坐标点,只有在边界上的小图形坐标点相对多一点。 297 | 298 | 299 | [​](?) 300 | 301 | ## 内存优化过程 302 | 省市区三级 176MB 的geojson文件,3632条数据不做任何处理,全部解析成Geometry对象加载到内存后,内存占用约318MB。 303 | 304 | 因为几何图形内是大量的双精度浮点数坐标点,因此可以将Geometry对象转成WKB二进制数据,再放到内存里面,另外Geometry对象的envelope对象也需要单独存一份到内存,在查询的时候,先经过envelope急速的初步筛选,筛出来的为数不多的图形,然后取出WKB二进制数据还原成Geometry对象进行几何运算,整个内存占用约140MB,减少一倍多;但此方式增加了WKB还原成Geometry对象的损耗,约0.01ms一次还原;这个就是现在的 Init_StoreInMemory 初始化数据存储方式。 305 | 306 | WKB二进制数据放内存里面始终要占用内存,因此把Geometry对象转成WKB二进制数据后存放到文件里面,内存中只存Geometry对象的envelope对象,在查询的时候,先经过envelope急速的初步筛选,筛出来的为数不多的图形,先从文件读取出对应的WKB二进制数据,然后还原成Geometry对象进行几何运算,整个内存占用约10MB;此方式增加了文件IO损耗(约0.3ms一次IO)和WKB还原成Geometry对象的损耗(约0.01ms一次还原);这个就是现在的 Init_StoreInWkbsFile 初始化数据存储方式。 307 | 308 | 注:在经过性能优化后,每个边界图形切分成了很多个小图形,两种初始化方式对应的内存占用也增大了一些。 309 | 310 | 311 | 312 | 313 | [​](?) 314 | 315 | [​](?) 316 | 317 | [​](?) 318 | 319 | # :star:捐赠 320 | 如果这个库有帮助到您,请 Star 一下。 321 | 322 | 您也可以使用支付宝或微信打赏作者: 323 | 324 | ![](https://github.com/xiangyuecn/Recorder/raw/master/assets/donate-alipay.png) ![](https://github.com/xiangyuecn/Recorder/raw/master/assets/donate-weixin.png) 325 | -------------------------------------------------------------------------------- /Test_HttpApiServer.java: -------------------------------------------------------------------------------- 1 | package com.github.xiangyuecn.areacity.query; 2 | 3 | //要是编译不过,就直接删掉这个文件就好了 4 | //要是编译不过,就直接删掉这个文件就好了 5 | //要是编译不过,就直接删掉这个文件就好了 6 | 7 | import java.io.IOException; 8 | import java.net.InetSocketAddress; 9 | import java.net.URI; 10 | import java.net.URLDecoder; 11 | import java.text.SimpleDateFormat; 12 | import java.util.Date; 13 | import java.util.HashMap; 14 | import java.util.Map.Entry; 15 | import java.util.regex.Matcher; 16 | import java.util.regex.Pattern; 17 | 18 | import org.locationtech.jts.geom.Geometry; 19 | import org.locationtech.jts.io.WKTReader; 20 | 21 | import com.github.xiangyuecn.areacity.query.AreaCityQuery.Func; 22 | import com.github.xiangyuecn.areacity.query.AreaCityQuery.QueryInitInfo; 23 | import com.github.xiangyuecn.areacity.query.AreaCityQuery.QueryResult; 24 | //jre rt.jar com.sun,Eclips不允许引用:Access restriction: The type 'HttpServer' is not API 25 | //Eclips修改项目配置 Java Compiler -> Errors/Warnings -> Deprecated and restricted API,将Error的改成Warning即可 26 | import com.sun.net.httpserver.Headers; 27 | import com.sun.net.httpserver.HttpExchange; 28 | import com.sun.net.httpserver.HttpHandler; 29 | import com.sun.net.httpserver.HttpServer; 30 | 31 | /** 32 | * AreaCityQuery测试本地轻量HTTP API服务 33 | * 34 | * GitHub: https://github.com/xiangyuecn/AreaCity-Query-Geometry (github可换成gitee) 35 | * 省市区县乡镇区划边界数据: https://github.com/xiangyuecn/AreaCity-JsSpider-StatsGov (github可换成gitee) 36 | */ 37 | public class Test_HttpApiServer { 38 | /** 是否允许输出大量WKT数据,默认不允许,只能输出最大20M的数据;如果要设为true,请确保没有 -Xmx300m 限制Java使用小内存 **/ 39 | static public boolean AllowResponseBigWKT=false; 40 | /** 套接字积压:已连上但服务器还未来得及accept的socket排队队列容量。如果此值小于或等于零,则使用系统默认值。用JMeter 200个线程测试能达到1900QPS,这个如果使用很小的值或系统默认值,服务器会拒绝部分连接,调大就正常了,但如果300个线程测试依旧会出现连接错误 **/ 41 | static public int SocketBacklog=1000; 42 | 43 | static private String Desc; 44 | static public boolean Create(String bindIP, int bindPort) { 45 | Desc="========== 本地轻量HTTP API服务 =========="; 46 | Desc+="\n可通过 http://127.0.0.1:"+bindPort+"/ 访问本服务、文档、实例状态,提供的接口:"; 47 | Desc+="\n\n - GET /queryPoint?lng=&lat=&tolerance=&returnWKTKey= 查询出包含此坐标点的所有边界图形的属性数据;lng必填经度,lat必填纬度,returnWKTKey可选要额外返回边界的wkt文本数据放到此key下。tolerance可选,距离范围容差值,单位米,比如2500相当于一个以此坐标为中心点、半径为2.5km的圆形范围,-1不限制距离;当坐标位于界线外侧(如海岸线、境界线)时QueryPoint方法将不会有边界图形能够匹配包含此坐标(就算距离只相差1cm),传了此参数后,会查询出在这个范围内和此坐标点距离最近的边界数据,并且结果属性中会额外添加PointDistance(图形与坐标的距离,单位米)、PointDistanceID(图形唯一标识符)两个值。"; 48 | Desc+="\n\n - GET /queryGeometry?wkt=&returnWKTKey= 查询出和此图形(点、线、面)有交点的所有边界图形的属性数据(包括边界相交);wkt必填任意图形,returnWKTKey可选要额外返回边界的wkt文本数据放到此key下。"; 49 | Desc+="\n\n - GET /readWKT?id=&pid=&deep=&extPath=&returnWKTKey= 读取边界图形的WKT文本数据;前四个参数可以组合查询或查一个参数(边界的属性中必须要有这些字段才能查询出来),id:查询指定id|unique_id的边界;pid:查询此pid下的所有边界;deep:限制只返回特定层级的数据,取值:0省1市2区想3乡镇;extPath:查询和ext_path完全相同值的边界,首尾支持*通配符(如:*武汉*);returnWKTKey回边界的wkt文本数据放到此key下,默认值polygon_wkt,填0不返回wkt文本数据;注意:默认只允许输出最大20M的WKT数据,请参考下面的注意事项。"; 50 | Desc+="\n\n - GET /debugReadGeometryGridSplitsWKT?id=&pid=&deep=&extPath=&returnWKTKey= Debug读取边界网格划分图形WKT文本数据;参数和/readWKT接口一致。"; 51 | Desc+="\n\n - JSON响应:{c:0, v:{...}, m:\"错误消息\"} c=0代表接口调用成功,v为内容;c=其他值调用错误,m为错误消息。"; 52 | Desc+="\n\n - 指定查询实例:接口前面加/0-"+(AreaCityQuery.Instances.length-1)+"/,或使用instance=0-"+(AreaCityQuery.Instances.length-1)+"参数来指定需要调用的静态实例,默认为AreaCityQuery.Instances[0]实例;允许同时使用多个数据文件来分别初始化多个实例,然后查询时指定需要调用哪个实例。"; 53 | Desc+="\n\n - 注意:所有输入坐标参数的坐标系必须和初始化时使用的geojson数据的坐标系一致,否则坐标可能会有比较大的偏移,导致查询结果不正确。"; 54 | Desc+="\n\n - 注意:如果要输出大量WKT数据,请调大Java内存,不然可能是 -Xmx300m 启动的只允许使用小内存,并且修改服务源码内的AllowResponseBigWKT=true,否则只允许输出最大20M的WKT数据。"; 55 | 56 | System.out.println(Desc); 57 | System.out.println(); 58 | System.out.println("绑定IP: "+bindIP+", Port: "+bindPort+", 正在启动HTTP API服务..."); 59 | 60 | boolean startOK=false; 61 | try { 62 | __Start(bindIP, bindPort); 63 | 64 | startOK=true; 65 | System.out.println("HTTP API服务正在运行,输入 exit 退出服务..."); 66 | while(true){ 67 | String inStr=Test.ReadIn().trim(); 68 | if(inStr.equals("exit")) { 69 | System.out.println("bye! 已退出HTTP API服务。"); 70 | System.out.println(); 71 | 72 | httpServer.stop(0); 73 | httpServer=null; 74 | break; 75 | } 76 | System.out.println("如需退出HTTP API服务请输入exit"); 77 | } 78 | }catch (Exception e) { 79 | e.printStackTrace(); 80 | if(!startOK) { 81 | System.out.println("创建HTTP服务异常:"+e.getMessage()); 82 | System.out.println(); 83 | return false; 84 | } 85 | } 86 | return true; 87 | } 88 | 89 | 90 | 91 | static private void Req_queryPoint(HashMap query, String[] response, String[] responseErr, int[] status, String[] contentType, HashMap respHeader) throws Exception { 92 | double lng=ToNum(query.get("lng"), 999); 93 | double lat=ToNum(query.get("lat"), 999); 94 | int tolerance=(int)ToLong(query.get("tolerance"), 0); 95 | String returnWKTKey=query.get("returnWKTKey"); 96 | if(lng<-180 || lat<-90 || lng>180 || lat>90) { 97 | responseErr[0]="坐标参数值无效"; 98 | return; 99 | } 100 | AreaCityQuery instance=GetInstance(query, responseErr); 101 | if(instance==null) return; 102 | 103 | QueryResult res=new QueryResult(); 104 | if(returnWKTKey!=null && returnWKTKey.length()>0) { 105 | res.Set_ReturnWKTKey=returnWKTKey; 106 | } 107 | if(tolerance==0) { 108 | instance.QueryPoint(lng, lat, null, res); 109 | }else { 110 | instance.QueryPointWithTolerance(lng, lat, null, res, tolerance); 111 | } 112 | 113 | response[0]=ResToJSON(res); 114 | } 115 | 116 | static private void Req_queryGeometry(HashMap query, String[] response, String[] responseErr, int[] status, String[] contentType, HashMap respHeader) throws Exception { 117 | String wkt=query.get("wkt"); 118 | String returnWKTKey=query.get("returnWKTKey"); 119 | if(wkt==null || wkt.length()==0) { 120 | responseErr[0]="wkt参数无效"; 121 | return; 122 | } 123 | Geometry geom; 124 | try { 125 | geom=new WKTReader(AreaCityQuery.Factory).read(wkt); 126 | }catch (Exception e) { 127 | responseErr[0]="wkt参数解析失败:"+e.getMessage(); 128 | return; 129 | } 130 | AreaCityQuery instance=GetInstance(query, responseErr); 131 | if(instance==null) return; 132 | 133 | QueryResult res=new QueryResult(); 134 | if(returnWKTKey!=null && returnWKTKey.length()>0) { 135 | res.Set_ReturnWKTKey=returnWKTKey; 136 | } 137 | instance.QueryGeometry(geom, null, res); 138 | 139 | response[0]=ResToJSON(res); 140 | } 141 | 142 | static private void Req_readWKT(boolean debugReadGrid, HashMap query, String[] response, String[] responseErr, int[] status, String[] contentType, HashMap respHeader) throws Exception { 143 | long id=ToLong(query.get("id"), -1); 144 | long pid=ToLong(query.get("pid"), -1); 145 | long deep=ToLong(query.get("deep"), -1); 146 | String extPath=query.get("extPath"); if(extPath==null) extPath=""; 147 | String returnWKTKey=query.get("returnWKTKey"); 148 | if(id==-1 && pid==-1 && deep==-1 && extPath.length()==0) { 149 | responseErr[0]="请求参数无效"; 150 | return; 151 | } 152 | if(returnWKTKey==null || returnWKTKey.length()==0) { 153 | returnWKTKey="polygon_wkt"; 154 | } 155 | if("0".equals(returnWKTKey)) { 156 | returnWKTKey=null; 157 | } 158 | AreaCityQuery instance=GetInstance(query, responseErr); 159 | if(instance==null) return; 160 | 161 | String exp=extPath; 162 | if(extPath!=null && extPath.length()>0) { 163 | if(exp.equals("*")) { 164 | exp=""; 165 | } else { 166 | if(exp.startsWith("*")) { 167 | exp=exp.substring(1); 168 | }else { 169 | exp="\""+exp; 170 | } 171 | if(exp.endsWith("*")) { 172 | exp=exp.substring(0, exp.length()-1); 173 | }else { 174 | exp=exp+"\""; 175 | } 176 | } 177 | } 178 | String exp_=exp; 179 | String extPath_=extPath; 180 | 181 | int[] readCount=new int[] {0}; 182 | boolean[] isWktSizeErr=new boolean[] {false}; 183 | int[] wktSize=new int[] {0}; 184 | Func where=new Func() { 185 | @Override 186 | public Boolean Exec(String prop) throws Exception { 187 | String prop2=(","+prop.substring(1, prop.length()-1)+",").replace("\"", "").replace(" ", ""); //不解析json,简单处理 188 | if(id!=-1) { 189 | if(!prop2.contains(",id:"+id+",") && !prop2.contains(",unique_id:"+id+",")) { 190 | return false; 191 | } 192 | } 193 | if(pid!=-1) { 194 | if(!prop2.contains(",pid:"+pid+",")) { 195 | return false; 196 | } 197 | } 198 | if(deep!=-1) { 199 | if(!prop2.contains(",deep:"+deep+",")) { 200 | return false; 201 | } 202 | } 203 | if(extPath_.length()>0) { 204 | int i0=prop.indexOf("ext_path"); 205 | if(i0==-1)return false; 206 | int i1=prop.indexOf(",", i0); 207 | if(i1==-1)i1=prop.length(); 208 | if(!prop.substring(i0+9, i1).contains(exp_)) { 209 | return false; 210 | } 211 | } 212 | 213 | readCount[0]++; 214 | if(isWktSizeErr[0]) { 215 | return false; 216 | } 217 | return true; 218 | } 219 | }; 220 | Func onFind=new Func() { 221 | @Override 222 | public Boolean Exec(String[] val) throws Exception { 223 | wktSize[0]+=val[1].length(); 224 | if(!AllowResponseBigWKT && wktSize[0]>20*1024*1024) { 225 | isWktSizeErr[0]=true; 226 | return false; 227 | } 228 | return true; 229 | } 230 | }; 231 | QueryResult res; 232 | if(debugReadGrid) { 233 | res=instance.Debug_ReadGeometryGridSplitsWKT(returnWKTKey, null, where, onFind); 234 | } else { 235 | res=instance.ReadWKT_FromWkbsFile(returnWKTKey, null, where, onFind); 236 | } 237 | 238 | if(isWktSizeErr[0]) { 239 | responseErr[0]="已匹配到"+readCount[0]+"条数据,但WKT数据量超过20M限制,可修改服务源码内的AllowResponseBigWKT=true来解除限制"; 240 | return; 241 | } 242 | response[0]=ResToJSON(res); 243 | } 244 | 245 | 246 | 247 | static private AreaCityQuery GetInstance(HashMap query, String[] responseErr) { 248 | int idx=(int)ToLong(query.get("instance"), 0); 249 | if(idx<0 || idx>=AreaCityQuery.Instances.length) { 250 | responseErr[0]="AreaCityQuery实例值"+idx+"无效"; 251 | return null; 252 | } 253 | AreaCityQuery val=AreaCityQuery.Instances[idx]; 254 | try { 255 | val.CheckInitIsOK(); 256 | }catch(Exception e) { 257 | responseErr[0]="AreaCityQuery实例"+idx+"未初始化完成:"+e.getMessage(); 258 | return null; 259 | } 260 | return val; 261 | } 262 | 263 | static private String ResToJSON(QueryResult res) { 264 | StringBuilder json=new StringBuilder(); 265 | json.append("{\"list\":[");//手撸json 266 | for(int i=0,L=res.Result.size();i0) json.append(","); 268 | json.append(res.Result.get(i)); 269 | res.Result.set(i, null);//已读取了结果就释放掉内存 270 | } 271 | json.append("]}"); 272 | return json.toString(); 273 | } 274 | static private String StringInnerJson(String str) { 275 | if (str==null || str.length()==0) { 276 | return ""; 277 | } 278 | int len = str.length(); 279 | StringBuilder sb = new StringBuilder(len * 2); 280 | char chr; 281 | for (int i = 0; i < len; i++) { 282 | chr = str.charAt(i); 283 | switch (chr) { 284 | case '"': 285 | sb.append('\\').append('"'); break; 286 | case '\\': 287 | sb.append('\\').append('\\'); break; 288 | case '\n': 289 | sb.append('\\').append('n'); break; 290 | case '\r': 291 | sb.append('\\').append('r'); break; 292 | default: 293 | sb.append(chr); 294 | break; 295 | } 296 | } 297 | return sb.toString(); 298 | } 299 | static private long ToLong(String val, long def) { 300 | if(val==null || val.length()==0) { 301 | return def; 302 | } 303 | try { 304 | return Long.parseLong(val); 305 | }catch (Exception e) { 306 | return def; 307 | } 308 | } 309 | static private double ToNum(String val, double def) { 310 | if(val==null || val.length()==0) { 311 | return def; 312 | } 313 | try { 314 | return Double.parseDouble(val); 315 | }catch (Exception e) { 316 | return def; 317 | } 318 | } 319 | 320 | 321 | 322 | 323 | 324 | static private HttpServer httpServer; 325 | static private Pattern Exp_PathInstance=Pattern.compile("^/(\\d+)(/.+)"); 326 | static private void __Start(String bindIP, int bindPort) throws Exception { 327 | if(httpServer!=null) { 328 | try { 329 | httpServer.stop(0); 330 | }catch(Exception e) {} 331 | } 332 | Func fn=new Func() { 333 | @Override 334 | public Object Exec(HttpExchange context) throws Exception { 335 | URI url=context.getRequestURI(); 336 | String path=url.getPath(); if(path==null||path.length()==0)path="/"; 337 | String queryStr=url.getQuery(); if(queryStr==null) queryStr=""; 338 | String method=context.getRequestMethod(); if(method==null)method=""; 339 | method=method.toUpperCase(); 340 | 341 | HashMap query=new HashMap<>(); 342 | String apiPath=path; 343 | Matcher m=Exp_PathInstance.matcher(apiPath); 344 | if(m.find()) { 345 | apiPath=m.group(2); 346 | query.put("instance", m.group(1)); 347 | } 348 | 349 | String[] queryArr=queryStr.split("&"); 350 | for(String s : queryArr) { 351 | if(s.length()>0) { 352 | String[] kv=s.split("="); 353 | if(kv.length==2) { 354 | query.put(kv[0], URLDecoder.decode(kv[1], "utf-8")); 355 | } 356 | } 357 | } 358 | 359 | int[] status=new int[] { 200 }; 360 | String[] contentType=new String[] {"text/json; charset=utf-8"}; 361 | HashMap respHeader=new HashMap<>(); 362 | respHeader.put("Access-Control-Allow-Origin", "*"); 363 | 364 | 365 | boolean isApi=true, isHtml=false; 366 | String[] response=new String[] { "" }; 367 | String[] responseErr=new String[] { "" }; 368 | try { 369 | if(!method.equals("POST") && !method.equals("GET")) { 370 | isApi=false; isHtml=true; 371 | response[0]="Method: "+method; 372 | } else if(apiPath.equals("/queryPoint")){ 373 | Req_queryPoint(query, response, responseErr, status, contentType, respHeader); 374 | } else if (apiPath.equals("/queryGeometry")) { 375 | Req_queryGeometry(query, response, responseErr, status, contentType, respHeader); 376 | } else if (apiPath.equals("/readWKT")) { 377 | Req_readWKT(false, query, response, responseErr, status, contentType, respHeader); 378 | } else if (apiPath.equals("/debugReadGeometryGridSplitsWKT")) { 379 | Req_readWKT(true, query, response, responseErr, status, contentType, respHeader); 380 | } else if (path.equals("/")) { 381 | isApi=false; isHtml=true; 382 | String html="\n\n\n\n【请求IP】\n"+context.getRemoteAddress().getAddress().getHostAddress(); 383 | if(context.getRemoteAddress().getAddress().isLoopbackAddress()) { 384 | html+="\n\n【静态实例列表】仅服务器本地访问可见"; 385 | for(int i=0;i\n" 399 | +Desc+html+"\n"; 400 | } else { 401 | isApi=false; isHtml=true; 402 | status[0]=404; 403 | response[0]="

请求路径 "+path+" 不存在!

"; 404 | } 405 | } catch (Throwable e) { 406 | e.printStackTrace(); 407 | if(e instanceof OutOfMemoryError) { 408 | System.gc(); 409 | } 410 | responseErr[0]="接口调用异常:"+e.getMessage(); 411 | } 412 | 413 | 414 | if(isApi) { 415 | if(responseErr[0].length()>0) {//手撸json 416 | response[0]="{\"c\":1,\"v\":null,\"m\":\""+StringInnerJson(responseErr[0])+"\"}"; 417 | } else { 418 | response[0]="{\"c\":0,\"v\":"+response[0]+",\"m\":\"\"}"; 419 | } 420 | } 421 | if(isHtml) { 422 | contentType[0]="text/html; charset=utf-8"; 423 | } 424 | 425 | respHeader.put("Content-Type", contentType[0]); 426 | Headers header=context.getResponseHeaders(); 427 | for(Entry kv : respHeader.entrySet()) { 428 | header.set(kv.getKey(), kv.getValue()); 429 | } 430 | 431 | byte[] sendData=response[0].getBytes("utf-8"); 432 | context.sendResponseHeaders(status[0], sendData.length); 433 | context.getResponseBody().write(sendData); 434 | 435 | 436 | StringBuilder log=new StringBuilder(); 437 | log.append("["+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+"]"); 438 | log.append(status[0]); 439 | log.append(" "+method); 440 | log.append(" "+path); 441 | if(queryStr.length()>0) { 442 | log.append("?"+queryStr); 443 | } 444 | log.append(" "+sendData.length); 445 | System.out.println(log); 446 | 447 | return null; 448 | } 449 | }; 450 | 451 | // https://www.apiref.com/java11-zh/jdk.httpserver/com/sun/net/httpserver/HttpServer.html 452 | httpServer = HttpServer.create(new InetSocketAddress(bindIP, bindPort), SocketBacklog); 453 | httpServer.createContext("/", new HttpHandler() { 454 | @Override 455 | public void handle(HttpExchange context) throws IOException { 456 | try { 457 | fn.Exec(context); 458 | } catch (Throwable e) { 459 | e.printStackTrace(); 460 | if(e instanceof OutOfMemoryError) { 461 | System.gc(); 462 | } 463 | } 464 | context.close(); 465 | } 466 | }); 467 | httpServer.start(); 468 | } 469 | } 470 | -------------------------------------------------------------------------------- /Test.java: -------------------------------------------------------------------------------- 1 | package com.github.xiangyuecn.areacity.query; 2 | 3 | import java.io.ByteArrayOutputStream; 4 | import java.io.File; 5 | import java.io.FileOutputStream; 6 | import java.lang.reflect.Method; 7 | import java.util.ArrayList; 8 | import java.util.Random; 9 | import java.util.regex.Matcher; 10 | import java.util.regex.Pattern; 11 | 12 | import org.locationtech.jts.geom.Coordinate; 13 | import org.locationtech.jts.geom.Geometry; 14 | import org.locationtech.jts.io.WKTReader; 15 | 16 | import com.github.xiangyuecn.areacity.query.AreaCityQuery.Func; 17 | import com.github.xiangyuecn.areacity.query.AreaCityQuery.QueryInitInfo; 18 | import com.github.xiangyuecn.areacity.query.AreaCityQuery.QueryResult; 19 | 20 | /** 21 | * AreaCityQuery测试控制台主程序 22 | * 23 | * GitHub: https://github.com/xiangyuecn/AreaCity-Query-Geometry (github可换成gitee) 24 | * 省市区县乡镇区划边界数据: https://github.com/xiangyuecn/AreaCity-JsSpider-StatsGov (github可换成gitee) 25 | */ 26 | public class Test { 27 | static public void main(String[] args) throws Exception { 28 | //【请在这里编写你自己的测试代码】 29 | 30 | 31 | /***【运行时直接启动http api服务】 这行开头加个/即可解开这个注释,代码即生效,下面填写实际的json文件路径 32 | // 比如在服务器里面用,使用这段代码不会显示命令行菜单,会直接启动http服务;linux服务器中可使用 `nohup bash xxx.sh` 命令执行后台运行 33 | Init_FromFile(0, true, "D:/xxx/ok_geo.json"); //支持使用.json、.geojson、.wkbs文件进行初始化 34 | //Init_FromFile(1, true, "D:/xxx/xx1.json"); //允许使用不同的数据文件初始化多个静态实例,api接口可以调用不同实例进行查询 35 | //Init_FromFile(2, true, "D:/xxx/xx2.json"); 36 | StartHttpApiServer(HttpApiServerPort); //直接启动http api服务,可指定端口 37 | if(true)return; 38 | // ***/ 39 | 40 | 41 | 42 | /***【基础调用示例代码】 这行开头加个/即可解开这个注释,代码即生效 43 | String jsonFile="仅供测试-全国省级GeoJSON数据-大幅简化粗略版.json"; 44 | //先获取到查询实例,默认提供的0-9的10个静态实例,每个实例可以分别使用一个数据文件进行初始化和查询,当然自己调用new AreaCityQuery()创建一个新实例使用也是一样的 45 | AreaCityQuery Instance=AreaCityQuery.Instances[0]; 46 | //static public final AreaCityQuery Instance=new AreaCityQuery(); //也可以自己创建静态实例 47 | 48 | //查询前先初始化,每个实例全局只会初始化一次,每次查询前都调用即可(查询会在初始化完成后进行),两种初始化方式根据自己业务情况二选一 49 | //首次初始化会从.json或.geojson文件中读取边界图形数据,速度比较慢,会自动生成.wkbs结尾的结构化文件,下次初始化就很快了 50 | //首次初始化生成了.wkbs文件后,后续初始化可以只使用此wkbs文件,允许不用再提供geojson文件(数据更新时需删除wkbs文件再重新用geojson文件进行初始化),具体请阅读对应初始化方法的注释文档 51 | Instance.Init_StoreInWkbsFile(jsonFile, jsonFile+".wkbs", true); 52 | //Instance.Init_StoreInMemory("geojson文件路径", "geojson文件路径.wkbs", true); 53 | 54 | //Instance.OnInitProgress=(initInfo)->{ ... } //初始化过程中的回调,可以绑定一个函数,接收初始化进度信息(编写时需在Init之前进行绑定) 55 | System.out.println(Instance.GetInitInfo().toString()); //打印初始化详细信息,包括性能信息 56 | 57 | //注意:以下查询中所有坐标参数的坐标系必须和初始化时使用的geojson数据的坐标系一致,否则坐标可能会有比较大的偏移,导致查询结果不正确 58 | //查询包含一个坐标点的所有边界图形的属性数据,可通过res参数让查询额外返回wkt格式边界数据 59 | //查询结果的判定:请不要假定查询结果的数量(坐标刚好在边界上可能会查询出多个省市区),也不要假定查询结果顺序(结果中省市区顺序是乱序的),请检查判定res1.Result中的结果是否符合查询的城市级别,比如查询省市区三级:结果中必须且仅有3条数据,并且省市区都有(判断deep=0省|1市|2区 来区分数据的级别),其他一律判定为查询无效 60 | QueryResult res1=Instance.QueryPoint(114.044346, 22.691963, null, null); 61 | //当坐标位于界线外侧(如海岸线、境界线)时QueryPoint方法将不会有边界图形能够匹配包含此坐标(就算距离只相差1cm),下面这个方法将能够匹配到附近不远的边界图形数据;2500相当于一个以此坐标为中心点、半径为2.5km的圆形范围,会查询出在这个范围内和此坐标点距离最近的边界 62 | QueryResult res1_2=Instance.QueryPointWithTolerance(121.993491, 29.524288, null, null, 2500); 63 | 64 | //查询和一个图形(点、线、面)有交点的所有边界图形的属性数据,可通过res参数让查询额外返回wkt格式边界数据 65 | Geometry geom=new WKTReader(AreaCityQuery.Factory).read("LINESTRING(114.30115 30.57962, 117.254285 31.824198, 118.785633 32.064869)"); 66 | //Geometry geom=AreaCityQuery.CreateSimpleCircle(114.044346, 22.691963, 10000, 24); //以指定坐标为中心点,创建一个半径为10km的圆面,圆面由24个坐标点粗略构成 67 | QueryResult res2=Instance.QueryGeometry(geom, null, null); 68 | 69 | //读取省市区的边界数据wkt格式,这个例子会筛选出武汉市所有区县 70 | QueryResult res3=Instance.ReadWKT_FromWkbsFile("wkt_polygon", null, (prop)->{return prop.contains("武汉市 ");}, null); 71 | //此方法会遍历所有边界图形的属性列表,因此可以用来遍历所有数据,提取感兴趣的属性内容,比如查询一个区划编号id对应的城市信息(城市名称、中心点) 72 | QueryResult res4=Instance.ReadWKT_FromWkbsFile(null, null, (prop)->{ 73 | prop=(","+prop.substring(1, prop.length()-1)+",").replace("\"", "").replace(" ", ""); //不解析json,简单处理 74 | return prop.contains(",id:42,"); //只查询出id=42(湖北省)的属性数据(注意初始化的geojson中必须要有对应的属性名,这里是id) 75 | }, null); 76 | 77 | 78 | System.out.println(res1+"\n"+res1_2+"\n"+res2+"\n"+res3+"\n"+res4); 79 | if(true)return; 80 | // ***/ 81 | 82 | 83 | Start(args); 84 | } 85 | 86 | 87 | static int CurrentIdx=0; 88 | static AreaCityQuery Current=AreaCityQuery.Instances[CurrentIdx]; 89 | /** 初始化时,只读取区县级数据,否则省市区都读 **/ 90 | static boolean Deep2Only=false; 91 | /** http api 服务端口号**/ 92 | static int HttpApiServerPort=9527; 93 | 94 | /**使用数据文件直接对实例进行初始化*/ 95 | static void Init_FromFile(int instance, boolean storeInWkbsFile, String dataFile) throws Exception { 96 | CurrentIdx=instance; 97 | Current=AreaCityQuery.Instances[instance]; 98 | Init__(storeInWkbsFile, dataFile); 99 | Current.CheckInitIsOK(); 100 | } 101 | 102 | static long BootMaxMemory; 103 | /**命令行菜单调用初始化*/ 104 | static void Init_FromMenu(boolean storeInWkbsFile) throws Exception { 105 | if(BootMaxMemory==0) BootMaxMemory=Runtime.getRuntime().maxMemory(); 106 | if(BootMaxMemory > 300*1000*1000) { 107 | System.out.println("可以在启动参数中配置 -Xmx300m 调小内存来测试。"); 108 | } 109 | System.out.println("========== "+(storeInWkbsFile?"Init_StoreInWkbsFile":"Init_StoreInMemory")+" =========="); 110 | 111 | File file=new File("./"); 112 | String[] files=file.list(); 113 | ArrayList jsonFiles=new ArrayList<>(); 114 | ArrayList wkbsFiles=new ArrayList<>(); 115 | for(String name : files) { 116 | String str=name.toLowerCase(); 117 | if(str.endsWith("json") || str.endsWith("geojson")) { 118 | jsonFiles.add(name); 119 | } 120 | if(str.endsWith("wkbs")) { 121 | wkbsFiles.add(name); 122 | } 123 | } 124 | String dataFile=""; 125 | 126 | 127 | System.out.println("Init_StoreInWkbsFile:用加载数据到结构化数据文件的模式进行初始化,推荐使用本方法初始化,边界图形数据存入结构化数据文件中,内存占用很低,查询时会反复读取文件对应内容,查询性能消耗主要在IO上,IO性能极高问题不大。"); 128 | System.out.println("Init_StoreInMemory:用加载数据到内存的模式进行初始化,边界图形数据存入内存中,内存占用和json数据文件大小差不多大,查询性能极高;另外可通过设置 Instances[0-9].SetInitStoreInMemoryUseObject=true 来进一步提升性能,但内存占用会增大一倍多。"); 129 | System.out.println(HR); 130 | System.out.println("首次初始化会从.json或.geojson文件中读取边界图形数据,并生成.wkbs结尾的结构化文件,速度比较慢(文件读写);下次会直接从.wkbs文件进行初始化(文件只读不写),就很快了,可copy此.wkbs文件到别的地方使用(比如服务器、只读环境中)。"); 131 | System.out.println(" - 如果.wkbs文件已存在并且有效,将优先从wkbs文件中读取数据,速度很快。"); 132 | System.out.println(" - 你可以在当前目录内放入 .json|.geojson|.wkbs 文件(utf-8),可通过菜单进行选择初始化,否则需要输入文件路径。"); 133 | System.out.println(" - 当前目录:"+new File("").getAbsolutePath()); 134 | System.out.println(" - json文件内必须一条数据占一行,如果不是将不支持解析,请按下面的方法生成一个json文件测试。"); 135 | System.out.println(HR); 136 | System.out.println("如何获取省市区县乡镇边界数据json文件:"); 137 | System.out.println(" 1. 请到开源库下载省市区边界数据ok_geo.csv文件: https://github.com/xiangyuecn/AreaCity-JsSpider-StatsGov (github可换成gitee);"); 138 | System.out.println(" 2. 下载开源库里面的“AreaCity-Geo格式转换工具软件”;"); 139 | System.out.println(" 3. 打开转换工具软件,选择ok_geo.csv,然后导出成geojson文件即可(默认会导出全国的省级数据,通过填写不同城市名前缀可以导出不同城市);"); 140 | System.out.println(" 4. 将导出的json文件复制到本java程序目录内,然后重新运行初始化即可解析使用此文件。"); 141 | System.out.println(HR); 142 | boolean useInputFile=false; 143 | boolean useChoice=false; 144 | if(jsonFiles.size()>0 || wkbsFiles.size()>0) { 145 | useChoice=true; 146 | } else { 147 | System.out.println("在当前目录内未发现任何一个 .json|.geojson|.wkbs 文件,需手动填写文件路径。"); 148 | System.out.println(); 149 | useInputFile=true; 150 | } 151 | if(useChoice) { 152 | System.out.println("在当前目录内发现数据文件,请选择要从哪个文件初始化,请输入文件序号:"); 153 | int idx=0; 154 | System.out.println(idx+". 手动输入文件路径"); 155 | for(String name : jsonFiles) { 156 | idx++; 157 | System.out.println(idx+". [json]"+name); 158 | } 159 | for(String name : wkbsFiles) { 160 | idx++; 161 | System.out.println(idx+". [wkbs]"+name); 162 | } 163 | while(true) { 164 | System.out.print("> "); 165 | String txt=ReadIn(); 166 | if(txt.length()==0){ 167 | break; 168 | } else if(txt.equals("0")) { 169 | useInputFile=true; 170 | break; 171 | } else if(txt.length()>0) { 172 | idx=-1; 173 | try { idx=Integer.parseInt(txt); } catch (Exception e){ } 174 | if(idx>0 && idx<=jsonFiles.size()) { 175 | dataFile=jsonFiles.get(idx-1); 176 | } else if(idx>0 && idx-jsonFiles.size()<=wkbsFiles.size()) { 177 | dataFile=wkbsFiles.get(idx-jsonFiles.size()-1); 178 | } else { 179 | System.out.println("输入的序号无效,请重新输入!"); 180 | continue; 181 | } 182 | break; 183 | } 184 | } 185 | } 186 | if(useInputFile) { 187 | System.out.println("请输入初始化要读取的一个 .json|.geojson|.wkbs 文件完整路径:"); 188 | while(true) { 189 | System.out.print("> "); 190 | String txt=ReadIn(); 191 | String str=txt.toLowerCase(); 192 | if(txt.length()==0) { 193 | break; 194 | } else if(str.endsWith("json") || str.endsWith("geojson")) { 195 | dataFile=txt; 196 | } else if (str.endsWith("wkbs")) { 197 | dataFile=txt; 198 | } else { 199 | System.out.println("输入的文件类型无效,请重新输入!"); 200 | continue; 201 | } 202 | File f=new File(txt); 203 | if(!f.exists()) { 204 | dataFile=""; 205 | System.out.println("文件不存在,请重新输入!(未找到文件:"+f.getAbsolutePath()+")"); 206 | continue; 207 | } 208 | break; 209 | } 210 | } 211 | 212 | Init__(storeInWkbsFile, dataFile); 213 | } 214 | 215 | /**省**/static boolean[] HasDeep0=new boolean[AreaCityQuery.Instances.length]; 216 | /**市**/static boolean[] HasDeep1=new boolean[AreaCityQuery.Instances.length]; 217 | /**区县**/static boolean[] HasDeep2=new boolean[AreaCityQuery.Instances.length]; 218 | /**乡镇街道**/static boolean[] HasDeep3=new boolean[AreaCityQuery.Instances.length]; 219 | static void Init__(boolean storeInWkbsFile, String dataFile) throws Exception { 220 | String initDataFile,initSaveWkbsFile; 221 | String str=dataFile.toLowerCase(); 222 | if(str.endsWith("json") || str.endsWith("geojson")) { 223 | initDataFile=new File(dataFile).getAbsolutePath(); 224 | initSaveWkbsFile=initDataFile+".wkbs"; 225 | if(!storeInWkbsFile) { 226 | System.out.println("用json文件进行Init_StoreInMemory初始化时,可选提供一个.wkbs后缀的文件路径,初始化时会自动生成此文件,如果不提供将不能查询WKT数据;直接回车提供,输入n不提供:"); 227 | System.out.print("> "); 228 | String txt=ReadIn(); 229 | if(txt.toLowerCase().equals("n")) { 230 | initSaveWkbsFile=""; 231 | } 232 | } 233 | } else if(str.endsWith("wkbs")) { 234 | initDataFile=new File(dataFile).getAbsolutePath(); 235 | initSaveWkbsFile=""; 236 | } else { 237 | System.out.println("未选择文件,不初始化,已退出!"); 238 | return; 239 | } 240 | 241 | HasDeep0[CurrentIdx]=HasDeep1[CurrentIdx]=HasDeep2[CurrentIdx]=HasDeep3[CurrentIdx]=false; 242 | 243 | //初始化回调 244 | Current.OnInitProgress=new Func() { 245 | long logTime=0;int maxNo=0,lastNo=0; 246 | @Override 247 | public Boolean Exec(QueryInitInfo info) throws Exception { 248 | if(logTime==0) { 249 | if(info.DataFromWkbsFile) { 250 | System.out.println("正在从wkbs结构化数据文件中快速读取数据..."); 251 | } else if(info.HasWkbsFile){ 252 | System.out.println("首次运行,正在生成wkbs结构化数据文件,速度可能会比较慢..."); 253 | } else { 254 | System.out.println("正在从json文件中读取数据,未提供wkbs文件,速度可能会比较慢..."); 255 | } 256 | } 257 | if(info.CurrentLine_No!=0) { 258 | maxNo=info.CurrentLine_No; 259 | } 260 | if(info.CurrentLine_No==0 && lastNo!=maxNo || System.currentTimeMillis()-logTime>1000) { 261 | logTime=System.currentTimeMillis(); 262 | lastNo=maxNo; 263 | System.out.println("读取第"+lastNo+"行..."); 264 | } 265 | if(info.CurrentLine_No!=0) { 266 | String prop=info.CurrentLine_Prop.replace(" ", "").replace("\"", ""); //不解析json,简单处理 267 | if(!Deep2Only && !HasDeep0[CurrentIdx])HasDeep0[CurrentIdx]=prop.contains("deep:0"); 268 | if(!Deep2Only && !HasDeep1[CurrentIdx])HasDeep1[CurrentIdx]=prop.contains("deep:1"); 269 | if(!HasDeep2[CurrentIdx])HasDeep2[CurrentIdx]=prop.contains("deep:2"); 270 | if(!Deep2Only && !HasDeep3[CurrentIdx])HasDeep3[CurrentIdx]=prop.contains("unique_id:"); 271 | 272 | if(Deep2Only) { 273 | return prop.contains("deep:2"); //只提取区级,其他一律返回false跳过解析 274 | } 275 | } 276 | return true; 277 | } 278 | }; 279 | //初始化,如果未生成结构化数据文件(wkbs)这里会从json数据文件自动生成,如果生成了就只会读取wkbs文件 280 | if(storeInWkbsFile) { 281 | Current.Init_StoreInWkbsFile(initDataFile, initSaveWkbsFile, true); 282 | } else { 283 | Current.Init_StoreInMemory(initDataFile, initSaveWkbsFile, true); 284 | } 285 | 286 | System.out.println("========== "+(storeInWkbsFile?"Init_StoreInWkbsFile":"Init_StoreInMemory")+" =========="); 287 | System.out.println(Current.GetInitInfo().toString()); 288 | System.out.println(); 289 | System.out.println("已加载数据级别:"+(HasDeep0[CurrentIdx]?"√":"×")+"省,"+(HasDeep1[CurrentIdx]?"√":"×")+"市,"+(HasDeep2[CurrentIdx]?"√":"×")+"区县,"+(HasDeep3[CurrentIdx]?"√":"×")+"乡镇 (×为未加载,可能是数据文件中并不含此级数据)"); 290 | System.out.println(); 291 | } 292 | 293 | static boolean ResultHas(QueryResult res, String str) { 294 | if(res.Result!=null) { 295 | for(int i=0,L=res.Result.size();i(); 310 | //res.Set_ReturnWKTKey="polygon_wkt"; 311 | for(int i=0;i(); 327 | double lng=121.993491,lat=29.524288; 328 | QueryResult res2=instance.QueryPoint(lng, lat, null, null); 329 | for(int i=0;i() { 359 | @Override 360 | public Boolean Exec(String prop) throws Exception { 361 | int i0=prop.indexOf("deep\"");//高性能手撸json字符串 362 | if(i0==-1)return false; 363 | int i1=prop.indexOf(",", i0); 364 | if(i1==-1)i1=prop.length(); 365 | return prop.substring(i0+6,i1).contains("0");//where条件过滤,只查找省级数据(deep==0,json内就是{deep:0}) 366 | } 367 | }, res); 368 | } 369 | System.out.println(res.toString()); 370 | System.out.println(ResultHas(res, "湖北省\"") 371 | && ResultHas(res, "河南省\"") 372 | && ResultHas(res, "安徽省\"") ?"OK":"查询失败!"); 373 | } 374 | 375 | System.out.println(); 376 | System.out.println("========== ReadWKT_FromWkbsFile =========="); 377 | { 378 | QueryResult res=new QueryResult(); 379 | for(int i=0;i() { 387 | @Override 388 | public Boolean Exec(String prop) throws Exception { 389 | return prop.contains("北京市 朝阳区\"") 390 | || prop.contains("武汉市 洪山区\"") 391 | || prop.contains("台北市 中山区\""); 392 | } 393 | }, null); 394 | } 395 | System.out.println(res.toString()); 396 | if(HasDeep2[instanceIdx]) { 397 | System.out.println(ResultHas(res, "北京市 朝阳区\"") 398 | && ResultHas(res, "武汉市 洪山区\"") 399 | && ResultHas(res, "台北市 中山区\"") ?"OK":"查询失败!"); 400 | } 401 | } 402 | System.out.println(); 403 | } 404 | 405 | static void LargeRndPointTest(int instanceIdx) throws Exception { 406 | AreaCityQuery instance=AreaCityQuery.Instances[instanceIdx]; 407 | System.out.println("========== QueryPoint:1万个伪随机点测试 =========="); 408 | System.out.println("伪随机:虽然是随机生成的点,但每次运行生成坐标列表都是相同的。"); 409 | for(int loop=0;loop<2;loop++) { 410 | System.out.println((loop==0?"QueryPoint":"QueryPointWithTolerance")+"测试中,请耐心等待..."); 411 | 412 | QueryResult res=new QueryResult(); 413 | double x_0=98.0,y_00=18.0;//矩形范围囊括大半个中国版图 414 | double x_1=135.0,y_1=42.0; 415 | int size=100;//1万点 416 | double xStep=(x_1-x_0)/size; 417 | double yStep=(y_1-y_00)/size; 418 | while(x_0-x_1<-xStep/2) {//注意浮点数±0.000000001的差异 419 | double x0=x_0, x1=x_0+xStep; x_0=x1; 420 | double y_0=y_00; 421 | while(y_0-y_1<-yStep/2) { 422 | double y0=y_0, y1=y_0+yStep; y_0=y1; 423 | 424 | if(loop==0) { 425 | res=instance.QueryPoint(x0, y0, null, res); 426 | }else { 427 | res=instance.QueryPointWithTolerance(x0, y0, null, res, 2500); 428 | } 429 | res.Result.clear();//只保留统计 430 | } 431 | } 432 | res.Result=null; 433 | System.out.println(res.toString()); 434 | System.out.println(); 435 | } 436 | } 437 | static void ThreadRun(ArrayList idxs) throws Exception { 438 | System.out.println("========== 多线程性能测试 =========="); 439 | boolean[] stop=new boolean[] {false}; 440 | int ThreadCount=Math.max(1, Runtime.getRuntime().availableProcessors()-1); 441 | QueryResult[] SecondCompletes=new QueryResult[ThreadCount]; 442 | 443 | System.out.println("通过开启 CPU核心数-1 个线程,每个线程内随机查询不同的坐标点,来达到性能测试的目的。"); 444 | System.out.println("正在测试中,线程数:"+ThreadCount+",按回车键结束测试..."); 445 | 446 | //测试函数 447 | Func run=new Func() { 448 | @Override 449 | public Object Exec(Object[] args) throws Exception { 450 | QueryResult res=(QueryResult)args[0]; 451 | int instanceIdx=(int)args[1]; 452 | AreaCityQuery instance=AreaCityQuery.Instances[instanceIdx]; 453 | 454 | //固定坐标点测试 455 | boolean allOk=true; 456 | instance.QueryPoint(114.044346, 22.691963, null, res); //广东省 深圳市 龙华区 457 | allOk&=ResultHas(res, "深圳市 龙华区\"");res.Result.clear(); 458 | 459 | instance.QueryPoint(117.286491, 30.450399, null, res); //安徽省 铜陵市 郊区 飞地 460 | allOk&=ResultHas(res, "铜陵市 郊区\"");res.Result.clear(); 461 | 462 | instance.QueryPoint(116.055588, 39.709385, null, res); //北京市 房山区 星城街道 飞地 463 | allOk&=ResultHas(res, "北京市 房山区\"");res.Result.clear(); 464 | 465 | instance.QueryPoint(130.283168, 47.281807, null, res); // 黑龙江省 鹤岗市 南山区 466 | allOk&=ResultHas(res, "鹤岗市 南山区\"");res.Result.clear(); 467 | 468 | instance.QueryPoint(118.161624, 39.656532, null, res); // 河北省 唐山市 路北区 469 | allOk&=ResultHas(res, "唐山市 路北区\"");res.Result.clear(); 470 | 471 | instance.QueryPoint(81.869760, 41.812321, null, res); // 新疆 阿克苏地区 拜城县 472 | allOk&=ResultHas(res, "阿克苏地区 拜城县\"");res.Result.clear(); 473 | 474 | if(HasDeep2[instanceIdx] && !allOk) { 475 | throw new Exception("查询失败!"); 476 | } 477 | 478 | 479 | //随机坐标点测试 480 | Random rnd=new Random(); 481 | int count=100;//只计算100次 482 | 483 | double x_0=98.0+rnd.nextDouble(),y_00=21.0+rnd.nextDouble();//矩形范围囊括大半个中国版图 484 | double x_1=122.0+rnd.nextDouble(),y_1=42.0+rnd.nextDouble(); 485 | int size=100;//1万点 486 | double xStep=(x_1-x_0)/size; 487 | double yStep=(y_1-y_00)/size; 488 | x_0+=(rnd.nextInt(size*size-count))*xStep; //随机选择开始位置 489 | while(x_0-x_1<-xStep/2) {//注意浮点数±0.000000001的差异 490 | double x0=x_0, x1=x_0+xStep; x_0=x1; 491 | double y_0=y_00; 492 | while(y_0-y_1<-yStep/2) { 493 | double y0=y_0, y1=y_0+yStep; y_0=y1; 494 | 495 | instance.QueryPoint(x0, y0, null, res); 496 | res.Result.clear();//只保留统计 497 | 498 | count--; 499 | if(count==0) { 500 | return null; 501 | } 502 | } 503 | } 504 | return null; 505 | } 506 | }; 507 | //更新统计显示 508 | long startTime=System.currentTimeMillis(); 509 | long[] showProgressTime=new long[] {0}; 510 | Func showProgress=new Func() { 511 | @Override 512 | public Object Exec(Object val) throws Exception { 513 | synchronized (showProgressTime) { 514 | if(System.nanoTime()-showProgressTime[0]<1000*1000000) { 515 | return null; 516 | } 517 | 518 | QueryResult res=new QueryResult(); 519 | for(int i=0;i1?"多实例":Current.IsStoreInMemory()?"InMemory":"InWkbsFile") 540 | +" "+arr[1]+"。按回车键结束测试..."); 541 | } 542 | return null; 543 | } 544 | } 545 | }; 546 | //获得一个线程执行函数 547 | Func> newThreadRun=new Func>() { 548 | @Override 549 | public Func Exec(Integer threadId) throws Exception { 550 | return new Func() { 551 | @Override 552 | public Object Exec(Object val) throws Exception { 553 | QueryResult res=new QueryResult();//这个只能单线程用 554 | Object[] args=new Object[] { res, CurrentIdx }; 555 | Random rnd=new Random(); 556 | long t1=System.nanoTime(); 557 | while(!stop[0]) { 558 | try { 559 | run.Exec(args); 560 | 561 | long t0=System.nanoTime(); 562 | if(t0-t1>=1000*1000000) {//1秒钟,给赋值一次统计数据 563 | SecondCompletes[threadId]=res; 564 | showProgress.Exec(null); 565 | args[0]=res=new QueryResult(); 566 | args[1]=idxs.get(rnd.nextInt(idxs.size())); 567 | t1=System.nanoTime(); 568 | } 569 | } catch(Exception e) { 570 | e.printStackTrace(); 571 | } 572 | } 573 | return null; 574 | } 575 | }; 576 | } 577 | }; 578 | //开启多线程 579 | int[] threadCount=new int[] { ThreadCount }; 580 | for(int i=0;i threadRun=newThreadRun.Exec(i); 582 | new Thread(new Runnable() { 583 | public void run() { 584 | try { 585 | threadRun.Exec(null); 586 | } catch(Exception e) { 587 | e.printStackTrace(); 588 | } finally { 589 | synchronized (threadCount) { threadCount[0]--; } 590 | } 591 | } 592 | }).start(); 593 | } 594 | 595 | ReadIn(); 596 | stop[0]=true; 597 | System.out.println("等待线程结束..."); 598 | while(threadCount[0]>0) { 599 | try { Thread.sleep(10); }catch (Exception e) { } 600 | } 601 | System.out.println("多线程性能测试已结束。"); 602 | System.out.println(); 603 | } 604 | 605 | 606 | 607 | static void Query_Point() throws Exception { 608 | String idxs=GetInitInstanceIdxs(); 609 | System.out.println("========== 查询一个坐标点对应的省市区乡镇数据 =========="); 610 | System.out.println("注意:输入坐标参数的坐标系必须和初始化时使用的geojson数据的坐标系一致,否则坐标可能会有比较大的偏移,导致查询结果不正确。"); 611 | System.out.println("请输入一个坐标点,格式:\"lng lat\"(允许有逗号):"); 612 | System.out.println(" - 比如:114.044346 22.691963,为广东省 深圳市 龙华区"); 613 | System.out.println(" - 比如:117.286491 30.450399,为安徽省 铜陵市 郊区,在池州市 贵池区的飞地"); 614 | System.out.println(" - 比如:121.993491 29.524288,为浙江省 宁波市 象山县,但坐标点位于海岸线外侧,不在任何边界内,需设置tolerance才能查出"); 615 | System.out.println(" - 输入 tolerance=2500 设置距离范围容差值,单位米,比如2500相当于一个以此坐标为中心点、半径为2.5km的圆形范围;默认0不设置,-1不限制距离;当坐标位于界线外侧(如海岸线、境界线)时QueryPoint方法将不会有边界图形能够匹配包含此坐标(就算距离只相差1cm),设置tolerance后,会查询出在这个范围内和此坐标点距离最近的边界数据"); 616 | System.out.println(" - 输入 exit 退出查询,输入 use "+idxs+" 切换查询实例"); 617 | int tolerance=0; 618 | while(true){ 619 | System.out.print((idxs.length()<2?"":"[实例"+CurrentIdx+"] ")+"> "); 620 | String inStr=ReadIn().trim(); 621 | if(inStr.length()==0) { 622 | System.out.println("输入为空,请重新输入!如需退出请输入exit"); 623 | continue; 624 | } 625 | if(inStr.equals("exit")) { 626 | System.out.println("bye! 已退出查询。"); 627 | System.out.println(); 628 | return; 629 | } 630 | if(inStr.startsWith("use ")) { 631 | if(InTxt_SetCurrent(inStr, true)) { 632 | System.out.println("已设置当前实例为"+CurrentIdx); 633 | } 634 | continue; 635 | } 636 | if(inStr.startsWith("tolerance")) { 637 | Matcher m=Pattern.compile("^tolerance[=\\s]+([+-]*\\d+)$").matcher(inStr); 638 | if(!m.find()) { 639 | System.out.println("tolerance设置格式错误,请重新输入"); 640 | }else { 641 | tolerance=Integer.parseInt(m.group(1)); 642 | System.out.println("已设置tolerance="+tolerance); 643 | } 644 | continue; 645 | } 646 | String[] arr=inStr.split("[,\\s]+"); 647 | double lng=-999,lat=-999; 648 | if(arr.length==2) { 649 | try { 650 | lng=Double.parseDouble(arr[0]); 651 | lat=Double.parseDouble(arr[1]); 652 | }catch(Exception e) { 653 | lng=lat=-999; 654 | } 655 | } 656 | if(lng<-180 || lat<-90 || lng>180 || lat>90) { 657 | System.out.println("输入的坐标格式不正确"); 658 | continue; 659 | } 660 | QueryResult res; 661 | if(tolerance==0) { 662 | res=Current.QueryPoint(lng, lat, null, null); 663 | }else { 664 | System.out.println("QueryPointWithTolerance tolerance="+tolerance); 665 | res=Current.QueryPointWithTolerance(lng, lat, null, null, tolerance); 666 | } 667 | System.out.println(res.toString()); 668 | } 669 | } 670 | 671 | static void Query_Geometry() throws Exception { 672 | String idxs=GetInitInstanceIdxs(); 673 | System.out.println("========== 查询和任意一个几何图形相交的省市区乡镇数据 =========="); 674 | System.out.println("注意:输入WKT的坐标系必须和初始化时使用的geojson数据的坐标系一致,否则坐标可能会有比较大的偏移,导致查询结果不正确。"); 675 | System.out.println("请输入一个WKT文本(Well Known Text):"); 676 | System.out.println(" - 比如:POINT(114.044346 22.691963),坐标点,为广东省 深圳市 龙华区"); 677 | System.out.println(" - 比如:LINESTRING(114.30115 30.57962, 117.254285 31.824198, 118.785633 32.064869),路径线段,武汉-合肥-南京 三个点连成的线段"); 678 | System.out.println(" - 比如:POLYGON((113.305514 30.564249, 113.305514 32.881526, 117.326510 32.881526, 117.326510 30.564249, 113.305514 30.564249)),范围,湖北-河南-安徽 三省交界的一个超大矩形范围"); 679 | System.out.println(" - 输入 exit 退出查询,输入 use "+idxs+" 切换查询实例"); 680 | while(true){ 681 | System.out.print((idxs.length()<2?"":"[实例"+CurrentIdx+"] ")+"> "); 682 | String inStr=ReadIn().trim(); 683 | if(inStr.length()==0) { 684 | System.out.println("输入为空,请重新输入!如需退出请输入exit"); 685 | continue; 686 | } 687 | if(inStr.equals("exit")) { 688 | System.out.println("bye! 已退出查询。"); 689 | System.out.println(); 690 | return; 691 | } 692 | if(inStr.startsWith("use ")) { 693 | if(InTxt_SetCurrent(inStr, true)) { 694 | System.out.println("已设置当前实例为"+CurrentIdx); 695 | } 696 | continue; 697 | } 698 | Geometry geom; 699 | try { 700 | geom=new WKTReader(AreaCityQuery.Factory).read(inStr); 701 | }catch(Exception e) { 702 | System.out.println("输入的WKT解析失败:"+e.getMessage()); 703 | continue; 704 | } 705 | QueryResult res=Current.QueryGeometry(geom, null, null); 706 | System.out.println(res.toString()); 707 | } 708 | } 709 | 710 | static void Read_WKT() throws Exception { 711 | System.out.println("========== 读取省市区乡镇边界的WKT文本数据 =========="); 712 | System.out.println("遍历所有边界图形的属性列表查询出符合条件的属性,然后返回图形的属性+边界图形WKT文本。 "); 713 | System.out.println("读取到的wkt文本,可以直接粘贴到页面内渲染显示:https://xiangyuecn.github.io/AreaCity-JsSpider-StatsGov/assets/geo-echarts.html"); 714 | System.out.println(); 715 | 716 | ExtPathExpIn("ReadWKT", new Func() { 717 | @Override 718 | public Object Exec(ExtPathExpInArgs args) throws Exception { 719 | int[] count=new int[] { 0 }; 720 | Current.ReadWKT_FromWkbsFile("", null, new Func() { 721 | @Override 722 | public Boolean Exec(String prop) throws Exception { 723 | return ExtPathMatch(prop, args.extPath_exp); 724 | } 725 | }, getWktReadFn("ReadWKT", args, count)); 726 | if(count[0] == 0) { 727 | System.out.println("未找到“"+args.extPath_inputTxt+"”匹配的属性!"); 728 | } else { 729 | System.out.println("查找完成,共"+count[0]+"条"); 730 | } 731 | return null; 732 | } 733 | }); 734 | } 735 | 736 | static void Query_DebugReadWKT() throws Exception { 737 | System.out.println("========== Debug: 读取边界网格划分图形WKT文本数据 =========="); 738 | System.out.println("调试用的,读取已在wkbs结构化文件中保存的网格划分图形WKT数据,用于核对网格划分情况。"); 739 | System.out.println("读取到的wkt文本,可以直接粘贴到页面内渲染显示:https://xiangyuecn.github.io/AreaCity-JsSpider-StatsGov/assets/geo-echarts.html"); 740 | System.out.println(); 741 | 742 | ExtPathExpIn("GirdWKT", new Func() { 743 | @Override 744 | public Object Exec(ExtPathExpInArgs args) throws Exception { 745 | int[] count=new int[] { 0 }; 746 | Current.Debug_ReadGeometryGridSplitsWKT("", null, new Func() { 747 | @Override 748 | public Boolean Exec(String prop) throws Exception { 749 | return ExtPathMatch(prop, args.extPath_exp); 750 | } 751 | }, getWktReadFn("GirdWKT", args, count)); 752 | if(count[0] == 0) { 753 | System.out.println("未找到“"+args.extPath_inputTxt+"”匹配的边界!"); 754 | } else { 755 | System.out.println("查找完成,共"+count[0]+"条"); 756 | } 757 | return null; 758 | } 759 | }); 760 | } 761 | 762 | 763 | static Func getWktReadFn(String tag, ExtPathExpInArgs args, int[] count){ 764 | return new Func() { 765 | @Override 766 | public Boolean Exec(String[] val) throws Exception { 767 | count[0]++; 768 | if(args.outFile!=null) { 769 | String str=val[0] +"\t"+ val[1]+"\n"; 770 | byte[] bytes=str.getBytes("utf-8"); 771 | args.outFile.write(bytes); 772 | 773 | System.out.println(count[0]+"条"+tag+"属性:"+val[0]); 774 | System.out.println(" "+bytes.length+"字节已保存到文件:"+args.outFilePath); 775 | } else { 776 | String str=count[0]+"条"+tag+"属性:"+val[0]; 777 | if(val[1].length()>500) { 778 | System.out.println(str); 779 | str=" WKT超长未显示("+val[1].length()+"字节),请命令后面输入\" > 文件名\"输出到文件"; 780 | } else { 781 | str=str +"\t"+ val[1]; 782 | } 783 | System.out.println(str); 784 | } 785 | return false; 786 | } 787 | }; 788 | } 789 | static boolean ExtPathMatch(String prop, String exp) { 790 | int i0=prop.indexOf("ext_path"); 791 | if(i0==-1)return false; 792 | int i1=prop.indexOf(",", i0); 793 | if(i1==-1)i1=prop.length(); 794 | return prop.substring(i0+9, i1).contains(exp); 795 | } 796 | static class ExtPathExpInArgs{ 797 | String extPath_exp; 798 | String extPath_inputTxt; 799 | String outFilePath; 800 | FileOutputStream outFile; 801 | } 802 | static void ExtPathExpIn(String tag, Func fn) throws Exception { 803 | String idxs=GetInitInstanceIdxs(); 804 | System.out.println("请输入"+tag+"要查询的城市完整名称,为ext_path值:"); 805 | System.out.println(" - 如:“湖北省 武汉市 洪山区”,精确查找"); 806 | System.out.println(" - 如:“*武汉市*”,*通配符模糊查找"); 807 | System.out.println(" - 如:“*”,查找全部"); 808 | System.out.println(" - 结尾输入“ > 文件名”可保存到文件"); 809 | System.out.println(" - 输入 exit 退出,输入 use "+idxs+" 切换查询实例"); 810 | while(true){ 811 | System.out.print((idxs.length()<2?"":"[实例"+CurrentIdx+"] ")+"> "); 812 | String inStr=ReadIn().trim(); 813 | if(inStr.length()==0) { 814 | System.out.println("输入为空,请重新输入!如需退出请输入exit"); 815 | continue; 816 | } 817 | if(inStr.equals("exit")) { 818 | System.out.println("bye! 已退出读取。"); 819 | System.out.println(); 820 | return; 821 | } 822 | if(inStr.startsWith("use ")) { 823 | if(InTxt_SetCurrent(inStr, true)) { 824 | System.out.println("已设置当前实例为"+CurrentIdx); 825 | } 826 | continue; 827 | } 828 | ExtPathExpInArgs args=new ExtPathExpInArgs(); 829 | String[] ins=inStr.split(" > "); 830 | args.extPath_inputTxt=ins[0]; 831 | 832 | String outFilePath= ins.length>1?ins[1]:""; 833 | FileOutputStream outFile=null; 834 | if(outFilePath.length()>0) { 835 | outFilePath=new File(outFilePath).getAbsolutePath(); 836 | outFile=new FileOutputStream(outFilePath); 837 | } 838 | args.outFilePath=outFilePath; 839 | args.outFile=outFile; 840 | 841 | 842 | String exp=ins[0]; 843 | if(exp.equals("*")) { 844 | exp=""; 845 | } else { 846 | if(exp.startsWith("*")) { 847 | exp=exp.substring(1); 848 | }else { 849 | exp="\""+exp; 850 | } 851 | if(exp.endsWith("*")) { 852 | exp=exp.substring(0, exp.length()-1); 853 | }else { 854 | exp=exp+"\""; 855 | } 856 | } 857 | args.extPath_exp=exp; 858 | 859 | fn.Exec(args); 860 | 861 | if(outFile!=null)outFile.close(); 862 | } 863 | } 864 | 865 | 866 | 867 | 868 | 869 | 870 | 871 | static public boolean StartHttpApiServer(int port) throws Exception { 872 | String clazzName=Test.class.getPackage().getName()+".Test_HttpApiServer"; 873 | Method[] fns; 874 | try { 875 | fns=Class.forName(clazzName).getMethods(); 876 | }catch (Exception e) { 877 | System.out.println("Test_HttpApiServer.java加载失败,不支持启动本地轻量HTTP API服务。"); 878 | return false; 879 | } 880 | Method fn=null; for(Method x : fns) if(x.getName().equals("Create")) fn=x; 881 | return (boolean)fn.invoke(null, "0.0.0.0", port); 882 | } 883 | 884 | 885 | 886 | 887 | 888 | 889 | 890 | static public String ReadIn() throws Exception { 891 | ByteArrayOutputStream in=new ByteArrayOutputStream(); 892 | while(true) { 893 | int byt=System.in.read(); 894 | if(byt=='\r') continue; 895 | if(byt=='\n') { 896 | break; 897 | } 898 | if(in.size()>=2048) {//防止内存溢出,某些环境下可能会有无限的输入 899 | byte[] bytes=in.toByteArray(); 900 | in=new ByteArrayOutputStream(); 901 | in.write(bytes, bytes.length-1024, 1024); 902 | } 903 | in.write(byt); 904 | } 905 | return in.toString(); 906 | } 907 | static public boolean InTxt_SetCurrent(String inTxt, boolean checkInit) { 908 | int idx=-1; try{ idx=Integer.parseInt(inTxt.split("\\s+")[1]); }catch(Exception e) {} 909 | if(idx<0 || idx>=AreaCityQuery.Instances.length) { 910 | System.out.println("use实例序号无效,请重新输入!"); 911 | return false; 912 | } 913 | AreaCityQuery val=AreaCityQuery.Instances[idx]; 914 | if(checkInit && val.GetInitStatus()!=2) { 915 | System.out.println("实例"+idx+"未初始化,可用实例["+GetInitInstanceIdxs()+"],请重新输入!"); 916 | return false; 917 | } 918 | CurrentIdx=idx; 919 | Current=val; 920 | return true; 921 | } 922 | static public String GetInitInstanceIdxs() { 923 | String initIdxs=""; 924 | for(int i=0;i0?",":"")+i; 928 | } 929 | } 930 | return initIdxs; 931 | } 932 | static boolean IsCmd=false; 933 | static String HR="-----------------------------------"; 934 | static void Start(String[] args) throws Exception { 935 | if(args.length>0) { 936 | System.out.print(args.length+"个启动参数"); 937 | for(int i=0;i idxs=new ArrayList<>(); 950 | int curIdx=0; String initIdxs=""; 951 | for(int i=0;i0?",":"")+i; 956 | } 957 | if(item==Current)curIdx=i; 958 | } 959 | 960 | 961 | System.out.println("【功能菜单】 当前静态实例Instances["+curIdx+"]"); 962 | System.out.println("1. "+(isInit?"重新":"")+"初始化:调用 Init_StoreInWkbsFile -内存占用很低(性能受IO限制)"+(Current.IsStoreInWkbsFile()?" [已初始化]":"")); 963 | System.out.println("2. "+(isInit?"重新":"")+"初始化:调用 Init_StoreInMemory -内存占用和json文件差不多大(性能豪放)"+(Current.IsStoreInMemory()?" [已初始化]":"")); 964 | if(isInit) { 965 | System.out.println(HR); 966 | System.out.println("3. 测试:基础功能测试"); 967 | System.out.println("4. 测试:1万个伪随机点测试"); 968 | System.out.println("5. 测试:多线程性能测试"); 969 | System.out.println(HR); 970 | System.out.println("6. 查询: QueryPoint 查找坐标点所在省市区乡镇"); 971 | System.out.println("A. 查询: QueryGeometry 查找和图形相交的省市区乡镇"); 972 | System.out.println("7. 查询: ReadWKT 读取省市区乡镇边界的WKT文本数据"); 973 | System.out.println("8. 查询: Debug 读取边界网格划分图形WKT文本数据"); 974 | System.out.println(HR); 975 | System.out.println("9. HTTP: 启动本地轻量HTTP API服务"); 976 | } 977 | System.out.println(HR); 978 | System.out.println("*. 输入 use 0-"+(AreaCityQuery.Instances.length-1)+" 切换静态实例,list 列出实例信息,当前"+(initIdxs.length()==0?"无已初始化实例":"["+initIdxs+"]已初始化")+""); 979 | System.out.println("*. 输入 exit 退出"); 980 | System.out.println(); 981 | System.out.println("请输入菜单序号:"); 982 | System.out.print("> "); 983 | 984 | boolean waitAnyKey=true; 985 | String inTxt=""; 986 | while(true) { 987 | int byt=System.in.read(); 988 | inTxt+=(char)byt; 989 | 990 | if(byt!='\n') { 991 | continue; 992 | } 993 | inTxt=inTxt.trim().toUpperCase(); 994 | try { 995 | if(inTxt.equals("1") || inTxt.equals("2")) { 996 | Current.ResetInitStatus(); 997 | System.gc(); 998 | 999 | Init_FromMenu(inTxt.equals("1")); 1000 | if(Current.GetInitStatus()==2) { 1001 | waitAnyKey=false; 1002 | } 1003 | } else if(isInit && inTxt.equals("3")) { 1004 | for(int i : idxs) { 1005 | if(idxs.size()>1) System.out.println("【测试实例"+i+"】 Instances["+i+"]"); 1006 | BaseTest(i); 1007 | } 1008 | } else if(isInit && inTxt.equals("4")) { 1009 | for(int i : idxs) { 1010 | if(idxs.size()>1) System.out.println("【测试实例"+i+"】 Instances["+i+"]"); 1011 | LargeRndPointTest(i); 1012 | } 1013 | } else if(isInit && inTxt.equals("5")) { 1014 | ThreadRun(idxs); 1015 | waitAnyKey=false; 1016 | } else if(isInit && inTxt.equals("6")) { 1017 | Query_Point(); 1018 | waitAnyKey=false; 1019 | } else if(isInit && inTxt.equals("A")) { 1020 | Query_Geometry(); 1021 | waitAnyKey=false; 1022 | } else if(isInit && inTxt.equals("7")) { 1023 | Read_WKT(); 1024 | waitAnyKey=false; 1025 | } else if(isInit && inTxt.equals("8")) { 1026 | Query_DebugReadWKT(); 1027 | waitAnyKey=false; 1028 | } else if(isInit && inTxt.equals("9")) { 1029 | if(StartHttpApiServer(HttpApiServerPort)) { 1030 | waitAnyKey=false; 1031 | } 1032 | } else if(inTxt.startsWith("USE ")) { 1033 | if(InTxt_SetCurrent(inTxt, false)) { 1034 | waitAnyKey=false; 1035 | }else { 1036 | inTxt=""; 1037 | System.out.print("> "); 1038 | continue; 1039 | } 1040 | } else if(inTxt.equals("LIST")) { 1041 | for(int i : idxs) { 1042 | AreaCityQuery item=AreaCityQuery.Instances[i]; 1043 | QueryInitInfo info=item.GetInitInfo(); 1044 | System.out.println((item==Current?"[当前]":"") 1045 | +"实例"+i+": Instances["+i+"] "+(item.IsStoreInMemory()?"Init_StoreInMemory":"Init_StoreInWkbsFile")); 1046 | System.out.println(" Geometry "+info.GeometryCount+" 个(Grid切分Polygon "+info.PolygonCount+" 个)"); 1047 | System.out.println(" Data文件: "+info.FilePath_Data); 1048 | System.out.println(" Wkbs文件: "+info.FilePath_SaveWkbs); 1049 | } 1050 | if(idxs.size()==0) { 1051 | System.out.println("没有已初始化的实例信息!"); 1052 | } 1053 | } else if(inTxt.equals("EXIT")) { 1054 | System.out.println("bye!"); 1055 | return; 1056 | } else { 1057 | inTxt=""; 1058 | System.out.println("序号无效,请重新输入菜单序号!"); 1059 | System.out.print("> "); 1060 | continue; 1061 | } 1062 | } catch(Exception e) { 1063 | e.printStackTrace(); 1064 | } 1065 | break; 1066 | } 1067 | 1068 | if(waitAnyKey) { 1069 | System.out.println("按任意键继续..."); 1070 | int n=System.in.read(); 1071 | if(n=='\r') { 1072 | System.in.read(); 1073 | } 1074 | } 1075 | } 1076 | } 1077 | } 1078 | -------------------------------------------------------------------------------- /AreaCityQuery.java: -------------------------------------------------------------------------------- 1 | package com.github.xiangyuecn.areacity.query; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.File; 6 | import java.io.FileInputStream; 7 | import java.io.FileOutputStream; 8 | import java.io.InputStreamReader; 9 | import java.io.PrintWriter; 10 | import java.io.StringWriter; 11 | import java.lang.management.ManagementFactory; 12 | import java.lang.management.OperatingSystemMXBean; 13 | import java.lang.reflect.Method; 14 | import java.math.BigDecimal; 15 | import java.math.RoundingMode; 16 | import java.text.DecimalFormat; 17 | import java.text.SimpleDateFormat; 18 | import java.util.ArrayList; 19 | import java.util.Date; 20 | import java.util.HashMap; 21 | import java.util.HashSet; 22 | import java.util.List; 23 | import java.util.Map; 24 | import java.util.regex.Matcher; 25 | import java.util.regex.Pattern; 26 | 27 | import org.locationtech.jts.geom.Coordinate; 28 | import org.locationtech.jts.geom.Envelope; 29 | import org.locationtech.jts.geom.Geometry; 30 | import org.locationtech.jts.geom.GeometryFactory; 31 | import org.locationtech.jts.geom.LinearRing; 32 | import org.locationtech.jts.geom.MultiPolygon; 33 | import org.locationtech.jts.geom.Point; 34 | import org.locationtech.jts.geom.Polygon; 35 | import org.locationtech.jts.geom.PrecisionModel; 36 | import org.locationtech.jts.index.strtree.STRtree; 37 | import org.locationtech.jts.io.WKBReader; 38 | import org.locationtech.jts.io.WKBWriter; 39 | import org.locationtech.jts.io.WKTWriter; 40 | import org.locationtech.jts.operation.distance.DistanceOp; 41 | 42 | /** 43 | * 使用jts库从省市区县乡镇边界数据(AreaCity-JsSpider-StatsGov开源库)或geojson文件中查找出和任意点、线、面有相交的边界,内存占用低,性能优良。 44 | *
  45 |  * 可用于:
  46 |  *     - 调用 QueryPoint(lng, lat) 查询一个坐标点对应的省市区名称等信息;
  47 |  *     - 调用 ReadWKT_FromWkbsFile(where) 查询获取需要的省市区边界WKT文本数据。
  48 |  * 
  49 |  * 部分原理:
  50 |  *      1. 初始化时,会将边界图形按网格动态的切分成小的图形,大幅减少查询时的几何计算量从而性能优异;
  51 |  *      2. 内存中只会保存小的图形的外接矩形(Envelope),小的图形本身会序列化成WKB数据(根据Init方式存入文件或内存),因此内存占用很低;
  52 |  *      3. 内存中的外接矩形(Envelope)数据会使用jts的STRTree索引,几何计算查询时,先从EnvelopeSTRTree中初步筛选出符合条件的边界,RTree性能极佳,大幅过滤掉不相关的边界;
  53 |  *      4. 对EnvelopeSTRTree初步筛选出来的边界,读取出WKB数据反序列化成小的图形,然后进行精确的几何计算(因为是小图,所以读取和计算性能极高)。
  54 |  * 
  55 |  * jts库地址:https://github.com/locationtech/jts
  56 |  * 
57 | * 58 | *
GitHub: https://github.com/xiangyuecn/AreaCity-Query-Geometry (github可换成gitee) 59 | *
省市区县乡镇区划边界数据: https://github.com/xiangyuecn/AreaCity-JsSpider-StatsGov (github可换成gitee) 60 | */ 61 | public class AreaCityQuery { 62 | /** 默认提供的0-9的10个静态实例,每个实例可以分别使用一个数据文件进行初始化和查询,当然自己调用new AreaCityQuery()创建一个新实例使用也是一样的 */ 63 | static public final AreaCityQuery[] Instances=new AreaCityQuery[] { 64 | new AreaCityQuery(),new AreaCityQuery(),new AreaCityQuery(),new AreaCityQuery(),new AreaCityQuery() 65 | ,new AreaCityQuery(),new AreaCityQuery(),new AreaCityQuery(),new AreaCityQuery(),new AreaCityQuery() 66 | }; 67 | 68 | /** 69 | * 几何计算查询出包含此坐标点的所有边界图形的属性数据(和此坐标点相交): 70 | *
  71 | 	 * - 如果坐标点位于图形内部或边上,这个图形将匹配;
  72 | 	 * - 如果坐标点位于两个图形的边上,这两个图形将都会匹配;
  73 | 	 * - 如果图形存在孔洞,并且坐标点位于孔洞内(不含边界),这个图形将不匹配。
  74 | 	 * 
75 | * 76 | *
输入坐标参数的坐标系必须和初始化时使用的geojson数据的坐标系一致,否则坐标可能会有比较大的偏移,导致查询结果不正确。 77 | *
如果还未完成初始化,或者查询出错,都会抛异常。 78 | *
本方法线程安全。 79 | * 80 | *

注意:如果此坐标位于界线外侧(如海岸线、境界线)时将不会有边界图形能够匹配包含(就算距离只相差1cm),此时如果你希望能匹配到附近不远的边界图形,请使用QueryPointWithTolerance方法 81 | * 82 | * @param lng 进度坐标值 83 | * @param lat 纬度坐标值 84 | * @param where 可以为null,可选提供一个函数,筛选属性数据(此数据已经过初步筛选),会传入属性的json字符串,如果需要去精确计算这个边界图形是否匹配就返回true,否则返回false跳过这条边界图形的精确计算 85 | * @param res 可以为null,如果提供结果对象,可通过此对象的Set_XXX属性控制某些查询行为,比如设置Set_ReturnWKTKey可以额外返回边界的WKT文本数据;并且本次查询的结果和统计数据将累加到这个结果内(性能测试用)。注意:此结果对象非线程安全 86 | */ 87 | public QueryResult QueryPoint(double lng, double lat, Func where, QueryResult res) throws Exception{ 88 | CheckInitIsOK(); 89 | return QueryGeometry(Factory.createPoint(new Coordinate(lng, lat)), where, res); 90 | } 91 | /** 92 | * 先几何计算查询出包含此坐标点的所有边界图形的属性数据,此时和QueryPoint方法功能完全一致。 93 | *

当没有边界图形包含此坐标点时,会查询出和此坐标点距离最近的边界图形的属性数据,同一级别的边界图形只会返回距离最近的一条属性数据,比如:范围内匹配到多个市,只返回最近的一个市;级别的划分依据为属性中的deep值,deep值为空的为同的一级 94 | * ;结果属性中会额外添加PointDistance(图形与坐标的距离,单位米)、PointDistanceID(图形唯一标识符)两个值;由于多进行了一次范围查询,性能会比QueryPoint方法低些。 95 | *

本方法主要用途是解决:当坐标位于界线外侧(如海岸线、境界线)时QueryPoint方法将不会有边界图形能够匹配包含此坐标(就算距离只相差1cm),本方法将能够匹配到附近不远的边界图形数据。 96 | * 97 | *

更多参数文档请参考QueryPoint方法,本方法线程安全。 98 | * 99 | * @see #QueryPoint(double, double, Func, QueryResult) 100 | * @param toleranceMetre 距离范围容差值,单位米,比如取值2500,相当于一个以此坐标为中心点、半径为2.5km的圆形范围;当没有任何边界图形包含此坐标点时,会查询出与此坐标点的距离不超过此值 且 距离最近的边界图形属性数据;取值为0时不进行范围查找;取值为-1时不限制距离大小,会遍历所有数据导致性能极低 101 | */ 102 | public QueryResult QueryPointWithTolerance(double lng, double lat, Func where, QueryResult res, int toleranceMetre) throws Exception { 103 | CheckInitIsOK(); 104 | if(res!=null && res.Result==null) throw new Exception("不支持无Result调用"); 105 | 106 | int resLen0=res==null?0:res.Result.size(); 107 | Point point=Factory.createPoint(new Coordinate(lng, lat)); 108 | QueryResult res1=QueryGeometry(point, where, res); 109 | if(res1.Result.size()>resLen0 || toleranceMetre==0) { 110 | return res1; //查找到了的就直接返回 111 | } 112 | 113 | Geometry geom; 114 | if(toleranceMetre>0) { //以点为中心,容差为半径,构造出一个圆,扩大到容差范围进行查找 115 | geom=CreateSimpleCircle(lng, lat, toleranceMetre, 24); 116 | } else { //不限制范围 117 | geom=CreateRect(-180, -90, 180, 90); 118 | } 119 | HashMap propDists=new HashMap<>(); 120 | HashMap deepDists=new HashMap<>(); 121 | DecimalFormat df=new DecimalFormat("0.00"); 122 | res1.QueryCount--; 123 | res1=QueryGeometryProcess(geom, where, res1, new Func(){ 124 | @Override 125 | public Boolean Exec(Object[] args) throws Exception { 126 | boolean add=false; 127 | String prop=(String)args[0]; 128 | Geometry geom=(Geometry)args[1]; 129 | String lineNo=(String)args[2]; 130 | 131 | Coordinate[] ps=DistanceOp.nearestPoints(geom, point); 132 | double dist=Distance(ps[0].x, ps[0].y, ps[1].x, ps[1].y); 133 | Double exists=propDists.get(lineNo); 134 | if(exists==null || exists>dist) {//去重,相同一条数据只取距离最近的 135 | Matcher m=Exp_OkGeoCsv_Deep.matcher(prop); 136 | String deep=m.find()?m.group(1):""; 137 | Object[] deepExists=deepDists.get(deep); 138 | if(deepExists==null || (double)deepExists[0]>dist) {//去重,同一级别只取距离最近的 139 | add=true; 140 | propDists.put(lineNo, dist); 141 | deepDists.put(deep, new Object[] { dist, lineNo }); 142 | prop=prop.substring(0, prop.length()-1)+", \"PointDistanceID\": "+lineNo+", \"PointDistance\": "+df.format(dist)+"}"; 143 | args[0]=prop; 144 | } 145 | } 146 | return add; 147 | } 148 | }); 149 | //清理掉结果中多余的数据,每一级取一个,同一数据取最后一个 150 | HashSet ids=new HashSet<>(), exists=new HashSet<>(); 151 | for(Object[] o : deepDists.values()) ids.add((String)o[1]); 152 | for(int i=res1.Result.size()-1;i>=resLen0;i--) { 153 | String prop=res1.Result.get(i); 154 | Matcher m=Exp_PointDistanceID.matcher(prop); m.find(); 155 | String lineNo=m.group(1); 156 | if(!ids.contains(lineNo) || exists.contains(lineNo)) { 157 | res1.Result.remove(i); 158 | }else { 159 | exists.add(lineNo); 160 | } 161 | } 162 | return res1; 163 | } 164 | static private Pattern Exp_PointDistanceID=Pattern.compile("\"PointDistanceID[\\s\":]+(\\d+)"); 165 | static private Pattern Exp_OkGeoCsv_Deep=Pattern.compile("\"deep[\\s\":]+(\\d+)"); 166 | 167 | 168 | /** 169 | * 几何计算查询出和此图形(点、线、面)有交点的所有边界图形的属性数据(包括边界相交)。 170 | *
171 | *
所有输入坐标参数的坐标系必须和初始化时使用的geojson数据的坐标系一致,否则坐标可能会有比较大的偏移,导致查询结果不正确。 172 | *
如果还未完成初始化,或者查询出错,都会抛异常。 173 | *
本方法线程安全。 174 | * 175 | * @param geom 任意格式的图形对象(点、线、面),可以通过wkt文本进行构造:geom=new WKTReader(AreaCityQuery.Factory).read("wkt字符串") 176 | * @param where 可以为null,可选提供一个函数,筛选属性数据(此数据已经过初步筛选),会传入属性的json字符串,如果需要去精确计算这个边界图形是否匹配就返回true,否则返回false跳过这条边界图形的精确计算 177 | * @param res 可以为null,如果提供结果对象,可通过此对象的Set_XXX属性控制某些查询行为,比如设置Set_ReturnWKTKey可以额外返回边界的WKT文本数据;并且本次查询的结果和统计数据将累加到这个结果内(性能测试用)。注意:此结果对象非线程安全 178 | */ 179 | public QueryResult QueryGeometry(Geometry geom, Func where, QueryResult res) throws Exception{ 180 | return QueryGeometryProcess(geom, where, res, null); 181 | } 182 | /** 183 | * 几何计算查询出和此图形(点、线、面)有交点的所有边界图形的属性数据(包括边界相交)。 184 | *
185 | *
参数功能和QueryGeometry方法一致,多了一个process参数允许在匹配计算时进行自定义计算处理 186 | *
更多参数文档请参考QueryGeometry方法,本方法线程安全。 187 | * 188 | * @see #QueryGeometry(Geometry, Func, QueryResult) 189 | * @param process 当一条数据经过精确匹配后,加入到结果中前,会调用此函数进行自定义计算,返回true继续加入到结果中,返回false丢弃这条数据;提供本函数后的查询性能会比不提供时低些,因为未去重增加了重复计算量。 190 | *

注意:初始化时一个完整边界图形会在网格划分后产生多个小图形,匹配的每个小图形都会算作一条数据参与自定义计算,会导致结果数据重复,因此需要自行对结果数据进行去重 191 | *

参数为一个数组: 192 | *
[0]String:可读写,当前数据属性的json字符串,修改后的json内容会放到结果中 193 | *
[1]Geometry:当前数据的图形对象,用于计算,为网格划分后的小图形 194 | *
[2]String:为当前数据对应的完整图形的唯一标识符,用于数据去重 195 | */ 196 | public QueryResult QueryGeometryProcess(Geometry geom, Func where, QueryResult res, Func process) throws Exception{ 197 | CheckInitIsOK(); 198 | if(res==null) res=new QueryResult(); 199 | res.QueryCount++; 200 | long t_Start=System.nanoTime(); 201 | if(res.StartTimeN==0) res.StartTimeN=t_Start; 202 | 203 | boolean returnWkt=res.Set_ReturnWKTKey!=null && res.Set_ReturnWKTKey.length()>0; 204 | if(returnWkt && WkbsFilePath.length()==0) { 205 | throw new Exception("Set_ReturnWKT错误,初始化时必须保存了wkbs结构化数据文件,或者用的wkbs文件初始化的,否则不允许查询WKT数据"); 206 | } 207 | 208 | //先查找Envelope,基本不消耗时间 209 | @SuppressWarnings("rawtypes") 210 | List list=EnvelopeSTRTree.query(geom.getEnvelopeInternal()); 211 | res.DurationN_EnvelopeHitQuery+=System.nanoTime()-t_Start; 212 | res.EnvelopeHitCount+=list.size(); 213 | 214 | //进行精确查找 215 | String matchLines=","; 216 | for(int i=0,len=list.size();i store=(Map)list.get(i); 219 | 220 | byte[] wkbSub=null; 221 | String[] wkbPos=getWkbPos(store); 222 | String lineNo=wkbPos[0]; 223 | int fullPos=Integer.parseInt(wkbPos[1]); 224 | int subPos=Integer.parseInt(wkbPos[2]); 225 | 226 | //如果wkb对应的这条数据已经有一个sub匹配了,就不需要在继续查询 227 | if(process==null && matchLines.indexOf(","+lineNo+",")!=-1) {//提供了process自定义处理,不去重 228 | continue; 229 | } 230 | 231 | //提供了where筛选 232 | if(where!=null) { 233 | if(!where.Exec(getProp(store))) { 234 | continue; 235 | } 236 | } 237 | 238 | //读取wkb数据 239 | long t_IO=System.nanoTime(); 240 | Geometry subGeom=null; 241 | if(ReadFromMemory) { 242 | //从内存中得到wkb数据 或 直接存的对象 243 | if(SetInitStoreInMemoryUseObject) { 244 | subGeom=(Geometry)store.get("wkb"); 245 | } else { 246 | wkbSub=(byte[])store.get("wkb"); 247 | } 248 | } else { 249 | wkbSub=ReadWkbFromFile(subPos); 250 | } 251 | res.DurationN_IO+=System.nanoTime()-t_IO; 252 | 253 | //转换回图形 254 | long t_GeometryParse=System.nanoTime(); 255 | if(subGeom==null) { 256 | subGeom=new WKBReader(Factory).read(wkbSub); 257 | } 258 | res.DurationN_GeometryParse+=System.nanoTime()-t_GeometryParse; 259 | 260 | //是否精确匹配 261 | long t_Exact=System.nanoTime(); 262 | boolean isMatch=subGeom.intersects(geom); 263 | res.DurationN_ExactHitQuery+=System.nanoTime()-t_Exact; 264 | if(isMatch) { 265 | String prop=getProp(store); 266 | if(process!=null) { // 自定义计算 267 | t_Exact=System.nanoTime(); 268 | Object[] args=new Object[] { prop, subGeom, lineNo }; 269 | if(!process.Exec(args)) { 270 | isMatch=false; 271 | } else { 272 | prop=(String)args[0]; 273 | } 274 | res.DurationN_ExactHitQuery+=System.nanoTime()-t_Exact; 275 | } 276 | 277 | if(isMatch) { 278 | if(returnWkt) { // 需要同时返回完整图形的wkt数据 279 | t_IO=System.nanoTime(); 280 | byte[] wkbFull=ReadWkbFromFile(fullPos); 281 | res.DurationN_IO+=System.nanoTime()-t_IO; 282 | 283 | t_GeometryParse=System.nanoTime(); 284 | Geometry fullGeom=new WKBReader(Factory).read(wkbFull); 285 | res.DurationN_GeometryParse+=System.nanoTime()-t_GeometryParse; 286 | 287 | String wkt=new WKTWriter().write(fullGeom); 288 | prop=prop.substring(0, prop.length()-1)+", \""+res.Set_ReturnWKTKey+"\": \""+wkt+"\"}"; 289 | } 290 | 291 | if(res.Result!=null) { 292 | res.Result.add(prop); 293 | } 294 | res.ExactHitCount++; 295 | 296 | matchLines+=lineNo+","; 297 | } 298 | } 299 | 300 | if(res.Set_EnvelopeHitResult!=null) {//将初步筛选的结果存入数组,如果要求了的话 301 | String prop=getProp(store); 302 | prop="{\"_PolygonPointNum_\": "+subGeom.getNumPoints()+","+prop.substring(1); 303 | res.Set_EnvelopeHitResult.add(prop); 304 | } 305 | } 306 | 307 | res.EndTimeN=System.nanoTime(); 308 | return res; 309 | } 310 | 311 | 312 | 313 | /** 314 | * 遍历所有边界图形的属性列表查询出符合条件的属性,然后返回图形的属性+边界图形WKT文本。 315 | *
读取到的wkt文本,可以直接粘贴到页面内渲染显示:https://xiangyuecn.github.io/AreaCity-JsSpider-StatsGov/assets/geo-echarts.html 316 | *
本方法可以用来遍历所有数据,提取感兴趣的属性内容(wktKey传null只返回属性),比如查询一个区划编号id对应的城市信息(城市名称、中心点) 317 | * 318 | *
319 | *
注意:初始化时必须保存了wkbs结构化数据文件,或者用的wkbs文件初始化的,否则不允许查询WKT数据。 320 | *
如果还未完成初始化,或者查询出错,都会抛异常。 321 | *
本方法线程安全。 322 | * 323 | * @param wktKey 可以为null,比如填:wkt、polygon,作为json里的key: 存放wkt文本数据;如果传入空值,将只返回属性,不查询wkt文本数据;此参数会覆盖res.Set_ReturnWKTKey值 324 | * @param res 可以为null,如果提供结果对象,可通过此对象的Set_XXX属性控制某些查询行为,并且本次查询的结果和统计数据将累加到这个结果内(性能测试用)。注意:此结果对象非线程安全 325 | * @param where 必须提供一个函数,筛选属性数据(所有数据全过一遍),会传入属性的json字符串,如果需要匹配这个边界图形就返回true,否则返回false跳过这条边界图形 326 | * @param onFind 可选提供一个回调函数,每次查询到一条wkt数据后会通过onFind回传,String[]参数为[prop,wkt];如果返回false数据将不会存入res结果中(也会忽略wktKey参数),需在回调中自行处理数据 327 | */ 328 | public QueryResult ReadWKT_FromWkbsFile(String wktKey, QueryResult res, Func where, Func onFind) throws Exception{ 329 | CheckInitIsOK(); 330 | if(res==null) res=new QueryResult(); 331 | res.QueryCount++; 332 | long t_Start=System.nanoTime(); 333 | if(res.StartTimeN==0) res.StartTimeN=t_Start; 334 | 335 | res.Set_ReturnWKTKey=wktKey; 336 | boolean returnWkt=res.Set_ReturnWKTKey!=null && res.Set_ReturnWKTKey.length()>0; 337 | boolean readWkt=returnWkt; 338 | if(onFind!=null) { 339 | readWkt=true; 340 | } 341 | if(readWkt && WkbsFilePath.length()==0) { 342 | throw new Exception("初始化时必须保存了wkbs结构化数据文件,或者用的wkbs文件初始化的,否则不允许查询WKT数据"); 343 | } 344 | 345 | for(int i=0,iL=WKTDataStores.size();i store=WKTDataStores.get(i); 347 | 348 | //属性是否符合条件 349 | long t_Exact=System.nanoTime(); 350 | String prop=getProp(store); 351 | boolean isFind=where.Exec(prop); 352 | res.DurationN_ExactHitQuery+=System.nanoTime()-t_Exact; 353 | if(!isFind) { 354 | continue; 355 | } 356 | 357 | String wkt=null; 358 | if(readWkt) { 359 | //读取wkb 360 | byte[] wkbFull=null; 361 | if(!store.containsKey("empty")) { 362 | String[] wkbPos=getWkbPos(store); 363 | int fullPos=Integer.parseInt(wkbPos[1]); 364 | 365 | long t_IO=System.nanoTime(); 366 | wkbFull=ReadWkbFromFile(fullPos); 367 | res.DurationN_IO+=System.nanoTime()-t_IO; 368 | } 369 | 370 | //转换回图形 371 | long t_GeometryParse=System.nanoTime(); 372 | Geometry fullGeom; 373 | if(wkbFull!=null) { 374 | fullGeom=new WKBReader(Factory).read(wkbFull); 375 | } else { 376 | fullGeom=Factory.createPolygon(); 377 | } 378 | 379 | //生成wkt 380 | wkt=new WKTWriter().write(fullGeom); 381 | res.DurationN_GeometryParse+=System.nanoTime()-t_GeometryParse; 382 | } 383 | 384 | boolean add=true; 385 | if(onFind!=null) { 386 | add=onFind.Exec(new String[] { prop, wkt }); 387 | } 388 | if (add && res.Result!=null) { 389 | if(returnWkt) { 390 | prop=prop.substring(0, prop.length()-1)+", \""+res.Set_ReturnWKTKey+"\": \""+wkt+"\"}"; 391 | } 392 | res.Result.add(prop); 393 | } 394 | res.ExactHitCount++; 395 | } 396 | 397 | res.EndTimeN=System.nanoTime(); 398 | return res; 399 | } 400 | 401 | 402 | 403 | /** 404 | * 调试用的,读取已在wkbs结构化文件中保存的网格划分图形WKT数据,用于核对网格划分情况。 405 | *
读取到的wkt文本,可以直接粘贴到页面内渲染显示:https://xiangyuecn.github.io/AreaCity-JsSpider-StatsGov/assets/geo-echarts.html 406 | * 407 | * @param wktKey 可以为null,比如填:wkt、polygon,作为json里的key: 存放wkt文本数据;如果传入空值,将只返回属性,不查询wkt文本数据;此参数会覆盖res.Set_ReturnWKTKey值 408 | * @param res 可以为null,如果提供结果对象,可通过此对象的Set_XXX属性控制某些查询行为,并且本次查询的结果和统计数据将累加到这个结果内(性能测试用)。注意:此结果对象非线程安全 409 | * @param where 必须提供一个函数,筛选属性数据(所有数据全过一遍),会传入属性的json字符串,如果需要匹配这个边界图形就返回true,否则返回false跳过这条边界图形 410 | * @param onFind 可选提供一个回调函数,每次查询到一条wkt数据后会通过onFind回传,String[]参数为[prop,wkt];如果返回false数据将不会存入res结果中(也会忽略wktKey参数),需在回调中自行处理数据 411 | */ 412 | public QueryResult Debug_ReadGeometryGridSplitsWKT(String wktKey, QueryResult res, Func where, Func onFind) throws Exception { 413 | CheckInitIsOK(); 414 | if(res==null) res=new QueryResult(); 415 | res.QueryCount++; 416 | long t_Start=System.nanoTime(); 417 | if(res.StartTimeN==0) res.StartTimeN=t_Start; 418 | 419 | res.Set_ReturnWKTKey=wktKey; 420 | boolean returnWkt=res.Set_ReturnWKTKey!=null && res.Set_ReturnWKTKey.length()>0; 421 | boolean readWkt=returnWkt; 422 | if(onFind!=null) { 423 | readWkt=true; 424 | } 425 | if(readWkt && WkbsFilePath.length()==0) { 426 | throw new Exception("初始化时必须保存了wkbs结构化数据文件,或者用的wkbs文件初始化的,否则不允许查询WKT数据"); 427 | } 428 | 429 | for(int i=0,iL=WKTDataStores.size();i store=WKTDataStores.get(i); 431 | 432 | //属性是否符合条件 433 | long t_Exact=System.nanoTime(); 434 | String prop=getProp(store); 435 | boolean isFind=where.Exec(prop); 436 | res.DurationN_ExactHitQuery+=System.nanoTime()-t_Exact; 437 | if(!isFind) { 438 | continue; 439 | } 440 | 441 | String wkt=null; 442 | if(readWkt) { 443 | String[] wkbPos=getWkbPos(store); 444 | ArrayList subs=LineSubsPos.get(wkbPos[0]); 445 | if(subs==null) { 446 | continue; 447 | } 448 | 449 | //读取所有的切块,转换回图形 450 | ArrayList pols=new ArrayList(); 451 | for(int i2=0,i2L=subs.size();i2 500 | * 支持文件(utf-8): 501 | * - *.wkbs saveWkbsFilePath生成的结构化数据文件,读取效率高。 502 | * - *.json geojson文件,要求里面数据必须是一行一条数据 503 | * ,第一条数据的上一行必须是`"features": [` 504 | * ,最后一条数据的下一行必须是`]`打头 505 | * ,否则不支持解析,可尝试用文本编辑器批量替换添加换行符。 506 | * 507 | * 默认在内存中存储的是wkb格式数据(大幅减少内存占用),查询时会将wkb还原成图形对象,可通过设置 Instances[0-9].SetInitStoreInMemoryUseObject=true 来关闭这一过程减少性能损耗,在内存中直接存储图形对象,但内存占用会增大一倍多。 508 | * 509 | * @param dataFilePath 数据文件路径(支持:*.wkbs、*.json),从这个文件读取数据;如果autoUseExistsWkbsFile=true并且saveWkbsFilePath文件存在时(已生成了结构化数据文件),可以不提供此参数 510 | * @param saveWkbsFilePath 可选提供一个.wkbs后缀的文件路径:dataFile是wkbs时不可以提供;dataFile是geojson时,加载geojson解析的数据会自动生成此结构化数据文件;如果和dataFile都不提供wkbs文件时查询中将不允许获取WKT数据 511 | * @param autoUseExistsWkbsFile 当传true时:如果检测到saveWkbsFilePath对应文件已成功生成过了,将直接使用这个wkbs文件作为dataFile(直接忽略dataFilePath参数);建议传true,这样只需要首次加载生成了结构文件,以后读取数据都非常快(数据更新时需删除wkbs文件) 512 | */ 513 | public void Init_StoreInMemory(String dataFilePath, String saveWkbsFilePath, boolean autoUseExistsWkbsFile) { 514 | __Init(autoUseExistsWkbsFile, dataFilePath, saveWkbsFilePath, true); 515 | } 516 | /** 517 | * 用加载数据到结构化数据文件的模式进行初始化,推荐使用本方法初始化,边界图形数据存入结构化数据文件中,内存占用很低(查询时会反复读取文件对应内容,查询性能消耗主要在IO上,IO性能极高问题不大);本方法可以反复调用但只会初始化一次,每次查询前都调用即可(查询会在初始化完成后进行) 518 | *
 519 | 	 * 支持文件(utf-8):
 520 | 	 *  - *.wkbs saveWkbsFilePath生成的结构化数据文件,读取效率高。
 521 | 	 *  - *.json geojson文件,要求里面数据必须是一行一条数据
 522 | 	 *                     ,第一条数据的上一行必须是`"features": [`
 523 | 	 *                     ,最后一条数据的下一行必须是`]`打头
 524 | 	 *                     ,否则不支持解析,可尝试用文本编辑器批量替换添加换行符。
 525 | 	 * 
526 | * 527 | * @param dataFilePath 数据文件路径(支持:*.wkbs、*.json),从这个文件读取数据;如果autoUseExistsWkbsFile=true并且saveWkbsFilePath文件存在时(已生成了结构化数据文件),可以不提供此参数 528 | * @param saveWkbsFilePath 不提供,或一个.wkbs后缀的文件路径:dataFile是wkbs时不可以提供;dataFile是geojson时,必须提供,加载geojson解析的数据会存入此文件 529 | * @param autoUseExistsWkbsFile 当传true时:如果检测到saveWkbsFilePath对应文件已成功生成过了,将直接使用这个wkbs文件作为dataFile(直接忽略dataFilePath参数);建议传true,这样只需要首次加载生成了结构文件,以后读取数据都非常快(数据更新时需删除wkbs文件) 530 | */ 531 | public void Init_StoreInWkbsFile(String dataFilePath, String saveWkbsFilePath, boolean autoUseExistsWkbsFile) { 532 | __Init(autoUseExistsWkbsFile, dataFilePath, saveWkbsFilePath, false); 533 | } 534 | 535 | 536 | 537 | 538 | 539 | 540 | 541 | /** 版本号,主要用于wkbs结构化文件的版本 **/ 542 | static public final String Version="1.0"; 543 | 544 | /** 性能优化的重要参数,用于将大的边界按网格拆分成小的边界,这个参数决定了每个小边界的坐标点数在这个值附近 545 | *
取值越小,查询性能越高;初始化拆分出来的Polygon会越多,占用内存也会相应增多,解析json文件、或生成wkbs文件会比较耗时。 546 | *
取值越大,查询性能越低;初始化拆分出来的Polygon会越少,占用内存也会越少,解析json文件、或生成wkbs文件会比较快。 547 | *
如果不清楚作用,请勿调整此参数;修改后,之前生成的wkbs结构化文件均会失效,初始化时会重新生成。 548 | * **/ 549 | public int SetGridFactor=100; 550 | 551 | /** init时允许使用的最大线程数量,默认为不超过5 并且 不超过cpu核心数-1;线程数不要太多, 默认就好**/ 552 | public int SetInitUseThreadMax=5; 553 | 554 | /** init采用的Init_StoreInMemory时,图形数据直接存到内存,不要转成wkb压缩内存,可进一步提升性能,但会增大一倍多的内存占用 **/ 555 | public boolean SetInitStoreInMemoryUseObject=false; 556 | 557 | /** 558 | * init状态:0未初始化,1初始化中,2初始化完成,3初始化失败(InitInfo.ErrMsg为错误消息) 559 | */ 560 | public int GetInitStatus() { 561 | return InitLock[0]; 562 | } 563 | /** 检查init状态是否是2已初始化完成,未完成会抛出错误原因 **/ 564 | public void CheckInitIsOK() throws Exception { 565 | if(InitLock[0]==3) { 566 | throw new Exception(InitInfo.ErrMsg); 567 | } 568 | if(InitLock[0]!=2) { 569 | throw new Exception("需要先Init完成后,再来进行查询调用"); 570 | } 571 | } 572 | /** 将init状态设置为0(未初始化),允许重新Init **/ 573 | public void ResetInitStatus() { 574 | synchronized (InitLock) { 575 | InitLock[0] = 0; 576 | EnvelopeSTRTree = null; 577 | WKTDataStores = null; 578 | LineSubsPos = null; 579 | } 580 | } 581 | 582 | 583 | /** 是否是通过Init_StoreInMemory初始化的 **/ 584 | public boolean IsStoreInMemory() { 585 | return GetInitStatus()==2 && ReadFromMemory; 586 | } 587 | /** 是否是通过Init_StoreInWkbsFile初始化的 **/ 588 | public boolean IsStoreInWkbsFile() { 589 | return GetInitStatus()==2 && !ReadFromMemory; 590 | } 591 | 592 | /** 593 | * init时的回调,可以绑定一个函数,接收InitInfo进度信息,回调时机: 594 | *
 595 | 	 * - 每处理一行数据会回调一次,返回false可以跳过处理一行数据,此时initInfo.CurrentLine_XX全部有值
 596 | 	 * - 处理完成时会回调一次(此时initInfo.CurrentLine_XX全部为空)
 597 | 	 * 
598 | * 此回调线程安全。 599 | */ 600 | public Func OnInitProgress; 601 | /** 602 | * init时的进度信息 603 | */ 604 | public QueryInitInfo GetInitInfo() { 605 | return InitInfo; 606 | } 607 | private QueryInitInfo InitInfo; 608 | 609 | 610 | 611 | 612 | 613 | 614 | /** jts的factory,可以用来创建Geometry **/ 615 | static public GeometryFactory Factory=new GeometryFactory(new PrecisionModel(), 4326); 616 | 617 | 618 | private int[] InitLock=new int[] { 0 };//0未初始化,1初始化中,2初始化完成,3初始化失败 619 | private boolean ReadFromMemory; 620 | private String WkbsFilePath; 621 | private STRtree EnvelopeSTRTree; //所有图形的外接矩形索引 622 | private List> WKTDataStores; //WKT查询时需要读取的属性列表 623 | private HashMap> LineSubsPos; //每行数据grid拆分后的数据在wkbs里面的存储位置 624 | private void __Init(boolean autoUseExistsWkbsFile, String dataFilePath, String saveWkbsFilePath, boolean readFromMemory) { 625 | if(InitLock[0] >= 2) { 626 | return; 627 | } 628 | synchronized (InitLock) { 629 | if(InitLock[0] >= 2) { 630 | return; 631 | } 632 | FileOutputStream fw=null; 633 | FileInputStream fr=null; 634 | BufferedReader read=null; 635 | 636 | InitLock[0]=1; 637 | try { 638 | InitInfo=new QueryInitInfo(); 639 | InitInfo.StartTimeN = System.nanoTime(); 640 | InitInfo.StartMemory_System = GetMemory_System(); 641 | InitInfo.StartMemory_JavaRuntime = GetMemory_JavaRuntime(); 642 | 643 | ReadFromMemory=readFromMemory; 644 | WkbsFilePath=""; 645 | 646 | dataFilePath=dataFilePath==null?"":dataFilePath; 647 | saveWkbsFilePath=saveWkbsFilePath==null?"":saveWkbsFilePath; 648 | if(saveWkbsFilePath.length()>0) { 649 | WkbsFilePath=saveWkbsFilePath; 650 | }else if(IsWkbsFilePath(dataFilePath)) { 651 | WkbsFilePath=dataFilePath; 652 | }else if(!ReadFromMemory){ 653 | throw new Exception("Init_StoreInWkbsFile传入非wkbs文件时,必须提供saveWkbsFilePath"); 654 | } 655 | if(saveWkbsFilePath.length()>0) { 656 | if(!IsWkbsFilePath(saveWkbsFilePath)) { 657 | throw new Exception("saveWkbsFilePath必须是.wkbs结尾"); 658 | } 659 | if(IsWkbsFilePath(dataFilePath)) { 660 | throw new Exception("dataFilePath是.wkbs文件时,不允许再提供saveWkbsFilePath"); 661 | } 662 | 663 | if(autoUseExistsWkbsFile){//如果wkbs文件已存在,并且有效,就直接读取这个文件的数据 664 | if(AvailableWkbsFile(saveWkbsFilePath)) { 665 | dataFilePath=saveWkbsFilePath; 666 | saveWkbsFilePath=""; 667 | } 668 | } 669 | } 670 | InitInfo.DataFromWkbsFile=IsWkbsFilePath(dataFilePath); 671 | InitInfo.HasWkbsFile=WkbsFilePath.length()>0; 672 | InitInfo.FilePath_Data=dataFilePath; 673 | InitInfo.FilePath_SaveWkbs=saveWkbsFilePath; 674 | 675 | //打开文件 676 | fr=new FileInputStream(dataFilePath); 677 | read=new BufferedReader(new InputStreamReader(fr, "utf-8")); 678 | if(saveWkbsFilePath.length()>0) { 679 | fw=new FileOutputStream(saveWkbsFilePath); 680 | } 681 | 682 | __InitProcess(dataFilePath, read, saveWkbsFilePath, fw); 683 | 684 | EnvelopeSTRTree.build();//立即生成索引树 685 | 686 | InitLock[0]=2; 687 | } catch (Exception e) { 688 | InitInfo.ErrMsg="初始化发生异常:"+ErrorStack(e); 689 | InitLock[0]=3; 690 | } finally { 691 | try { if(fw!=null) fw.close(); } catch(Exception e) {} 692 | try { if(fr!=null) fr.close(); } catch(Exception e) {} 693 | try { if(read!=null) read.close(); } catch(Exception e) {} 694 | 695 | long t_gc=System.nanoTime(); 696 | System.gc();//强制回收内存 697 | InitInfo.DurationN_JavaGC=System.nanoTime()-t_gc; 698 | 699 | InitInfo.CurrentLine_No=0; 700 | InitInfo.CurrentLine_Text=""; 701 | InitInfo.CurrentLine_Prop=""; 702 | 703 | InitInfo.EndTimeN = System.nanoTime(); 704 | InitInfo.EndMemory_System = GetMemory_System(); 705 | InitInfo.EndMemory_JavaRuntime = GetMemory_JavaRuntime(); 706 | } 707 | 708 | //初始化完成了,回调一下进度 709 | if(OnInitProgress!=null) { 710 | try { 711 | OnInitProgress.Exec(InitInfo); 712 | } catch (Exception e) { } 713 | } 714 | } 715 | } 716 | private void __InitProcess(String dataFilePath, BufferedReader dataFile, String saveWkbsFilePath, FileOutputStream saveWkbsFile) throws Exception { 717 | Exception[] threadError=new Exception[] { null }; 718 | 719 | STRtree rtree=new STRtree(); 720 | List> wktDataStores=new ArrayList<>(); 721 | List> emptyGeoms=new ArrayList<>(); 722 | HashMap> lineSubsPos=new HashMap<>(); 723 | 724 | boolean isWkbsFile=IsWkbsFilePath(dataFilePath); 725 | String IsStartErrMsg="未识别到geojson|wkbs数据,请检查初始化传入的文件是否正确。" 726 | +"注意:如果是geojson文件,要求里面数据必须是一行一条数据" 727 | +",第一条数据的上一行必须是`\"features\": [`,最后一条数据的下一行必须是`]`打头" 728 | +",否则不支持解析,可尝试用文本编辑器批量替换添加换行符。"; 729 | boolean[] IsStart=new boolean[] { false }; 730 | boolean[] IsEnd=new boolean[] { false }; 731 | int[] LineNo=new int[] { 0 }; 732 | HashMap Strings=new HashMap<>();//prop字符串转成引用类型 733 | 734 | //写入wkbs文件,并记录已写入长度 735 | int[] saveWkbsFileLength=new int[] { 0 }; 736 | Func SaveWkbsWrite=new Func() { 737 | @Override 738 | public Object Exec(String val) throws Exception { 739 | byte[] bs=val.getBytes("utf-8"); 740 | saveWkbsFileLength[0]+=bs.length; 741 | saveWkbsFile.write(bs); 742 | return null; 743 | } 744 | }; 745 | 746 | Func ThreadExec=new Func() { 747 | @Override 748 | public String Exec(Object val) throws Exception { 749 | while(true) { 750 | int lineNo; 751 | String line; 752 | synchronized (dataFile) {//先读取一行内容,文件内容之类的识别不允许并行 753 | if(threadError[0]!=null) throw threadError[0]; 754 | if(IsEnd[0]) break; 755 | 756 | long t_fr=System.nanoTime(); 757 | line=dataFile.readLine(); 758 | InitInfo.DurationN_FileRead+=System.nanoTime()-t_fr; 759 | if(line==null) { 760 | //没有数据了 761 | if(!IsStart[0]){ 762 | throw new Exception(IsStartErrMsg); 763 | } 764 | if(!IsEnd[0]){ 765 | throw new Exception("初始化传入的文件未发现结束位置,可能文件已损坏"); 766 | } 767 | break; 768 | } 769 | lineNo=++LineNo[0]; 770 | line=line.trim(); 771 | if(line.length()==0)continue; 772 | 773 | if(IsStart[0] && line.charAt(0)==']'){ 774 | //处理完成所有数据 775 | IsEnd[0]=true; 776 | break; 777 | } 778 | if(!IsStart[0]){ 779 | //等待开始标志 780 | int fIdx=line.indexOf("\"features\""); 781 | if(fIdx==0 || fIdx>0 && fIdx>=line.length()-14){ 782 | if(!line.endsWith("[")){ 783 | throw new Exception("初始化传入的文件第"+lineNo+"行风格不对,不支持处理此文件"); 784 | } 785 | IsStart[0]=true; 786 | 787 | if(saveWkbsFile!=null) {//写入 wkbs 文件头,这里无需同步操作 788 | SaveWkbsWrite.Exec("/*******************" 789 | +"\n本wkbs文件是由 "+AreaCityQuery.class.getTypeName()+" 生成,为专用的结构化数据文件,用于边界图形数据加速解析。" 790 | +"\n@Version: "+Version 791 | +"\n@GridFactor: "+SetGridFactor 792 | +"\n@数据文件: "+dataFilePath 793 | +"\n@生成时间: "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) 794 | +"\n" 795 | +"\nGitHub: https://github.com/xiangyuecn/AreaCity-Query-Geometry (github可换成gitee)" 796 | +"\n省市区县乡镇区划边界数据: https://github.com/xiangyuecn/AreaCity-JsSpider-StatsGov (github可换成gitee)" 797 | +"\n*******************/" 798 | +"\n" 799 | +"\n\"features\": ["); 800 | } 801 | } 802 | continue; 803 | } 804 | }// synchronized end 805 | 806 | //开始处理这一行数据 807 | 808 | long r_t1=System.nanoTime(); 809 | //手工提取properties 810 | String[] propStrPtr; 811 | String propStr,wkbPosStr=lineNo+":0:0"; 812 | boolean wkbTypeIsParent=false,wkbTypeIsSub=false,wkbTypeIsEmpty=false; 813 | int wkbIdx=0; 814 | if(isWkbsFile){ 815 | int i0=line.indexOf(WKB_SP_Pos); 816 | String wkbType=line.substring(0, i0); 817 | if(wkbType.equals("Sub")) { 818 | wkbTypeIsSub=true; 819 | } else if(wkbType.equals("Full")) { 820 | // NOOP 821 | } else if(wkbType.equals("Parent")) { 822 | wkbTypeIsParent=true; 823 | } else if(wkbType.equals("Empty")) { 824 | wkbTypeIsEmpty=true; 825 | } 826 | 827 | i0+=WKB_SP_Pos.length(); 828 | int i1=line.indexOf(WKB_SP_Prop, i0); 829 | wkbPosStr=line.substring(i0, i1); 830 | 831 | i1+=WKB_SP_Prop.length(); 832 | int i2=line.indexOf(WKB_SP_WKB, i1); 833 | propStr=line.substring(i1, i2); 834 | wkbIdx=i2+WKB_SP_WKB.length(); 835 | } else { 836 | int i0=line.indexOf("properties\""); 837 | int i1=line.indexOf("{", i0); 838 | int i2=line.indexOf("}", i0); 839 | propStr=line.substring(i1, i2+1); 840 | } 841 | //手工提取geometry类型 842 | String typeStr=""; 843 | if(!isWkbsFile){ 844 | int iGeom=line.indexOf("geometry\""); 845 | 846 | int i0=line.indexOf("type\"", iGeom); 847 | int i1=line.indexOf("\"", i0+5); 848 | int i2=line.indexOf("\"", i1+1); 849 | typeStr=line.substring(i1+1, i2); 850 | } 851 | synchronized (InitInfo) { 852 | InitInfo.DurationN_FileParse+=System.nanoTime()-r_t1; 853 | 854 | InitInfo.CurrentLine_No=lineNo; 855 | InitInfo.CurrentLine_Text=line; 856 | InitInfo.CurrentLine_Prop=propStr; 857 | 858 | //回调一下,顺带看看需不需要解析这条数据 859 | if(OnInitProgress!=null) { 860 | if(!OnInitProgress.Exec(InitInfo)) { 861 | continue; 862 | } 863 | } 864 | 865 | //在这个同步块里面顺带处理一下字符串转引用类型,减少字符串内存占用 866 | propStrPtr=Strings.get(propStr); 867 | if(propStrPtr==null) { 868 | propStrPtr=new String[] { propStr }; 869 | Strings.put(propStr, propStrPtr); 870 | } 871 | } 872 | 873 | //wkbs里面的非Sub图形,完整图形 874 | if(isWkbsFile && !wkbTypeIsSub) { 875 | synchronized (InitInfo) { 876 | InitInfo.GeometryCount++; 877 | } 878 | if(!wkbTypeIsEmpty) {//empty的丢到下面统一处理 879 | HashMap store=new HashMap<>(); 880 | store.put("prop", propStrPtr); 881 | store.put("wkbPos", wkbPosStr); 882 | synchronized (wktDataStores) { 883 | wktDataStores.add(store);//存好WKT查询数据,一个数据只存一条就行了 884 | } 885 | } 886 | if(wkbTypeIsParent) {//已经拆分了,上级完整图形无需再处理 887 | continue; 888 | } 889 | } 890 | 891 | //手工创建图形对象 892 | long r_t2=System.nanoTime(); 893 | Geometry geomSrc; 894 | if(isWkbsFile){ 895 | byte[] wkb=Hex2Bytes(line, wkbIdx); 896 | geomSrc=new WKBReader(Factory).read(wkb); 897 | } else { 898 | if(!(typeStr.equals("Polygon") || typeStr.equals("MultiPolygon"))) { 899 | throw new Exception("初始化传入的文件第"+lineNo+"行"+typeStr+"数据不是Polygon类,要求必须是Polygon或者MultiPolygon,并且json文件内一条数据一行"); 900 | } 901 | geomSrc=JSONLineParse(Factory, line); 902 | } 903 | synchronized (InitInfo) { 904 | InitInfo.DurationN_GeometryParse+=System.nanoTime()-r_t2; 905 | if(!isWkbsFile) { 906 | InitInfo.GeometryCount++; 907 | } 908 | 909 | if(geomSrc.isEmpty()){//空的存一下属性,边界就丢弃 910 | HashMap store=new HashMap<>(); 911 | store.put("prop", propStrPtr); 912 | store.put("wkbPos", wkbPosStr); 913 | store.put("empty", true); 914 | emptyGeoms.add(store); 915 | continue; 916 | } 917 | } 918 | 919 | //创建索引,将每个图形放到rtree,图形如果坐标点过多,先按网格拆成小的 920 | long r_t3=System.nanoTime(); 921 | Geometry geomGrid=geomSrc; 922 | if(!isWkbsFile) { //wkbs文件已经拆好了,非wkbs才需要按网格拆成小的 923 | geomGrid=GeometryGridSplit(Factory, geomSrc, SetGridFactor); 924 | } 925 | int wkbMemoryLen=0; 926 | int polygonNum=1; 927 | if(geomGrid instanceof MultiPolygon) { 928 | polygonNum = geomGrid.getNumGeometries(); 929 | } 930 | 931 | int parentPos=0; 932 | if(polygonNum>1 && saveWkbsFile!=null) {//有多个Polygon时,先存一个完整的父级 933 | byte[] wkb=new WKBWriter().write(geomSrc); 934 | synchronized (saveWkbsFile) { 935 | parentPos=saveWkbsFileLength[0]+1;//+1 换行符 936 | String wkbPos=lineNo+":"+parentPos+":"+parentPos; //编号:parent:sub 数据存储位置 937 | 938 | SaveWkbsWrite.Exec("\nParent"+WKB_SP_Pos+wkbPos+WKB_SP_Prop+propStr+WKB_SP_WKB+Bytes2Hex(wkb)); 939 | } 940 | } 941 | 942 | for(int i0=0;i0 store=new HashMap<>(); 969 | store.put("prop", propStrPtr); 970 | if(ReadFromMemory){//写入内存 971 | if(SetInitStoreInMemoryUseObject) { 972 | store.put("wkb", polygon); 973 | }else { 974 | if(wkb==null) { 975 | wkb=new WKBWriter().write(polygon); 976 | } 977 | wkbMemoryLen+=wkb.length; 978 | store.put("wkb", wkb); 979 | } 980 | } 981 | 982 | if(isWkbsFile) {//从wkbs文件读的数据,直接给数据位置值 983 | wkbPos=wkbPosStr; 984 | } 985 | store.put("wkbPos", wkbPos); 986 | String[] wkbPosArr=getWkbPos(store); 987 | 988 | //构造外接矩形,放到rtree里面,非线程安全需同步操作 989 | synchronized (rtree) { 990 | rtree.insert(polygon.getEnvelopeInternal(), store); 991 | 992 | //在这个同步块里面顺带把sub添加到这行数据的引用列表中 993 | ArrayList subs=lineSubsPos.get(wkbPosArr[0]); 994 | if(subs==null) { 995 | subs=new ArrayList<>(); 996 | lineSubsPos.put(wkbPosArr[0], subs); 997 | } 998 | subs.add(Integer.parseInt(wkbPosArr[2])); 999 | } 1000 | if(i0==0 && !isWkbsFile) { 1001 | //这个只在查询完整wkt数据时才有用,一个数据只存一条就行了,wkbs的上面已经存好了 1002 | synchronized (wktDataStores) { 1003 | wktDataStores.add(store); 1004 | } 1005 | } 1006 | } 1007 | synchronized (InitInfo) { 1008 | InitInfo.DurationN_Index+=System.nanoTime()-r_t3; 1009 | 1010 | if(ReadFromMemory){ 1011 | if(InitInfo.WkbMemory==-1)InitInfo.WkbMemory=0; 1012 | InitInfo.WkbMemory+=wkbMemoryLen; 1013 | } 1014 | 1015 | InitInfo.PolygonCount+=polygonNum; 1016 | } 1017 | } 1018 | return null; 1019 | } 1020 | }; 1021 | 1022 | 1023 | // 开启多线程处理读取的数据,留一个核打酱油 1024 | int[] threadCount=new int[] { Math.max(1, Math.min(SetInitUseThreadMax, Runtime.getRuntime().availableProcessors()-1)) }; 1025 | InitInfo.UseThreadCount=threadCount[0]; 1026 | for(int i=0;i0) { 1043 | try { Thread.sleep(10); }catch (Exception e) { } 1044 | } 1045 | if(threadError[0]!=null) { 1046 | throw threadError[0]; 1047 | } 1048 | 1049 | if(!IsStart[0]){ 1050 | throw new Exception(IsStartErrMsg); 1051 | } 1052 | if(InitInfo.GeometryCount==0){ 1053 | throw new Exception("初始化传入的文件内没有数据"); 1054 | } 1055 | 1056 | //统一处理empty那些图形 1057 | for(int i=0,iL=emptyGeoms.size();i store=emptyGeoms.get(i); 1059 | wktDataStores.add(store); 1060 | 1061 | if(saveWkbsFile!=null) { 1062 | String propStr=getProp(store); 1063 | String lineNo=getWkbPos(store)[0]; 1064 | String wkbPos=(saveWkbsFileLength[0]+1)+"";//+1 换行符 1065 | wkbPos=lineNo+":"+wkbPos+":"+wkbPos; //parent:sub 数据存储位置 1066 | store.put("wkbPos", wkbPos); 1067 | 1068 | byte[] wkb=new WKBWriter().write(Factory.createPolygon()); 1069 | SaveWkbsWrite.Exec("\nEmpty"+WKB_SP_Pos+wkbPos+WKB_SP_Prop+propStr+WKB_SP_WKB+Bytes2Hex(wkb)); 1070 | } 1071 | } 1072 | 1073 | if(saveWkbsFile!=null) {//写入 wkbs 文件结尾 1074 | SaveWkbsWrite.Exec("\n]"); 1075 | } 1076 | LineSubsPos=lineSubsPos; 1077 | WKTDataStores=wktDataStores; 1078 | EnvelopeSTRTree=rtree; 1079 | } 1080 | static private final String WKB_SP_Prop="|Prop:",WKB_SP_Pos="|Pos:",WKB_SP_WKB="|WKB:"; 1081 | 1082 | 1083 | private String getProp(Map store) { 1084 | return ((String[])store.get("prop"))[0]; 1085 | } 1086 | /**从保存的数据中提取出位置信息**/ 1087 | private String[] getWkbPos(Map store) { 1088 | String str=(String)store.get("wkbPos"); 1089 | int p0=str.indexOf(':'); 1090 | int p1=str.indexOf(':', p0+1); 1091 | return new String[] { 1092 | str.substring(0, p0) 1093 | ,str.substring(p0+1, p1) 1094 | ,str.substring(p1+1) 1095 | }; 1096 | } 1097 | /** 1098 | * 检测结构化数据文件是否有效 1099 | */ 1100 | private boolean AvailableWkbsFile(String path) { 1101 | File file=new File(path); 1102 | if(!file.exists())return false; 1103 | try(FileInputStream in=new FileInputStream(path)) { 1104 | byte[] buffer=new byte[8*1024]; 1105 | int len=in.read(buffer); 1106 | String txt=new String(buffer, "utf-8"); 1107 | if(!txt.contains("@Version: "+Version+"\n")) { 1108 | return false; 1109 | } 1110 | if(!txt.contains("@GridFactor: "+SetGridFactor+"\n")) { 1111 | return false; 1112 | } 1113 | 1114 | in.skip(-len);// 请注意,倒车 1115 | in.skip(file.length()-1); 1116 | return in.read()==']';// 成功写入了结尾符号 1117 | }catch (Exception e) { 1118 | return false; 1119 | } 1120 | } 1121 | /** 1122 | * 从结构化数据文件中读取一条wkb数据 1123 | */ 1124 | private byte[] ReadWkbFromFile(int pos) throws Exception { 1125 | try(FileInputStream in=new FileInputStream(WkbsFilePath)) { // RandomAccessFile 没有区别,文件流无需缓存 新打开流不消耗性能,并发控制反而会影响性能 1126 | in.skip(pos); 1127 | ByteArrayOutputStream bs=new ByteArrayOutputStream(); 1128 | byte[] buffer=new byte[32*1024]; 1129 | int len=0; 1130 | boolean isStart=false; 1131 | int findLen=0; 1132 | char[] FindChars=WKB_SP_WKB.toCharArray(); 1133 | while((len=in.read(buffer))!=-1) { 1134 | int i0=0; 1135 | if(!isStart) {//查找 WKB_SP_WKB 1136 | for(int i=0;i0) { 1166 | bs.write(buffer, i0, i1-i0); 1167 | } 1168 | if(isEnd) { 1169 | byte[] byts=bs.toByteArray(); 1170 | if(byts.length%2==1) { 1171 | throw new Exception("结构化数据内部存在错误"); 1172 | } 1173 | return Hex2Bytes(byts, 0); 1174 | } 1175 | } 1176 | } 1177 | throw new Exception("结构化数据文件已损坏"); 1178 | } 1179 | 1180 | 1181 | 1182 | 1183 | 1184 | 1185 | 1186 | 1187 | 1188 | 1189 | 1190 | 1191 | 1192 | //===========================一些函数和方法=================================== 1193 | 1194 | 1195 | 1196 | 1197 | /** 通用回调接口 **/ 1198 | public interface Func { oT Exec(iT val) throws Exception; } 1199 | 1200 | 1201 | 1202 | 1203 | /** 1204 | * 将一行JSON数据转换成Geometry对象,要求一个JSON图形数据必须占用一行文本,高性能! 1205 | */ 1206 | static private Geometry JSONLineParse(GeometryFactory factory, String line) { 1207 | ArrayList<__ParsePolygon> multiPols=new ArrayList<>(); 1208 | int iGeom=line.indexOf("geometry\""); 1209 | for(int i=line.indexOf("coordinates\"", iGeom),L=line.length();i1) { 1222 | Polygon[] pols=new Polygon[multiPols.size()]; 1223 | for(int i=0,L=multiPols.size();i points=new ArrayList<>(); 1236 | boolean isStart=false; int multiEnds=0,polEnds=0; 1237 | int i0=index; 1238 | for(int Li=line.length();i0(); 1256 | } 1257 | multiEnds++; 1258 | if(multiEnds==3) {// MultiPolygon结束 1259 | i0++;break; 1260 | } 1261 | continue; 1262 | } 1263 | polEnds=0; 1264 | multiEnds=0; 1265 | 1266 | if(c==',' || c=='[')continue; 1267 | 1268 | StringBuilder lng=new StringBuilder(),lat=new StringBuilder(); 1269 | for(;i0 ringX=new ArrayList<>(); 1294 | public Polygon toPolygon(GeometryFactory factory) { 1295 | if(ring0==null) { 1296 | return factory.createPolygon(); 1297 | } 1298 | LinearRing[] holes=null; 1299 | if(ringX.size()>0) { 1300 | holes=ringX.toArray(new LinearRing[0]); 1301 | } 1302 | return factory.createPolygon(ring0, holes); 1303 | } 1304 | } 1305 | 1306 | 1307 | /** 1308 | * 将坐标点数过多的边界,使用网格进行拆分成小块 1309 | */ 1310 | static private Geometry GeometryGridSplit(GeometryFactory factory, Geometry geom, int gridFactor) { 1311 | ArrayList pols=new ArrayList<>(); 1312 | if(geom instanceof Polygon) { 1313 | __PolygonGridSplit(factory, gridFactor, pols, (Polygon)geom); 1314 | } else { 1315 | for(int i=0,L=geom.getNumGeometries();i pols, Polygon polygon) { 1325 | int pointCount=polygon.getNumPoints(); 1326 | int gridPoint=(int)Math.round(1.0*pointCount/gridFactor);//最外层的1格平均分担点数,计算最外层网格边数 1327 | if(gridPoint<2) {//没必要拆分了 1328 | pols.add(polygon); 1329 | return; 1330 | } 1331 | Envelope box=polygon.getEnvelopeInternal(); 1332 | 1333 | //按最长的一边,对中切开,切成两块,然后递归去切 1334 | double width=box.getMaxX()-box.getMinX(); 1335 | double height=box.getMaxY()-box.getMinY(); 1336 | int gridX=1,gridY=1;//xy轴列数 1337 | if(width/(height*2)>1) {//x轴更长,切x轴,纬度简单*2 当做跟 经度 一样 1338 | gridX++; 1339 | } else { 1340 | gridY++; 1341 | } 1342 | double xStep=width/gridX; 1343 | double yStep=height/gridY; 1344 | 1345 | double x_0=box.getMinX(),y_00=box.getMinY(); 1346 | double x_1=box.getMaxX(),y_1=box.getMaxY(); 1347 | while(x_0-x_1<-xStep/2) {//注意浮点数±0.000000001的差异 1348 | double x0=x_0, x1=x_0+xStep; x_0=x1; 1349 | double y_0=y_00; 1350 | while(y_0-y_1<-yStep/2) { 1351 | double y0=y_0, y1=y_0+yStep; y_0=y1; 1352 | Polygon gridItem=factory.createPolygon(new Coordinate[] { 1353 | new Coordinate(x0, y0) 1354 | , new Coordinate(x0, y1) 1355 | , new Coordinate(x1, y1) 1356 | , new Coordinate(x1, y0) 1357 | , new Coordinate(x0, y0) 1358 | }); 1359 | Geometry chunk=polygon.intersection(gridItem); 1360 | if(!chunk.isEmpty()) { 1361 | //如果有大的就继续拆分 1362 | if(chunk instanceof Polygon) { 1363 | __PolygonGridSplit(factory, gridFactor, pols, (Polygon)chunk); 1364 | } else { 1365 | for(int i2=0,L2=chunk.getNumGeometries();i2>4) & 0x0F; 1428 | int b2=b & 0x0F; 1429 | str.append((char)(b1<=9?'0'+b1:'A'+b1-10)); 1430 | str.append((char)(b2<=9?'0'+b2:'A'+b2-10)); 1431 | } 1432 | return str.toString(); 1433 | } 1434 | /**16进制文本转成二进制内容,从指定位置开始转**/ 1435 | static private byte[] Hex2Bytes(String hex, int start) { 1436 | byte[] val=new byte[(hex.length()-start)/2]; 1437 | for(int i=start,n=0,len=hex.length();i'0') { 1480 | c+=2; break; 1481 | } 1482 | c++; 1483 | } 1484 | big=big.setScale(c, RoundingMode.HALF_UP); 1485 | 1486 | return big.toString()+"ms"; 1487 | } 1488 | /**计算两个内存字节数差值,然后显示成MB**/ 1489 | static private String Memory(long memory) { 1490 | return memory/1024/1024+"MB"; 1491 | } 1492 | /**获取当前系统内存已用字节数**/ 1493 | static private long GetMemory_System() { 1494 | try { 1495 | OperatingSystemMXBean osMX = ManagementFactory.getOperatingSystemMXBean(); 1496 | Method totalFn=osMX.getClass().getMethod("getTotalPhysicalMemorySize"); 1497 | totalFn.setAccessible(true); 1498 | Method freeFn=osMX.getClass().getMethod("getFreePhysicalMemorySize"); 1499 | freeFn.setAccessible(true); 1500 | return (long)totalFn.invoke(osMX) - (long)freeFn.invoke(osMX); 1501 | }catch (Exception e) { 1502 | return 0; 1503 | } 1504 | } 1505 | /**获取当前Java Runtime内存已用字节数**/ 1506 | static private long GetMemory_JavaRuntime() { 1507 | return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory(); 1508 | } 1509 | 1510 | 1511 | 1512 | /** 初始化是的相关信息对象 **/ 1513 | static public class QueryInitInfo { 1514 | /** 开始时间,纳秒 **/ 1515 | public long StartTimeN; 1516 | /** 结束时间,纳秒 **/ 1517 | public long EndTimeN; 1518 | 1519 | /** 开始时的系统内存已用字节数 **/ 1520 | public long StartMemory_System; 1521 | /** 结束时的系统内存已用字节数 **/ 1522 | public long EndMemory_System; 1523 | 1524 | /** 开始时的Java Runtime内存已用字节数 **/ 1525 | public long StartMemory_JavaRuntime; 1526 | /** 结束时的Java Runtime内存已用字节数 **/ 1527 | public long EndMemory_JavaRuntime; 1528 | /** 初始化使用的线程数量 **/ 1529 | public int UseThreadCount=1; 1530 | 1531 | /** 当前处理的文件行数,当全部处理完成时为0 **/ 1532 | public int CurrentLine_No; 1533 | /** 当前处理的行完整内容,当全部处理完成时为空字符串 **/ 1534 | public String CurrentLine_Text=""; 1535 | /** 当前处理的行属性内容,当全部处理完成时为空字符串 **/ 1536 | public String CurrentLine_Prop=""; 1537 | 1538 | /** 有效的图形数量,不包括空的图形 **/ 1539 | public int GeometryCount; 1540 | /** 图形中的Polygon数量,一个图形包含1-n个Polygon,会用这些数量的Polygon外接矩形进行初步查找 **/ 1541 | public int PolygonCount; 1542 | /** 如果缓存了wkb数据在内存,这里将会有wkb总字节数,未缓存为-1 **/ 1543 | public int WkbMemory=-1; 1544 | 1545 | /** 文件读取:文件内容读取耗时,纳秒 **/ 1546 | public long DurationN_FileRead; 1547 | /** 文件解析:文件内容解析耗时,纳秒 **/ 1548 | public long DurationN_FileParse; 1549 | /** 创建图形:内容解析成Geometry对象耗时,纳秒 **/ 1550 | public long DurationN_GeometryParse; 1551 | /** Geometry对象进行索引耗时,纳秒 **/ 1552 | public long DurationN_Index; 1553 | /** 初始化结尾调用System.gc()回收内存的耗时,纳秒 **/ 1554 | public long DurationN_JavaGC; 1555 | 1556 | /** 初始化时提供的数据文件路径 **/ 1557 | public String FilePath_Data; 1558 | /** 初始化是提供的.wkbs后缀的结构化数据文件路径 **/ 1559 | public String FilePath_SaveWkbs; 1560 | 1561 | /**初始化时的数据是否是从wkbs结构化数据文件中读取;如果为false可能代表还未生成过wkbs文件,首次初始化可能会很慢**/ 1562 | public boolean DataFromWkbsFile; 1563 | /**初始化时是否使用或保存了wkbs结构化数据文件,没有wkbs文件时查询中不允许获取WKT数据**/ 1564 | public boolean HasWkbsFile; 1565 | /**初始化失败时的错误消息**/ 1566 | public String ErrMsg=""; 1567 | 1568 | /** 初始化是否出现了错误 **/ 1569 | public boolean hasError() { 1570 | return ErrMsg!=null && ErrMsg.length()>0; 1571 | } 1572 | @Override 1573 | public String toString() { 1574 | StringBuilder str=new StringBuilder(); 1575 | str.append("[v"+AreaCityQuery.Version+"]" 1576 | +(DataFromWkbsFile?"wkbs+":"") 1577 | +"已读取Geometry "+GeometryCount+" 个(Grid切分Polygon "+PolygonCount+" 个)"); 1578 | 1579 | if(hasError()) { 1580 | String errT="\n=============\n"; 1581 | str.append(errT+ErrMsg+errT); 1582 | } 1583 | 1584 | str.append("\n"); 1585 | long tn=EndTimeN-StartTimeN; 1586 | str.append("Init总耗时: "+tn/1000000+"ms"); 1587 | str.append(",平均: "+(GeometryCount==0?"-":Nano(tn*1.0/GeometryCount))+"/个Geometry,线程数: "+UseThreadCount); 1588 | 1589 | if(WkbMemory!=-1)str.append("\nWKB内存: "+Memory(WkbMemory)); 1590 | str.append("\n文件读取耗时: "+Nano(DurationN_FileRead)); 1591 | str.append("\n文件解析耗时: "+Nano(DurationN_FileParse/UseThreadCount)+"/线程,总: "+Nano(DurationN_FileParse)); 1592 | str.append("\n创建图形耗时: "+Nano(DurationN_GeometryParse/UseThreadCount)+"/线程,总: "+Nano(DurationN_GeometryParse)); 1593 | str.append("\n创建索引耗时: "+Nano(DurationN_Index/UseThreadCount)+"/线程,总: "+Nano(DurationN_Index)); 1594 | 1595 | str.append("\n内存占用: "+Memory(EndMemory_JavaRuntime- StartMemory_JavaRuntime)+" (Java Runtime)"); 1596 | str.append(", "+Memory(EndMemory_System - StartMemory_System)+" (系统)"); 1597 | str.append(", Java GC耗时: "+Nano(DurationN_JavaGC)); 1598 | 1599 | str.append("\nData文件: "+FilePath_Data); 1600 | str.append("\nWkbs文件: "+FilePath_SaveWkbs); 1601 | 1602 | return str.toString(); 1603 | } 1604 | } 1605 | 1606 | 1607 | 1608 | 1609 | 1610 | /** 查询控制+和结果信息对象 **/ 1611 | static public class QueryResult { 1612 | /** 查询结果列表,为匹配的边界属性数据(prop json字符串);如果设为null将只统计数据,不返回结果 **/ 1613 | public ArrayList Result=new ArrayList<>(); 1614 | 1615 | /** 查询开始时间,纳秒 **/ 1616 | public long StartTimeN; 1617 | /** 查询结束时间,纳秒 **/ 1618 | public long EndTimeN; 1619 | 1620 | /** 查询过程中涉及到的IO耗时,纳秒 **/ 1621 | public long DurationN_IO; 1622 | /** 查询过程中涉及到的图形对象解析耗时,纳秒 **/ 1623 | public long DurationN_GeometryParse; 1624 | /** 从边界外接矩形中初步筛选耗时,纳秒 **/ 1625 | public long DurationN_EnvelopeHitQuery; 1626 | /** 查询过程中精确查找耗时,纳秒 **/ 1627 | public long DurationN_ExactHitQuery; 1628 | 1629 | /** 外接矩形中初步筛选匹配到的矩形数量 **/ 1630 | public int EnvelopeHitCount; 1631 | /** 精确查找到的边界数量 **/ 1632 | public int ExactHitCount; 1633 | 1634 | /** 本结果对象经过了几次查询(性能测试用) **/ 1635 | public int QueryCount; 1636 | 1637 | /** 将另一个的统计数据添加到这个里面来 **/ 1638 | public void Add(QueryResult other) { 1639 | StartTimeN=Math.min(StartTimeN, other.StartTimeN); 1640 | EndTimeN=Math.max(EndTimeN, other.EndTimeN); 1641 | 1642 | DurationN_IO+=other.DurationN_IO; 1643 | DurationN_GeometryParse+=other.DurationN_GeometryParse; 1644 | DurationN_EnvelopeHitQuery+=other.DurationN_EnvelopeHitQuery; 1645 | DurationN_ExactHitQuery+=other.DurationN_ExactHitQuery; 1646 | 1647 | EnvelopeHitCount+=other.EnvelopeHitCount; 1648 | ExactHitCount+=other.ExactHitCount; 1649 | QueryCount+=other.QueryCount; 1650 | } 1651 | 1652 | 1653 | /** 如果不为null,几何计算查询时将会把从边界外接矩形中初步筛选时匹配到的中间结果写入到这个数组中(这些匹配项将参与精确匹配,数量越多性能越低下) **/ 1654 | public ArrayList Set_EnvelopeHitResult=null; 1655 | 1656 | /** 查询结果中要额外包含对应的边界wkt文本,此参数会作为wkt文本在json里的key;必须初始化时保存了wkbs结构化数据文件,或者用的wkbs文件初始化的 **/ 1657 | public String Set_ReturnWKTKey=null; 1658 | 1659 | 1660 | @Override 1661 | public String toString() { 1662 | StringBuilder str=new StringBuilder(); 1663 | long tn=EndTimeN-StartTimeN; 1664 | str.append("查询"+QueryCount+"次共耗时: "+Nano(tn)); 1665 | str.append(",EnvelopeHitCount: "+EnvelopeHitCount); 1666 | str.append(",ExactHitCount: "+ExactHitCount); 1667 | str.append(",IO: "+Nano(DurationN_IO)); 1668 | str.append(",GeometryParse: "+Nano(DurationN_GeometryParse)); 1669 | str.append(",EnvelopeHitQuery: "+Nano(DurationN_EnvelopeHitQuery)); 1670 | str.append(",ExactHitQuery: "+Nano(DurationN_ExactHitQuery)); 1671 | 1672 | if(QueryCount>1) { 1673 | double count=QueryCount; 1674 | str.append("\n单次查询耗时: "+Nano(tn/count)); 1675 | str.append(",EnvelopeHitCount: "+Math.round(EnvelopeHitCount*100/count)/100.0); 1676 | str.append(",ExactHitCount: "+Math.round(ExactHitCount*100/count)/100.0); 1677 | str.append(",IO: "+Nano(DurationN_IO/count)); 1678 | str.append(",GeometryParse: "+Nano(DurationN_GeometryParse/count)); 1679 | str.append(",EnvelopeHitQuery: "+Nano(DurationN_EnvelopeHitQuery/count)); 1680 | str.append(",ExactHitQuery: "+Nano(DurationN_ExactHitQuery/count)); 1681 | } 1682 | 1683 | if(Set_EnvelopeHitResult!=null) { 1684 | str.append("\n\nEnvelopeHit初步筛选: "+Set_EnvelopeHitResult.size()+"条"); 1685 | for(int i=0;i