diff --git a/.gitignore b/.gitignore index 7f7b9c3..aceaaf2 100644 --- a/.gitignore +++ b/.gitignore @@ -74,3 +74,9 @@ $RECYCLE.BIN/ # Windows shortcuts *.lnk /target/ + +.idea/ +.gradle/ +build/ +local.properties +*.iml diff --git a/README.md b/README.md index 358268a..a8dc8c0 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,30 @@ -coordtransform 坐标转换 +CoordTransform 坐标转换 --- -提供百度坐标(BD09)、国测局坐标(火星坐标,GCJ02)、和WGS84坐标系之间的转换的工具模块 -(参考wandergis的python版coordtransform的Java版实现) -其他版本实现 ---- -* [java版本](https://github.com/geosmart/coordtransform) -* [javascript版本](https://github.com/wandergis/coordtransform) -* [python版本](https://github.com/wandergis/coordtransform) +[![Release](https://jitpack.io/v/ipcjs/coordtransform.svg)](https://jitpack.io/#ipcjs/coordtransform) + +[wandergis/coordtransform](https://github.com/wandergis/coordtransform)的Java版。 +提供百度坐标(BD09)、国测局坐标(火星坐标,GCJ02)、和WGS84坐标系之间的转换的工具模块。 + +**注意**:CoordinateTransformUtil的方法的输入输出参数都为`(lng, lat)`,和Android一般的`(lat, lng)`正好相反,使用时要注意一下。 + +## 国内外判断 + +黄色为原版的国内区域,蓝色和红色为修改后的国内区域 + +![国内的范围](doc/is_in_china.jpg) + +## 测试 + +- [CoordinateConverterTest.java](/src/test/java/me/demo/util/geo/test/CoordinateConverterTest.java):将坐标转换后生成[Web版百度](http://lbsyun.baidu.com/index.php?title=uri/api/web)的Url,点开即可查看转换是否偏移 + +## 其他版本实现 + +- JavaScript版:[wandergis/coordtransform](https://github.com/wandergis/coordtransform) +- Python版:[wandergis/coordTransform_py](https://github.com/wandergis/coordTransform_py) +- Java版:[geosmart/coordtransform](https://github.com/geosmart/coordtransform) +- Dart/Flutter版:[ipcjs/coordtransform_dart](https://github.com/ipcjs/coordtransform_dart) + +## 参考资料 +- [Coordtransform 的使用文档](http://wandergis.com/coordtransform/) diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..d39ffe3 --- /dev/null +++ b/build.gradle @@ -0,0 +1,82 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. + +buildscript { + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:4.2.2' + } +} + +allprojects { + repositories { + google() + maven { url 'https://jitpack.io' } + mavenCentral() + } +} + +ext { + compileSdkVersion = 33 + minSdkVersion = 19 + targetSdkVersion = 33 +} + +apply plugin: 'com.android.application' + +android { + compileSdk rootProject.compileSdkVersion + + defaultConfig { + applicationId "com.github.ipcjs.coordtransform" + minSdkVersion rootProject.minSdkVersion + targetSdkVersion rootProject.targetSdkVersion + versionCode 1 + versionName "1.0" + testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" + manifestPlaceholders = [ + BAIDU_MAP_KEY : "rM8VXLKBO7K9F69vdAyNc1Mr9H8p9wma", + GOOGLE_MAP_KEY: "xx", + ] + } + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' + } + } + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + signingConfigs { + // your debug keystore + debug { + storeFile file("debug.keystore") + } + } + + sourceSets { + main { + jniLibs.srcDir 'libs' + } + } + lintOptions { + abortOnError false + } +} + +dependencies { + implementation project(':library') + implementation 'com.github.ipcjs.baidu-map-sdk:g01:g01_3.0.5' + + testImplementation "junit:junit:4.13.2" + androidTestImplementation "androidx.test.ext:junit:1.1.5" + androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1") + implementation fileTree(dir: 'libs', include: ['*.jar']) + implementation "androidx.appcompat:appcompat:1.3.1" +} \ No newline at end of file diff --git a/debug.keystore b/debug.keystore new file mode 100644 index 0000000..aa6b9e7 Binary files /dev/null and b/debug.keystore differ diff --git a/doc/is_in_china.jpg b/doc/is_in_china.jpg new file mode 100644 index 0000000..e122ed2 Binary files /dev/null and b/doc/is_in_china.jpg differ diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..0068720 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,15 @@ +## For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +# Default value: -Xmx1024m -XX:MaxPermSize=256m +# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 +# +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. For more details, visit +# https://developer.android.com/r/tools/gradle-multi-project-decoupled-projects +# org.gradle.parallel=true +#Thu Jun 13 10:57:14 CST 2024 +android.enableJetifier=true +android.useAndroidX=true diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..13372ae Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..905ec45 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Thu Nov 22 14:58:10 CST 2018 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.9.4-all.zip diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..9d82f78 --- /dev/null +++ b/gradlew @@ -0,0 +1,160 @@ +#!/usr/bin/env bash + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn ( ) { + echo "$*" +} + +die ( ) { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; +esac + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules +function splitJvmOpts() { + JVM_OPTS=("$@") +} +eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS +JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" + +exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..8a0b282 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,90 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windowz variants + +if not "%OS%" == "Windows_NT" goto win9xME_args +if "%@eval[2+2]" == "4" goto 4NT_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* +goto execute + +:4NT_args +@rem Get arguments from the 4NT Shell from JP Software +set CMD_LINE_ARGS=%$ + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/library/.gitignore b/library/.gitignore new file mode 100644 index 0000000..796b96d --- /dev/null +++ b/library/.gitignore @@ -0,0 +1 @@ +/build diff --git a/library/build.gradle b/library/build.gradle new file mode 100644 index 0000000..1b19556 --- /dev/null +++ b/library/build.gradle @@ -0,0 +1,9 @@ +apply plugin: 'java-library' +apply plugin: 'maven' + +dependencies { + implementation fileTree(dir: 'libs', include: ['*.jar']) +} + +sourceCompatibility = "1.8" +targetCompatibility = "1.8" diff --git a/library/src/main/java/com/github/ipcjs/coordtransform/CoordinateTransformUtil.java b/library/src/main/java/com/github/ipcjs/coordtransform/CoordinateTransformUtil.java new file mode 100644 index 0000000..a8dc416 --- /dev/null +++ b/library/src/main/java/com/github/ipcjs/coordtransform/CoordinateTransformUtil.java @@ -0,0 +1,260 @@ +package com.github.ipcjs.coordtransform; + +/** + * 百度坐标(BD09)、国测局坐标(火星坐标,GCJ02)、和WGS84坐标系之间的转换的工具 + *

+ * 参考wandergis/coordtransform实现的Java版本 + * @author geosmart + */ +public class CoordinateTransformUtil { + + // China region - raw data + public static final Rectangle[] REGION = { + new Rectangle(79.446200, 49.220400, 96.330000, 42.889900), + new Rectangle(109.687200, 54.141500, 135.000200, 39.374200), + new Rectangle(73.124600, 42.889900, 124.143255, 29.529700), + new Rectangle(82.968400, 29.529700, 97.035200, 26.718600), + new Rectangle(97.025300, 29.529700, 124.367395, 20.414096), + new Rectangle(107.975793, 20.414096, 111.744104, 17.871542), + }; + + // China excluded region - raw data + public static final Rectangle[] EXCLUDE = { + new Rectangle(119.921265, 25.398623, 122.497559, 21.785006), + new Rectangle(101.865200, 22.284000, 106.665000, 20.098800), + new Rectangle(106.452500, 21.542200, 108.051000, 20.487800), + new Rectangle(109.032300, 55.817500, 119.127000, 50.325700), + new Rectangle(127.456800, 55.817500, 137.022700, 49.557400), + new Rectangle(131.266200, 44.892200, 137.022700, 42.569200), + new Rectangle(73.124600, 35.398637, 77.948114, 29.529700), + }; + + // China excluded region 2, HongKong etc. + public static final Rectangle[] EXCLUDE_REGION_2 = { + new Rectangle(114.505238, 22.138258, 113.845000, 22.428903), + new Rectangle(113.97000, 22.507833, 114.450000, 22.428903), + }; + + private static double X_PI = 3.14159265358979324 * 3000.0 / 180.0; + + // π + private static double PI = 3.1415926535897932384626; + + // 长半轴 + private static double A = 6378245.0; + + // 扁率 + private static double EE = 0.00669342162296594323; + + private static boolean isInChina(double lng, double lat) { + return isInChina(lng, lat, true); + } + + private static boolean isInChina(double lng, double lat, boolean excludeRegion2) { + for (Rectangle region : REGION) { + if (region.contain(lng, lat)) { + for (Rectangle exclude : EXCLUDE) { + if (exclude.contain(lng, lat)) { + return false; + } + } + if (excludeRegion2) { + for (Rectangle exclude : EXCLUDE_REGION_2) { + if (exclude.contain(lng, lat)) { + return false; + } + } + } + return true; + } + } + return false; + } + + /** + * WGS84转GCJ02(火星坐标系) (判断了中国范围) + * @param lng WGS84坐标系的经度 + * @param lat WGS84坐标系的纬度 + * @return 火星坐标数组 + */ + public static double[] wgs84ToGcj02(double lng, double lat) { + if (!isInChina(lng, lat)) { + return new double[]{lng, lat}; + } + return wgs84ToGcj02Raw(lng, lat); + } + + /** + * GCJ02(火星坐标系)转WGS84 (判断了中国范围) + * @param lng 火星坐标系的经度 + * @param lat 火星坐标系纬度 + * @return WGS84坐标数组 + */ + public static double[] gcj02ToWgs84(double lng, double lat) { + if (!isInChina(lng, lat)) { + return new double[]{lng, lat}; + } + return gcj02ToWgs84Raw(lng, lat); + } + + /** + * 百度坐标系(BD-09)转WGS坐标 (判断了中国范围) + * @param lng 百度坐标纬度 + * @param lat 百度坐标经度 + * @return WGS84坐标数组 + */ + public static double[] bd09ToWgs84(double lng, double lat) { + if (!isInChina(lng, lat, false)) { + return new double[]{lng, lat}; + } + return bd09ToWgs84Raw(lng, lat); + } + + /** + * WGS坐标转百度坐标系(BD-09) (判断了中国范围) + * @param lng WGS84坐标系的经度 + * @param lat WGS84坐标系的纬度 + * @return 百度坐标数组 + */ + public static double[] wgs84ToBd09(double lng, double lat) { + if (!isInChina(lng, lat, false)) { + return new double[]{lng, lat}; + } + return wgs84ToBd09Raw(lng, lat); + } + + /** + * WGS84转GCJ02(火星坐标系) + * @param lng WGS84坐标系的经度 + * @param lat WGS84坐标系的纬度 + * @return 火星坐标数组 + */ + public static double[] wgs84ToGcj02Raw(double lng, double lat) { + return transform(lng, lat); + } + + /** + * GCJ02(火星坐标系)转WGS84 + * @param lng 火星坐标系的经度 + * @param lat 火星坐标系纬度 + * @return WGS84坐标数组 + */ + public static double[] gcj02ToWgs84Raw(double lng, double lat) { + double[] out = transform(lng, lat); + return new double[]{lng * 2 - out[0], lat * 2 - out[1]}; + } + + /** + * 火星坐标系(GCJ-02)转百度坐标系(BD-09) + * @param lng 火星坐标经度 + * @param lat 火星坐标纬度 + * @return 百度坐标数组 + * @info 谷歌、高德——>百度 + */ + public static double[] gcj02ToBd09(double lng, double lat) { + double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * X_PI); + double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * X_PI); + double bd_lng = z * Math.cos(theta) + 0.0065; + double bd_lat = z * Math.sin(theta) + 0.006; + return new double[]{bd_lng, bd_lat}; + } + + /** + * 百度坐标系(BD-09)转火星坐标系(GCJ-02) + * @param bd_lng 百度坐标纬度 + * @param bd_lat 百度坐标经度 + * @return 火星坐标数组 + * @info 百度——>谷歌、高德 + */ + public static double[] bd09ToGcj02(double bd_lng, double bd_lat) { + double x = bd_lng - 0.0065; + double y = bd_lat - 0.006; + double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI); + double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI); + double gg_lng = z * Math.cos(theta); + double gg_lat = z * Math.sin(theta); + return new double[]{gg_lng, gg_lat}; + } + + /** + * WGS坐标转百度坐标系(BD-09) + * @param lng WGS84坐标系的经度 + * @param lat WGS84坐标系的纬度 + * @return 百度坐标数组 + */ + public static double[] wgs84ToBd09Raw(double lng, double lat) { + double[] gcj = wgs84ToGcj02Raw(lng, lat); + double[] bd09 = gcj02ToBd09(gcj[0], gcj[1]); + return bd09; + } + + /** + * 百度坐标系(BD-09)转WGS坐标 + * @param lng 百度坐标纬度 + * @param lat 百度坐标经度 + * @return WGS84坐标数组 + */ + public static double[] bd09ToWgs84Raw(double lng, double lat) { + double[] gcj = bd09ToGcj02(lng, lat); + double[] wgs84 = gcj02ToWgs84Raw(gcj[0], gcj[1]); + return wgs84; + } + + private static double[] transform(final double lng, final double lat) { + double dlat = transformLat(lng - 105.0, lat - 35.0); + double dlng = transformLng(lng - 105.0, lat - 35.0); + double radlat = lat / 180.0 * PI; + double magic = Math.sin(radlat); + magic = 1 - EE * magic * magic; + double sqrtmagic = Math.sqrt(magic); + dlat = (dlat * 180.0) / ((A * (1 - EE)) / (magic * sqrtmagic) * PI); + dlng = (dlng * 180.0) / (A / sqrtmagic * Math.cos(radlat) * PI); + return new double[]{lng + dlng, lat + dlat}; + } + + /** + * 纬度转换 + */ + private static double transformLat(double lng, double lat) { + double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math + .sqrt(Math.abs(lng)); + ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; + ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0; + ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0; + return ret; + } + + /** + * 经度转换 + */ + private static double transformLng(double lng, double lat) { + double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math + .sqrt(Math.abs(lng)); + ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; + ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0; + ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0; + return ret; + } + + public static class Rectangle { + + public final double west; + + public final double north; + + public final double east; + + public final double south; + + public Rectangle(double lng1, double lat1, double lng2, double lat2) { + this.west = Math.min(lng1, lng2); + this.north = Math.max(lat1, lat2); + this.east = Math.max(lng1, lng2); + this.south = Math.min(lat1, lat2); + } + + public boolean contain(double lng, double lat) { + return this.west <= lng && this.east >= lng && this.north >= lat && this.south <= lat; + } + } +} diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 0000000..d8f14a1 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +include ':library' diff --git a/src/main/AndroidManifest.xml b/src/main/AndroidManifest.xml new file mode 100644 index 0000000..01abcb6 --- /dev/null +++ b/src/main/AndroidManifest.xml @@ -0,0 +1,11 @@ + + + + + + + + + + diff --git a/src/main/java/me/demo/MainActivity.java b/src/main/java/me/demo/MainActivity.java new file mode 100644 index 0000000..aaefe93 --- /dev/null +++ b/src/main/java/me/demo/MainActivity.java @@ -0,0 +1,167 @@ +package me.demo; + +import android.graphics.Bitmap; +import android.graphics.Canvas; +import android.graphics.Color; +import android.graphics.Point; +import android.os.Bundle; +import android.util.Log; +import android.view.MotionEvent; +import android.widget.TextView; + +import com.baidu.mapapi.CoordType; +import com.baidu.mapapi.SDKInitializer; +import com.baidu.mapapi.map.BaiduMap; +import com.baidu.mapapi.map.BaiduMapOptions; +import com.baidu.mapapi.map.BitmapDescriptor; +import com.baidu.mapapi.map.BitmapDescriptorFactory; +import com.baidu.mapapi.map.InfoWindow; +import com.baidu.mapapi.map.MapPoi; +import com.baidu.mapapi.map.MapStatus; +import com.baidu.mapapi.map.MapStatusUpdateFactory; +import com.baidu.mapapi.map.MarkerOptions; +import com.baidu.mapapi.map.Overlay; +import com.baidu.mapapi.map.PolylineOptions; +import com.baidu.mapapi.map.SupportMapFragment; +import com.baidu.mapapi.model.LatLng; +import com.baidu.mapapi.model.LatLngBounds; +import com.github.ipcjs.coordtransform.CoordinateTransformUtil; + +import java.util.ArrayList; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.appcompat.app.AppCompatActivity; +import androidx.fragment.app.FragmentManager; + +/** + * Created by ipcjs on 2017/9/29. + */ + +public class MainActivity extends AppCompatActivity { + + public static final CoordinateTransformUtil.Rectangle[] RECTANGLES = { + new CoordinateTransformUtil.Rectangle(72.004, 0.8293, 137.8347, 55.8271) + }; + + public static final String TAG_MAP = "map"; + private static final String TAG = "MainActivity"; + + private BaiduMap mBaiduMap; + + private SupportMapFragment mMapFragment; + private Overlay mDotMarker = null; + + @Override + protected void onCreate(@Nullable Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + FragmentManager fm = getSupportFragmentManager(); + + SDKInitializer.setAgreePrivacy(getApplicationContext(), true); + SDKInitializer.initialize(getApplicationContext()); + SDKInitializer.setCoordType(CoordType.GCJ02); + + mMapFragment = (SupportMapFragment) fm.findFragmentByTag(TAG_MAP); + if (mMapFragment == null) { + mMapFragment = SupportMapFragment.newInstance(new BaiduMapOptions() + .mapStatus(new MapStatus.Builder().zoom(2).build()) + ); + fm.beginTransaction() + .add(android.R.id.content, mMapFragment, TAG_MAP) + .commitNow(); // 立即提交 + } + getWindow().getDecorView().post(this::initMap); // 下个事件循环中才能读取到MapView + } + + private void initMap() { + mBaiduMap = mMapFragment.getBaiduMap(); + drawRectangle(CoordinateTransformUtil.REGION, Color.BLUE); // 属于中国的范围 + drawRectangle(CoordinateTransformUtil.EXCLUDE, Color.RED); // 不属于中国的范围 + drawRectangle(RECTANGLES, Color.YELLOW); // 属于中国的范围 + + mBaiduMap.setOnMapLoadedCallback(() -> { + LatLngBounds.Builder boundBuilder = new LatLngBounds.Builder(); + for (CoordinateTransformUtil.Rectangle rect : RECTANGLES) { + boundBuilder.include(new LatLng(rect.north, rect.west)); + boundBuilder.include(new LatLng(rect.south, rect.east)); + } + mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLngBounds(boundBuilder.build())); + }); + + mBaiduMap.setOnMapTouchListener(new BaiduMap.OnMapTouchListener() { + @Override + public void onTouch(MotionEvent event) { + if (event.getAction() != MotionEvent.ACTION_UP) { + return; + } + LatLng latLng = mBaiduMap.getProjection().fromScreenLocation(new Point((int) event.getX(), (int) event.getY())); + Log.d(TAG, "onTouch: " + latLng + ", (" + event.getX() + ", " + event.getY() + ")"); + // 要延时一下, 否则OnMapClickListener会不生效... + getWindow().getDecorView().postDelayed(() -> updateDotMarker(latLng), 500); + } + }); + + mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() { + @Override + public void onMapClick(LatLng latLng) { + Log.d(TAG, "onMapClick: " + latLng); + } + + @Override + public void onMapPoiClick(MapPoi mapPoi) { + Log.d(TAG, "onMapPoiClick: " + mapPoi.getName() + ", " + mapPoi.getPosition()); + } + }); + mBaiduMap.setOnMarkerClickListener(marker -> { + if (marker.getTitle() != null) { + mBaiduMap.showInfoWindow(new InfoWindow(createTextIcon(marker.getTitle(), Color.BLACK), marker.getPosition(), 0, () -> { + Log.i(TAG, "infoWindow clicked"); + })); + return true; + } + return false; + }); + } + + private void updateDotMarker(LatLng latLng) { + if (mDotMarker != null) { + mDotMarker.remove(); + } + Log.i(TAG, "add dot on " + latLng.toString()); + mDotMarker = mBaiduMap.addOverlay(new MarkerOptions() + .position(latLng) + .anchor(0.5f, 0.5f) + .title(latLng.toString()) + .icon(createDotIcon()) + ); + } + + @NonNull + private BitmapDescriptor createDotIcon() { + Bitmap dot = Bitmap.createBitmap(9, 9, Bitmap.Config.ARGB_8888); + Canvas c = new Canvas(dot); + c.drawColor(Color.RED); + return BitmapDescriptorFactory.fromBitmap(dot); + } + + private BitmapDescriptor createTextIcon(CharSequence text, int textColor) { + TextView view = new TextView(this); + view.setText(text); + view.setTextColor(textColor); + return BitmapDescriptorFactory.fromView(view); + } + + private void drawRectangle(CoordinateTransformUtil.Rectangle[] rectangles, int color) { + for (int i = 0, rectanglesLength = rectangles.length; i < rectanglesLength; i++) { + CoordinateTransformUtil.Rectangle r = rectangles[i]; + ArrayList points = new ArrayList<>(); + points.add(new LatLng(r.north, r.west)); + points.add(new LatLng(r.north, r.east)); + points.add(new LatLng(r.south, r.east)); + points.add(new LatLng(r.south, r.west)); + points.add(points.get(0)); // 闭合 线 + mBaiduMap.addOverlay(new PolylineOptions().points(points).color(color)); + mBaiduMap.addOverlay(new MarkerOptions().position(points.get(0)).icon(createTextIcon(String.valueOf(i), color))); + } + } +} diff --git a/src/main/java/me/demo/util/geo/CoordinateTransformUtil.java b/src/main/java/me/demo/util/geo/CoordinateTransformUtil.java deleted file mode 100644 index ef77003..0000000 --- a/src/main/java/me/demo/util/geo/CoordinateTransformUtil.java +++ /dev/null @@ -1,171 +0,0 @@ -package me.demo.util.geo; - -/** - * 百度坐标(BD09)、国测局坐标(火星坐标,GCJ02)、和WGS84坐标系之间的转换的工具 - * - * @see 参考https://github.com/wandergis/coordtransform实现的Java版本 - * @author geosmart - */ -public class CoordinateTransformUtil { - static double x_pi = 3.14159265358979324 * 3000.0 / 180.0; - // π - static double pi = 3.1415926535897932384626; - // 长半轴 - static double a = 6378245.0; - // 扁率 - static double ee = 0.00669342162296594323; - - /** - * 百度坐标系(BD-09)转WGS坐标 - * - * @param lng 百度坐标纬度 - * @param lat 百度坐标经度 - * @return WGS84坐标数组 - */ - public static double[] bd09towgs84(double lng, double lat) { - double[] gcj = bd09togcj02(lng, lat); - double[] wgs84 = gcj02towgs84(gcj[0], gcj[1]); - return wgs84; - } - - /** - * WGS坐标转百度坐标系(BD-09) - * - * @param lng WGS84坐标系的经度 - * @param lat WGS84坐标系的纬度 - * @return 百度坐标数组 - */ - public static double[] wgs84tobd09(double lng, double lat) { - double[] gcj = wgs84togcj02(lng, lat); - double[] bd09 = gcj02tobd09(gcj[0], gcj[1]); - return bd09; - } - - /** - * 火星坐标系(GCJ-02)转百度坐标系(BD-09) - * - * @see 谷歌、高德——>百度 - * @param lng 火星坐标经度 - * @param lat 火星坐标纬度 - * @return 百度坐标数组 - */ - public static double[] gcj02tobd09(double lng, double lat) { - double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_pi); - double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_pi); - double bd_lng = z * Math.cos(theta) + 0.0065; - double bd_lat = z * Math.sin(theta) + 0.006; - return new double[] { bd_lng, bd_lat }; - } - - /** - * 百度坐标系(BD-09)转火星坐标系(GCJ-02) - * - * @see 百度——>谷歌、高德 - * @param lng 百度坐标纬度 - * @param lat 百度坐标经度 - * @return 火星坐标数组 - */ - public static double[] bd09togcj02(double bd_lon, double bd_lat) { - double x = bd_lon - 0.0065; - double y = bd_lat - 0.006; - double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi); - double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi); - double gg_lng = z * Math.cos(theta); - double gg_lat = z * Math.sin(theta); - return new double[] { gg_lng, gg_lat }; - } - - /** - * WGS84转GCJ02(火星坐标系) - * - * @param lng WGS84坐标系的经度 - * @param lat WGS84坐标系的纬度 - * @return 火星坐标数组 - */ - public static double[] wgs84togcj02(double lng, double lat) { - if (out_of_china(lng, lat)) { - return new double[] { lng, lat }; - } - double dlat = transformlat(lng - 105.0, lat - 35.0); - double dlng = transformlng(lng - 105.0, lat - 35.0); - double radlat = lat / 180.0 * pi; - double magic = Math.sin(radlat); - magic = 1 - ee * magic * magic; - double sqrtmagic = Math.sqrt(magic); - dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi); - dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi); - double mglat = lat + dlat; - double mglng = lng + dlng; - return new double[] { mglng, mglat }; - } - - /** - * GCJ02(火星坐标系)转GPS84 - * - * @param lng 火星坐标系的经度 - * @param lat 火星坐标系纬度 - * @return WGS84坐标数组 - */ - public static double[] gcj02towgs84(double lng, double lat) { - if (out_of_china(lng, lat)) { - return new double[] { lng, lat }; - } - double dlat = transformlat(lng - 105.0, lat - 35.0); - double dlng = transformlng(lng - 105.0, lat - 35.0); - double radlat = lat / 180.0 * pi; - double magic = Math.sin(radlat); - magic = 1 - ee * magic * magic; - double sqrtmagic = Math.sqrt(magic); - dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi); - dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi); - double mglat = lat + dlat; - double mglng = lng + dlng; - return new double[] { lng * 2 - mglng, lat * 2 - mglat }; - } - - /** - * 纬度转换 - * - * @param lng - * @param lat - * @return - */ - public static double transformlat(double lng, double lat) { - double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng)); - ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0; - ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0; - ret += (160.0 * Math.sin(lat / 12.0 * pi) + 320 * Math.sin(lat * pi / 30.0)) * 2.0 / 3.0; - return ret; - } - - /** - * 经度转换 - * - * @param lng - * @param lat - * @return - */ - public static double transformlng(double lng, double lat) { - double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng)); - ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0; - ret += (20.0 * Math.sin(lng * pi) + 40.0 * Math.sin(lng / 3.0 * pi)) * 2.0 / 3.0; - ret += (150.0 * Math.sin(lng / 12.0 * pi) + 300.0 * Math.sin(lng / 30.0 * pi)) * 2.0 / 3.0; - return ret; - } - - /** - * 判断是否在国内,不在国内不做偏移 - * - * @param lng - * @param lat - * @return - */ - public static boolean out_of_china(double lng, double lat) { - if (lng < 72.004 || lng > 137.8347) { - return true; - } else if (lat < 0.8293 || lat > 55.8271) { - return true; - } - return false; - } -} diff --git a/src/test/java/me/demo/util/geo/test/CoordinateConverterTest.java b/src/test/java/me/demo/util/geo/test/CoordinateConverterTest.java new file mode 100644 index 0000000..0597c41 --- /dev/null +++ b/src/test/java/me/demo/util/geo/test/CoordinateConverterTest.java @@ -0,0 +1,128 @@ +package me.demo.util.geo.test; + +import org.junit.Test; + +import java.util.Arrays; +import java.util.Locale; + +import static com.github.ipcjs.coordtransform.CoordinateTransformUtil.bd09ToGcj02; +import static com.github.ipcjs.coordtransform.CoordinateTransformUtil.bd09ToWgs84; +import static com.github.ipcjs.coordtransform.CoordinateTransformUtil.gcj02ToBd09; +import static com.github.ipcjs.coordtransform.CoordinateTransformUtil.gcj02ToWgs84; +import static com.github.ipcjs.coordtransform.CoordinateTransformUtil.wgs84ToBd09; +import static com.github.ipcjs.coordtransform.CoordinateTransformUtil.wgs84ToGcj02; +import static org.junit.Assert.assertArrayEquals; + +/** + * Created by ipcjs on 2017/9/28. + */ + +public class CoordinateConverterTest { + + public static void p(Object... objs) { + System.out.println(Arrays.deepToString(objs)); + } + + public static String toUrl(LatLng location) { + String coordTypeStr; + switch (location.getCoordType()) { + default: + case WGS84: + coordTypeStr = "wgs84"; + break; + case GCJ02: + coordTypeStr = "gcj02"; + break; + case BD09: + coordTypeStr = "bd09ll"; + break; + } + return String.format(Locale.getDefault(), + "http://api.map.baidu.com/marker?location=%1$s,%2$s&title=%3$s&content=beijing&output=html&coord_type=%4$s&src=test", + location.getLat(), + location.getLng(), + location.getCoordType(), + coordTypeStr + ); + } + + @Test + public void testWgs84AndGcj02() { + // wgs84 桃园路 + double lat = 22.535697; + double lng = 113.915547; + + p("wgs84 <-> gcj02"); + double[] gcj02 = wgs84ToGcj02(lng, lat); + double[] wgs84 = gcj02ToWgs84(gcj02[0], gcj02[1]); + p(toUrl(LatLng.from(CoordType.WGS84, lat, lng))); + p(toUrl(LatLng.from(CoordType.GCJ02, gcj02[1], gcj02[0]))); // 没有偏移 + p(toUrl(LatLng.from(CoordType.WGS84, wgs84[1], wgs84[0]))); // 没有偏移 + assertArrayEquals(new double[]{lng, lat}, wgs84, 1e-5); + } + + @Test + public void testWgs84AndBd09() { + // wgs84 桃园路 + double lat = 22.535697; + double lng = 113.915547; + + p("wgs84 <-> bd09"); + double[] bd09_1 = wgs84ToBd09(lng, lat); + double[] wgs84_4 = bd09ToWgs84(bd09_1[0], bd09_1[1]); + p(toUrl(LatLng.from(CoordType.WGS84, lat, lng))); + p(toUrl(LatLng.from(CoordType.BD09, bd09_1[1], bd09_1[0]))); // 没有偏移 + p(toUrl(LatLng.from(CoordType.WGS84, wgs84_4[1], wgs84_4[0]))); // 没有偏移 + assertArrayEquals(new double[]{lng, lat}, wgs84_4, 1e-5); + } + + @Test + public void testBd09AndGcj02() { + // bd09ll 116.403959,39.915132, 天安门 + double lat = 39.915132; + double lng = 116.403959; + + p("bd09 <-> gcj02"); + double[] gcj02_2 = bd09ToGcj02(lng, lat); + double[] bd09_3 = gcj02ToBd09(gcj02_2[0], gcj02_2[1]); + p(toUrl(LatLng.from(CoordType.BD09, lat, lng))); + p(toUrl(LatLng.from(CoordType.GCJ02, gcj02_2[1], gcj02_2[0]))); // 没有偏移 + p(toUrl(LatLng.from(CoordType.BD09, bd09_3[1], bd09_3[0]))); // 没有偏移 + assertArrayEquals(new double[]{lng, lat}, bd09_3, 1e-5); + } + + public enum CoordType { + BD09, GCJ02, WGS84 + } + + public static class LatLng { + + private final CoordType coordType; + + private final double lat; + + private final double lng; + + public LatLng(CoordType coordType, double lat, double lng) { + this.coordType = coordType; + this.lat = lat; + this.lng = lng; + } + + public static LatLng from(CoordType coordType, double lat, double lnt) { + return new LatLng(coordType, lat, lnt); + } + + public CoordType getCoordType() { + return coordType; + } + + public double getLat() { + return lat; + } + + public double getLng() { + return lng; + } + } +} diff --git a/src/test/java/me/demo/util/geo/test/CoordinateTransformUtilTest.java b/src/test/java/me/demo/util/geo/test/CoordinateTransformUtilTest.java index 0641e51..da3568b 100644 --- a/src/test/java/me/demo/util/geo/test/CoordinateTransformUtilTest.java +++ b/src/test/java/me/demo/util/geo/test/CoordinateTransformUtilTest.java @@ -1,24 +1,41 @@ package me.demo.util.geo.test; -import me.demo.util.geo.CoordinateTransformUtil; +import com.github.ipcjs.coordtransform.CoordinateTransformUtil; import org.junit.Test; +import static org.junit.Assert.assertArrayEquals; + /** * 坐标转换-测试用例 */ public class CoordinateTransformUtilTest { - @Test - public void test_bd09towgs84() { - // 百度坐标转WGS84 - double[] wgs84 = CoordinateTransformUtil.bd09towgs84(120.698967, 31.324966); - System.out.println(wgs84[0] + "," + wgs84[1]); - } - - @Test - public void test_wgs84tobd09() { - // WGS84转百度坐标 - double[] bd09 = CoordinateTransformUtil.wgs84tobd09(118.3013077, 32.2719040); - System.out.println(bd09[0] + "," + bd09[1]); - } + + @Test + public void test_bd09ToWgs84() { + // 百度坐标转WGS84 + double[] wgs84 = CoordinateTransformUtil.bd09ToWgs84(120.698967, 31.324966); + assertArrayEquals(new double[]{120.68817433685123, 31.320969743354603}, wgs84, 0); + } + + @Test + public void test_wgs84ToBd09() { + // WGS84转百度坐标 + double[] bd09 = CoordinateTransformUtil.wgs84ToBd09(118.3013077, 32.2719040); + assertArrayEquals(new double[]{118.31309502519456, 32.27614034221775}, bd09, 0); + } + + @Test + public void testMalaysiaIsNotInChina() { + double[] wgs84 = {110.32592, 1.46692}; + double[] gcj02 = CoordinateTransformUtil.wgs84ToGcj02(wgs84[0], wgs84[1]); + assertArrayEquals(gcj02, wgs84, 0); + } + + @Test + public void testHongKongIsNotInChina() { + double[] HONG_KONG = {114.158321, 22.28451}; + double[] gcj02 = CoordinateTransformUtil.wgs84ToGcj02(HONG_KONG[0], HONG_KONG[1]); + assertArrayEquals(HONG_KONG, gcj02, 0); + } }