├── .gitignore ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── majidsoft │ │ └── navigationsample │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── majidsoft │ │ │ └── navigationsample │ │ │ └── MainActivity.java │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── majidsoft │ └── navigationsample │ └── ExampleUnitTest.java ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── navigation1.jpg ├── navigationlibrary ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── majidsoft │ │ └── navigationlibrary │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── majidsoft │ │ │ └── navigationlibrary │ │ │ ├── CustomJsonRequest.java │ │ │ ├── LinearRegression.java │ │ │ ├── MapUtil.java │ │ │ ├── NavigationFragment.java │ │ │ └── Point.java │ └── res │ │ ├── drawable │ │ ├── dot.png │ │ └── gps_indicator.png │ │ ├── layout │ │ └── fragment_navigation.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── majidsoft │ └── navigationlibrary │ └── ExampleUnitTest.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Navigation 2 | Car navigation with google map. 3 | Routing from current location to specified destination. 4 | 5 | ![alt text](navigation1.jpg) 6 | 7 | ### Getting Started 8 | Download Navigationlibrary from github and add this library to your project. 9 | 10 | ### How to use 11 | Create new activity and add below segment code to onCreate() method 12 | 13 | ``` 14 | FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 15 | transaction.replace(R.id.container, NavigationFragment.newInstance(35.756983, 51.362269)); 16 | transaction.commit(); 17 | ``` 18 | 19 | ### License 20 | Copyright 2016 Majid Mohammadnejad 21 | 22 | Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at 23 | 24 | ``` 25 | http://www.apache.org/licenses/LICENSE-2.0 26 | ``` 27 | 28 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 29 | 30 | ### Author 31 | Majid Mohammadnejad 32 | 33 | Email: m.mohammadnejad@digikala.com 34 | 35 | Github: https://github.com/mohammadnejad 36 | 37 | 38 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.2" 6 | defaultConfig { 7 | applicationId "com.majidsoft.navigationsample" 8 | minSdkVersion 9 9 | targetSdkVersion 25 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(include: ['*.jar'], dir: 'libs') 24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 25 | exclude group: 'com.android.support', module: 'support-annotations' 26 | }) 27 | compile 'com.android.support:appcompat-v7:25.1.0' 28 | testCompile 'junit:junit:4.12' 29 | compile project(':navigationlibrary') 30 | } 31 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/majid/android-studiov2.2/android-sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/majidsoft/navigationsample/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.majidsoft.navigationsample; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.majidsoft.navigationsample", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 12 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /app/src/main/java/com/majidsoft/navigationsample/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.majidsoft.navigationsample; 2 | 3 | import android.support.v4.app.Fragment; 4 | import android.support.v4.app.FragmentTransaction; 5 | import android.support.v7.app.AppCompatActivity; 6 | import android.os.Bundle; 7 | 8 | import com.majidsoft.navigationlibrary.NavigationFragment; 9 | 10 | public class MainActivity extends AppCompatActivity { 11 | 12 | @Override 13 | protected void onCreate(Bundle savedInstanceState) { 14 | super.onCreate(savedInstanceState); 15 | setContentView(R.layout.activity_main); 16 | 17 | changeFragment(NavigationFragment.newInstance(35.756983, 51.362269)); 18 | } 19 | 20 | private void changeFragment(Fragment fragment) { 21 | FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); 22 | transaction.replace(R.id.container, fragment); 23 | transaction.commit(); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 13 | 14 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | NavigationSample 3 | 4 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /app/src/test/java/com/majidsoft/navigationsample/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.majidsoft.navigationsample; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.2.0' 9 | 10 | // NOTE: Do not place your application dependencies here; they belong 11 | // in the individual module build.gradle files 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | jcenter() 18 | } 19 | } 20 | 21 | task clean(type: Delete) { 22 | delete rootProject.buildDir 23 | } 24 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-2.14.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /navigation1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/navigation1.jpg -------------------------------------------------------------------------------- /navigationlibrary/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /navigationlibrary/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.2" 6 | 7 | defaultConfig { 8 | minSdkVersion 9 9 | targetSdkVersion 25 10 | versionCode 1 11 | versionName "1.0" 12 | 13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 14 | 15 | } 16 | buildTypes { 17 | release { 18 | minifyEnabled false 19 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 20 | } 21 | } 22 | } 23 | 24 | dependencies { 25 | compile fileTree(dir: 'libs', include: ['*.jar']) 26 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 27 | exclude group: 'com.android.support', module: 'support-annotations' 28 | }) 29 | compile 'com.android.support:appcompat-v7:25.1.0' 30 | compile 'com.android.support:support-v4:25.1.0' 31 | compile 'com.google.android.gms:play-services-maps:9.6.1' 32 | compile 'com.google.android.gms:play-services-location:9.6.1' 33 | compile 'com.google.maps.android:android-maps-utils:0.4.3' 34 | compile 'com.android.volley:volley:1.0.0' 35 | testCompile 'junit:junit:4.12' 36 | } 37 | -------------------------------------------------------------------------------- /navigationlibrary/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in /home/majid/android-studiov2.2/android-sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /navigationlibrary/src/androidTest/java/com/majidsoft/navigationlibrary/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.majidsoft.navigationlibrary; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.majidsoft.navigationlibrary", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /navigationlibrary/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /navigationlibrary/src/main/java/com/majidsoft/navigationlibrary/CustomJsonRequest.java: -------------------------------------------------------------------------------- 1 | package com.majidsoft.navigationlibrary; 2 | 3 | import com.android.volley.Response; 4 | import com.android.volley.toolbox.JsonObjectRequest; 5 | 6 | import org.json.JSONObject; 7 | 8 | /** 9 | * Created by majid on 7/13/16. 10 | */ 11 | 12 | public class CustomJsonRequest extends JsonObjectRequest { 13 | 14 | public CustomJsonRequest(int method, String url, JSONObject jsonRequest, 15 | Response.Listener listener, Response.ErrorListener errorListener) { 16 | super(method, url, jsonRequest, listener, errorListener); 17 | } 18 | 19 | private Priority mPriority; 20 | 21 | public void setPriority(Priority priority) { 22 | mPriority = priority; 23 | } 24 | 25 | @Override 26 | public Priority getPriority() { 27 | return mPriority == null ? Priority.NORMAL : mPriority; 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /navigationlibrary/src/main/java/com/majidsoft/navigationlibrary/LinearRegression.java: -------------------------------------------------------------------------------- 1 | package com.majidsoft.navigationlibrary; 2 | 3 | /** 4 | * The LinearRegression class calculate point p that project in line with two points 5 | * 6 | * @author Majid Mohammadnejad 7 | * @version 1.0 8 | * @email : majidrasht@gmail.com 9 | * @since 10/8/16 10 | */ 11 | 12 | public class LinearRegression { 13 | 14 | public Point getProjectedPointOnLine(Point v1, Point v2, Point p) { 15 | 16 | // get dot product of e1, e2 17 | Point e1 = new Point(v2.x - v1.x, v2.y - v1.y); 18 | Point e2 = new Point(p.x - v1.x, p.y - v1.y); 19 | double valDp = dotProduct(e1, e2); 20 | 21 | // get length of vectors 22 | double lenLineE1 = Math.sqrt(e1.x * e1.x + e1.y * e1.y); 23 | double lenLineE2 = Math.sqrt(e2.x * e2.x + e2.y * e2.y); 24 | double cos = valDp / (lenLineE1 * lenLineE2); 25 | 26 | // length of v1P' 27 | double projLenOfLine = cos * lenLineE2; 28 | Point pp = new Point((v1.x + (projLenOfLine * e1.x) / lenLineE1), 29 | (v1.y + (projLenOfLine * e1.y) / lenLineE1)); 30 | 31 | return pp; 32 | } 33 | 34 | private double dotProduct(Point p1, Point p2) { 35 | return p1.x * p2.x + p1.y * p2.y; 36 | } 37 | 38 | public boolean checkPointInsideLine(Point startPoint, Point endPoint, Point pointInsideLine) { 39 | double maxX; 40 | double minX; 41 | double maxY; 42 | double minY; 43 | 44 | if (startPoint.x >= endPoint.x) { 45 | maxX = startPoint.x; 46 | minX = endPoint.x; 47 | } else { 48 | maxX = endPoint.x; 49 | minX = startPoint.x; 50 | } 51 | 52 | if (startPoint.y >= endPoint.y) { 53 | maxY = startPoint.y; 54 | minY = endPoint.y; 55 | } else { 56 | maxY = endPoint.y; 57 | minY = startPoint.y; 58 | } 59 | 60 | if ((pointInsideLine.x > minX && pointInsideLine.x < maxX) && (pointInsideLine.y > minY && pointInsideLine.y < maxY)) { 61 | return true; 62 | } 63 | 64 | return false; 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /navigationlibrary/src/main/java/com/majidsoft/navigationlibrary/MapUtil.java: -------------------------------------------------------------------------------- 1 | package com.majidsoft.navigationlibrary; 2 | 3 | import android.util.Log; 4 | 5 | import com.google.android.gms.maps.model.LatLng; 6 | 7 | import java.text.DecimalFormat; 8 | import java.util.List; 9 | 10 | /** 11 | * The MapUtil class hold logical functions for google map 12 | * 13 | * @author Majid Mohammadnejad 14 | * @version 1.0 15 | * @email : majidrasht@gmail.com 16 | * @since 10/9/16 17 | */ 18 | 19 | public class MapUtil { 20 | 21 | private LinearRegression regression = new LinearRegression(); 22 | 23 | /** 24 | * This method calculate distance between two geographical points 25 | * 26 | * @param StartP 27 | * @param EndP 28 | * @return 29 | */ 30 | public double calculationByDistance(LatLng StartP, LatLng EndP) { 31 | 32 | int Radius = 6371;// radius of earth in Km 33 | double lat1 = StartP.latitude; 34 | double lat2 = EndP.latitude; 35 | 36 | double lon1 = StartP.longitude; 37 | double lon2 = EndP.longitude; 38 | 39 | double dLat = Math.toRadians(lat2 - lat1); 40 | double dLon = Math.toRadians(lon2 - lon1); 41 | 42 | double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) 43 | + Math.cos(Math.toRadians(lat1)) 44 | * Math.cos(Math.toRadians(lat2)) * Math.sin(dLon / 2) 45 | * Math.sin(dLon / 2); 46 | 47 | double c = 2 * Math.asin(Math.sqrt(a)); 48 | 49 | double valueResult = Radius * c; 50 | 51 | double km = valueResult / 1; 52 | 53 | DecimalFormat newFormat = new DecimalFormat("####"); 54 | 55 | int kmInDec = Integer.valueOf(newFormat.format(km)); 56 | 57 | double meter = valueResult % 1000; 58 | 59 | int meterInDec = Integer.valueOf(newFormat.format(meter)); 60 | 61 | Log.i("Radius Value", "" + valueResult + " KM " + kmInDec 62 | + " Meter " + meterInDec); 63 | 64 | return Radius * c; 65 | } 66 | 67 | /** 68 | * This method calculate min distance between gps location and list of locations and return member of list that is min distance 69 | * 70 | * @param gps 71 | * @return 72 | */ 73 | public int minDistanceBetweenListAndGPSMember(List latLngs, LatLng gps) { 74 | double distanceThreshold = 2; //threshold for min distance 75 | int minMember = 0; 76 | double minDistance = Double.MAX_VALUE; 77 | Double distance; 78 | 79 | for (int i = 0; i < latLngs.size(); i++) { 80 | distance = calculationByDistance(gps, latLngs.get(i)); 81 | 82 | Log.i("distance", "dis = " + distance); 83 | 84 | if (distance < minDistance) { 85 | minDistance = distance; 86 | minMember = i; 87 | } 88 | } 89 | 90 | if (minDistance > distanceThreshold) 91 | return -1; 92 | 93 | return minMember; 94 | } 95 | 96 | /** 97 | * This method calculate point p that is inside the line 98 | * 99 | * @param latLngs 100 | * @param gps 101 | * @return 102 | */ 103 | 104 | public LatLng getProjectLocation(List latLngs, LatLng gps) { 105 | 106 | LatLng firstLocation; 107 | LatLng secondLocation; 108 | Point startPoint; 109 | Point endPoint; 110 | Point gpsPoint; 111 | Point pointInsideLine; 112 | int nearMember; 113 | 114 | nearMember = minDistanceBetweenListAndGPSMember(latLngs, gps); 115 | 116 | //if min distance greater than threshold distance 117 | if (nearMember == -1) { 118 | return gps; 119 | } 120 | 121 | if (nearMember == 0) { 122 | firstLocation = latLngs.get(nearMember); 123 | secondLocation = latLngs.get(nearMember + 1); 124 | } else { 125 | firstLocation = latLngs.get(nearMember - 1); 126 | secondLocation = latLngs.get(nearMember); 127 | } 128 | 129 | startPoint = new Point(firstLocation.latitude, firstLocation.longitude); 130 | endPoint = new Point(secondLocation.latitude, secondLocation.longitude); 131 | gpsPoint = new Point(gps.latitude, gps.longitude); 132 | 133 | pointInsideLine = regression.getProjectedPointOnLine(startPoint, endPoint, gpsPoint); 134 | 135 | if (nearMember == 0 || nearMember == (latLngs.size() - 1)) 136 | return new LatLng(pointInsideLine.x, pointInsideLine.y); 137 | 138 | if (regression.checkPointInsideLine(startPoint, endPoint, pointInsideLine)) { 139 | return new LatLng(pointInsideLine.x, pointInsideLine.y); 140 | } else { 141 | firstLocation = latLngs.get(nearMember); 142 | secondLocation = latLngs.get(nearMember + 1); 143 | 144 | startPoint = new Point(firstLocation.latitude, firstLocation.longitude); 145 | endPoint = new Point(secondLocation.latitude, secondLocation.longitude); 146 | gpsPoint = new Point(gps.latitude, gps.longitude); 147 | 148 | pointInsideLine = regression.getProjectedPointOnLine(startPoint, endPoint, gpsPoint); 149 | 150 | return new LatLng(pointInsideLine.x, pointInsideLine.y); 151 | } 152 | 153 | } 154 | 155 | } -------------------------------------------------------------------------------- /navigationlibrary/src/main/java/com/majidsoft/navigationlibrary/NavigationFragment.java: -------------------------------------------------------------------------------- 1 | package com.majidsoft.navigationlibrary; 2 | 3 | import android.Manifest; 4 | import android.content.Context; 5 | import android.content.pm.PackageManager; 6 | import android.graphics.Color; 7 | import android.hardware.GeomagneticField; 8 | import android.hardware.Sensor; 9 | import android.hardware.SensorEvent; 10 | import android.hardware.SensorEventListener; 11 | import android.hardware.SensorManager; 12 | import android.location.Location; 13 | import android.os.AsyncTask; 14 | import android.os.Bundle; 15 | import android.support.annotation.NonNull; 16 | import android.support.annotation.Nullable; 17 | import android.support.v4.app.ActivityCompat; 18 | import android.support.v4.app.Fragment; 19 | import android.util.Log; 20 | import android.view.LayoutInflater; 21 | import android.view.View; 22 | import android.view.ViewGroup; 23 | 24 | import com.android.volley.Request; 25 | import com.android.volley.RequestQueue; 26 | import com.android.volley.Response; 27 | import com.android.volley.VolleyError; 28 | import com.android.volley.toolbox.Volley; 29 | import com.google.android.gms.common.ConnectionResult; 30 | import com.google.android.gms.common.api.GoogleApiClient; 31 | import com.google.android.gms.location.LocationListener; 32 | import com.google.android.gms.location.LocationRequest; 33 | import com.google.android.gms.location.LocationServices; 34 | import com.google.android.gms.maps.CameraUpdateFactory; 35 | import com.google.android.gms.maps.GoogleMap; 36 | import com.google.android.gms.maps.MapView; 37 | import com.google.android.gms.maps.OnMapReadyCallback; 38 | import com.google.android.gms.maps.model.BitmapDescriptorFactory; 39 | import com.google.android.gms.maps.model.CameraPosition; 40 | import com.google.android.gms.maps.model.LatLng; 41 | import com.google.android.gms.maps.model.Marker; 42 | import com.google.android.gms.maps.model.MarkerOptions; 43 | import com.google.android.gms.maps.model.Polyline; 44 | import com.google.android.gms.maps.model.PolylineOptions; 45 | 46 | import org.json.JSONArray; 47 | import org.json.JSONException; 48 | import org.json.JSONObject; 49 | 50 | import java.text.DateFormat; 51 | import java.util.ArrayList; 52 | import java.util.Date; 53 | import java.util.List; 54 | 55 | /** 56 | * NavigationFragment 57 | * 58 | * @author Majid Mohammadnejad 59 | * @version 1.0 60 | * @email : majidrasht@gmail.com 61 | * @since 10/9/16 62 | */ 63 | public class NavigationFragment extends Fragment implements 64 | LocationListener, 65 | SensorEventListener, 66 | GoogleApiClient.ConnectionCallbacks, 67 | GoogleApiClient.OnConnectionFailedListener { 68 | 69 | private static final String TAG = NavigationFragment.class.getName(); 70 | private static final String ARG_PARAM_LAT = "lat"; 71 | private static final String ARG_PARAM2_LNG = "lng"; 72 | 73 | private LatLng destLocation; 74 | 75 | private RequestQueue mRequestQueue; 76 | 77 | private static final String MAPS_DIRECTIONS = "http://maps.googleapis.com/maps/api/directions/json"; 78 | private Context instance = null; 79 | 80 | private static final float LEVEL_ZOOM = 17f; 81 | private static final float LEVEL_TILT = 30f; 82 | 83 | private static final int REQUEST_LOCATION_ = 1; 84 | private static String[] PERMISSIONS_Location = { 85 | Manifest.permission.ACCESS_FINE_LOCATION, 86 | Manifest.permission.ACCESS_COARSE_LOCATION 87 | }; 88 | 89 | private GoogleApiClient mGoogleApiClient; 90 | private LocationRequest mLocationRequest; 91 | private MapView mapView; 92 | private GoogleMap mGoogleMap; 93 | private LatLng source; 94 | private LatLng destination; 95 | private boolean firstCurrentLocationFound = false; 96 | 97 | private float mDeclination; 98 | private float lastBearing = 0f; 99 | private long lastUpdateTime; 100 | 101 | private SensorManager mSensorManager; 102 | private Sensor mAccelerometer; 103 | 104 | private float[] mRotationMatrix = new float[16]; 105 | private LatLng currentLocation; 106 | private Marker currentMarker; 107 | private Location mLastLocation; 108 | private MarkerOptions currentMarkerOptions; 109 | 110 | private boolean routingFinished; 111 | private List latLngs; 112 | 113 | private MapUtil mapUtil; 114 | 115 | public NavigationFragment() { 116 | // Required empty public constructor 117 | } 118 | 119 | public static NavigationFragment newInstance(double lat, double lng) { 120 | NavigationFragment fragment = new NavigationFragment(); 121 | Bundle args = new Bundle(); 122 | args.putDouble(ARG_PARAM_LAT, lat); 123 | args.putDouble(ARG_PARAM2_LNG, lng); 124 | fragment.setArguments(args); 125 | return fragment; 126 | } 127 | 128 | //*************************** Android Fragment life cycle*************************************** 129 | @Override 130 | public void onCreate(Bundle savedInstanceState) { 131 | super.onCreate(savedInstanceState); 132 | Log.i(TAG, "onCreate"); 133 | instance = getContext(); 134 | 135 | if (getArguments() != null) { 136 | double destLat = getArguments().getDouble(ARG_PARAM_LAT); 137 | double destLng = getArguments().getDouble(ARG_PARAM2_LNG); 138 | destLocation = new LatLng(destLat, destLng); 139 | } 140 | 141 | mapUtil = new MapUtil(); 142 | } 143 | 144 | @Override 145 | public View onCreateView(LayoutInflater inflater, ViewGroup container, 146 | Bundle savedInstanceState) { 147 | // Inflate the layout for this fragment 148 | Log.i(TAG, "onCreateView"); 149 | return inflater.inflate(R.layout.fragment_navigation, container, false); 150 | } 151 | 152 | @Override 153 | public void onViewCreated(View view, Bundle savedInstanceState) { 154 | super.onViewCreated(view, savedInstanceState); 155 | Log.i(TAG, "onViewCreated"); 156 | 157 | mapView = (MapView) view.findViewById(R.id.mapView); 158 | init(); 159 | } 160 | 161 | @Override 162 | public void onResume() { 163 | super.onResume(); 164 | Log.i(TAG, "onResume"); 165 | 166 | if (mGoogleApiClient.isConnected()) 167 | startLocationUpdates(); 168 | } 169 | 170 | @Override 171 | public void onStart() { 172 | super.onStart(); 173 | Log.i(TAG, "onStart"); 174 | 175 | createLocationRequest(); 176 | mGoogleApiClient.connect(); 177 | } 178 | 179 | @Override 180 | public void onStop() { 181 | super.onStop(); 182 | Log.i(TAG, "onStop"); 183 | 184 | if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { 185 | mGoogleApiClient.disconnect(); 186 | } 187 | 188 | if (mGoogleApiClient == null) 189 | stopLocationUpdates(); 190 | 191 | mapView.onStop(); 192 | } 193 | 194 | @Override 195 | public void onDestroy() { 196 | instance = null; 197 | super.onDestroy(); 198 | mSensorManager.unregisterListener(this); 199 | Log.i(TAG, "onDestroy"); 200 | } 201 | 202 | @Override 203 | public void onAttach(Context context) { 204 | super.onAttach(context); 205 | Log.i(TAG, "onAttach"); 206 | } 207 | 208 | @Override 209 | public void onDetach() { 210 | super.onDetach(); 211 | Log.i(TAG, "onDetach"); 212 | } 213 | 214 | //******************************* initial methods ********************************************** 215 | private void init() { 216 | Log.e(TAG, "onCreate -> init"); 217 | 218 | setGoogleApi(); 219 | 220 | initialMapFragment(); 221 | 222 | initialSensorManager(); 223 | } 224 | 225 | private void initialSensorManager() { 226 | mSensorManager = (SensorManager) instance.getSystemService(Context.SENSOR_SERVICE); 227 | mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR); 228 | 229 | mSensorManager.registerListener(this, mAccelerometer, SensorManager.SENSOR_DELAY_NORMAL); 230 | 231 | lastUpdateTime = System.currentTimeMillis(); 232 | } 233 | 234 | //*************************** SensorEventListener Override methods ***************************** 235 | @Override 236 | public void onSensorChanged(SensorEvent event) { 237 | if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) { 238 | // Log.i(TAG, event.sensor.getName() + ""); 239 | 240 | SensorManager.getRotationMatrixFromVector( 241 | mRotationMatrix, event.values); 242 | float[] orientation = new float[3]; 243 | SensorManager.getOrientation(mRotationMatrix, orientation); 244 | 245 | long actulTime = event.timestamp; 246 | 247 | float bearing = (float) Math.toDegrees(orientation[0]) + mDeclination; 248 | 249 | if (Math.abs(bearing - lastBearing) < 2 || Math.abs(actulTime - lastUpdateTime) < 50) { 250 | return; 251 | } 252 | 253 | lastUpdateTime = actulTime; 254 | updateCamera(bearing); 255 | } 256 | } 257 | 258 | @Override 259 | public void onAccuracyChanged(Sensor sensor, int i) { 260 | Log.e(TAG, "accuracy change : " + i + ""); 261 | } 262 | 263 | 264 | //*************************** GoogleApiClient override methods********************************** 265 | @Override 266 | public void onConnected(@Nullable Bundle bundle) { 267 | Log.i(TAG, "google client api connected"); 268 | 269 | if (ActivityCompat.checkSelfPermission(instance, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && 270 | ActivityCompat.checkSelfPermission(instance, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 271 | 272 | if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) && 273 | ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)) { 274 | } else { 275 | ActivityCompat.requestPermissions(getActivity(), 276 | PERMISSIONS_Location, 277 | REQUEST_LOCATION_); 278 | } 279 | 280 | } else { 281 | Log.i(TAG, "requestLocationUpdates"); 282 | } 283 | 284 | mLastLocation = LocationServices.FusedLocationApi.getLastLocation( 285 | mGoogleApiClient); 286 | 287 | currentMarkerOptions = new MarkerOptions(); 288 | currentMarkerOptions.title("current location'"); 289 | currentMarkerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.gps_indicator)); 290 | 291 | if (mLastLocation != null) { 292 | if (currentMarker == null) { 293 | Log.i(TAG, "add gps marker in connect"); 294 | 295 | currentMarker = mGoogleMap.addMarker(currentMarkerOptions.position( 296 | new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude())) 297 | ); 298 | } else { 299 | Log.i(TAG, "change position connect marker"); 300 | currentMarker.setPosition(new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude())); 301 | } 302 | } 303 | 304 | startLocationUpdates(); 305 | } 306 | 307 | @Override 308 | public void onConnectionSuspended(int i) { 309 | Log.i(TAG, "google client api suspended"); 310 | } 311 | 312 | @Override 313 | public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { 314 | Log.i(TAG, "google client api failed"); 315 | } 316 | 317 | //************************ Map initialize methods*********************************************** 318 | private void setGoogleApi() { 319 | mGoogleApiClient = new GoogleApiClient.Builder(instance) 320 | .addConnectionCallbacks(this) 321 | .addOnConnectionFailedListener(this) 322 | .addApi(LocationServices.API) 323 | .build(); 324 | } 325 | 326 | private void initialMapFragment() { 327 | mapView.onCreate(null); 328 | mapView.onResume(); 329 | 330 | mapView.getMapAsync(new OnMapReadyCallback() { 331 | @Override 332 | public void onMapReady(GoogleMap googleMap) { 333 | mGoogleMap = googleMap; 334 | } 335 | }); 336 | } 337 | 338 | private void initSourceLocation(Location location) { 339 | if (location != null) { 340 | source = new LatLng(location.getLatitude(), location.getLongitude()); 341 | 342 | MarkerOptions markerOptions = new MarkerOptions().position(source); 343 | markerOptions.title("source"); 344 | markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); 345 | 346 | mGoogleMap.addMarker(markerOptions); 347 | 348 | goToLocation(source.latitude, source.longitude); 349 | } 350 | } 351 | 352 | private void initDestinationLocation(LatLng location) { 353 | if (location != null) { 354 | destination = new LatLng(location.latitude, location.longitude); 355 | 356 | MarkerOptions markerOptions = new MarkerOptions().position(destination); 357 | markerOptions.title("destination"); 358 | markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)); 359 | 360 | mGoogleMap.addMarker(markerOptions); 361 | } 362 | } 363 | 364 | private void goToLocation(double lat, double lon) { 365 | CameraPosition cameraPosition = CameraPosition.builder() 366 | .target(new LatLng(lat, lon)) 367 | .zoom(LEVEL_ZOOM) 368 | .tilt(LEVEL_TILT) 369 | .build(); 370 | 371 | mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), null); 372 | } 373 | 374 | private void updateCamera(float bearing) { 375 | // Log.e(TAG, "move camera: " + bearing); 376 | lastBearing = bearing; 377 | 378 | if (mGoogleMap != null && currentLocation != null && currentLocation.longitude != 0 && currentLocation.latitude != 0) { 379 | CameraPosition oldPos = mGoogleMap.getCameraPosition(); 380 | 381 | CameraPosition pos = new CameraPosition.Builder() 382 | .target(currentLocation) 383 | .zoom(18f) 384 | .bearing(bearing) 385 | .tilt(50) 386 | .build(); 387 | 388 | mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(pos), 400, null); 389 | } 390 | } 391 | 392 | //************************* LocationListener Override method *********************************** 393 | @Override 394 | public void onLocationChanged(Location location) { 395 | Log.i(TAG, "location update : " + "lat = " + location.getLatitude() + 396 | " , lon = " + location.getLongitude() + 397 | " , accuracy = " + location.getAccuracy() + 398 | " , provider = " + location.getProvider() + 399 | " , time ; " + DateFormat.getTimeInstance().format(new Date())); 400 | 401 | currentLocation = new LatLng(location.getLatitude(), location.getLongitude()); 402 | 403 | // in route gps 404 | if (routingFinished && currentLocation.longitude != 0 && currentLocation.longitude != 0) { 405 | currentLocation = mapUtil.getProjectLocation(latLngs, currentLocation); 406 | } 407 | 408 | if (!firstCurrentLocationFound) { 409 | initSourceLocation(location); 410 | initDestinationLocation(destLocation); 411 | if (destination != null) 412 | routing(); 413 | firstCurrentLocationFound = true; 414 | } 415 | 416 | GeomagneticField field = new GeomagneticField( 417 | (float) location.getLatitude(), 418 | (float) location.getLongitude(), 419 | (float) location.getAltitude(), 420 | System.currentTimeMillis() 421 | ); 422 | 423 | // getDeclination returns degrees 424 | mDeclination = field.getDeclination(); 425 | 426 | if (firstCurrentLocationFound) { 427 | if (currentMarker != null) { 428 | Log.i(TAG, "change position marker"); 429 | 430 | currentMarker.setPosition(currentLocation); 431 | } else { 432 | Log.i(TAG, "add gps marker"); 433 | 434 | currentMarker = mGoogleMap.addMarker(currentMarkerOptions.position(currentLocation)); 435 | } 436 | } 437 | } 438 | 439 | //************************ Location request **************************************************** 440 | private void createLocationRequest() { 441 | Log.i(TAG, "create location request"); 442 | 443 | mLocationRequest = new LocationRequest(); 444 | mLocationRequest.setInterval(7000); // 10000 is normal 445 | mLocationRequest.setFastestInterval(3000); // 5000 is normal 446 | mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 447 | } 448 | 449 | private void startLocationUpdates() { 450 | Log.i(TAG, "start update location"); 451 | 452 | if (ActivityCompat.checkSelfPermission(instance, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && 453 | ActivityCompat.checkSelfPermission(instance, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 454 | 455 | if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) && 456 | ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)) { 457 | } else { 458 | ActivityCompat.requestPermissions(getActivity(), 459 | PERMISSIONS_Location, 460 | REQUEST_LOCATION_); 461 | } 462 | 463 | } else { 464 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 465 | Log.i(TAG, "requestLocationUpdates"); 466 | } 467 | } 468 | 469 | @Override 470 | public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) { 471 | switch (permsRequestCode) { 472 | case REQUEST_LOCATION_: { 473 | if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 474 | boolean locationEnabled = grantResults[0] == PackageManager.PERMISSION_GRANTED; 475 | 476 | if (ActivityCompat.checkSelfPermission(instance, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && 477 | ActivityCompat.checkSelfPermission(instance, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 478 | Log.i(TAG, "onRequestPermissionsResult : if 1"); 479 | return; 480 | } 481 | Log.i(TAG, "onRequestPermissionsResult : ok"); 482 | LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this); 483 | } else { 484 | 485 | // permission denied, boo! Disable the 486 | // functionality that depends on this permission. 487 | } 488 | return; 489 | } 490 | } 491 | 492 | } 493 | 494 | private void stopLocationUpdates() { 495 | Log.i(TAG, "stop location update"); 496 | 497 | LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); 498 | } 499 | 500 | //************************** Routing *********************************************************** 501 | private void routing() { 502 | drawDirectionRequest(source, destination); 503 | } 504 | 505 | public RequestQueue getRequestQueue() { 506 | if (mRequestQueue == null) { 507 | mRequestQueue = Volley.newRequestQueue(instance); 508 | } 509 | return mRequestQueue; 510 | } 511 | 512 | public void add(Request req) { 513 | req.setTag(TAG); 514 | getRequestQueue().add(req); 515 | } 516 | 517 | private void drawDirectionRequest(LatLng origin, LatLng destination) { 518 | CustomJsonRequest request = new CustomJsonRequest(Request.Method.GET, makeURLForDirection(origin, destination), null, 519 | 520 | new Response.Listener() { 521 | @Override 522 | public void onResponse(JSONObject response) { 523 | new DrawDirectionTask().execute(response.toString()); 524 | } 525 | }, 526 | 527 | new Response.ErrorListener() { 528 | @Override 529 | public void onErrorResponse(VolleyError error) { 530 | Log.e(TAG, "onErrorResponse: " + error.getMessage()); 531 | } 532 | } 533 | ); 534 | 535 | add(request); 536 | } 537 | 538 | public static String makeURLForDirection(LatLng origin, LatLng destination) { 539 | 540 | StringBuilder urlString = new StringBuilder(); 541 | urlString.append(MAPS_DIRECTIONS); 542 | urlString.append("?origin="); 543 | urlString.append(Double.toString(origin.latitude)); 544 | urlString.append(","); 545 | urlString.append(Double.toString(origin.longitude)); 546 | urlString.append("&destination="); 547 | urlString.append(Double.toString(destination.latitude)); 548 | urlString.append(","); 549 | urlString.append(Double.toString(destination.longitude)); 550 | urlString.append("&sensor=false&mode=driving&alternatives=true"); 551 | 552 | return urlString.toString(); 553 | } 554 | 555 | public static List decodePoly(String encoded) { 556 | 557 | List poly = new ArrayList(); 558 | int index = 0, len = encoded.length(); 559 | int lat = 0, lng = 0; 560 | 561 | while (index < len) { 562 | int b, shift = 0, result = 0; 563 | do { 564 | b = encoded.charAt(index++) - 63; 565 | result |= (b & 0x1f) << shift; 566 | shift += 5; 567 | } while (b >= 0x20); 568 | int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); 569 | lat += dlat; 570 | 571 | shift = 0; 572 | result = 0; 573 | do { 574 | b = encoded.charAt(index++) - 63; 575 | result |= (b & 0x1f) << shift; 576 | shift += 5; 577 | } while (b >= 0x20); 578 | int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); 579 | lng += dlng; 580 | 581 | LatLng p = new LatLng((((double) lat / 1E5)), 582 | (((double) lng / 1E5))); 583 | poly.add(p); 584 | } 585 | 586 | return poly; 587 | } 588 | 589 | /** 590 | * draw path from the result(json cast to string) of direction api callback used in draw direction method 591 | * 592 | * @param result 593 | */ 594 | private List parseJsonFromGoogle(String result) { 595 | List latLongs = null; 596 | try { 597 | latLongs = new ArrayList<>(); 598 | 599 | //Tranform the string into a json object 600 | final JSONObject json = new JSONObject(result); 601 | 602 | JSONArray routeArray = json.getJSONArray("routes"); 603 | JSONObject routes = routeArray.getJSONObject(0); 604 | 605 | JSONArray legsArray = routes.getJSONArray("legs"); 606 | JSONObject leg = legsArray.getJSONObject(0); 607 | JSONArray stepsArray = leg.getJSONArray("steps"); 608 | 609 | for (int j = 0; j < stepsArray.length(); j++) { 610 | JSONObject step = stepsArray.getJSONObject(j); 611 | 612 | JSONObject polyLine = step.getJSONObject("polyline"); 613 | latLongs.addAll(decodePoly(polyLine.getString("points"))); 614 | } 615 | } catch (JSONException e) { 616 | Log.e("test", e.getMessage() + ""); 617 | } 618 | 619 | return latLongs; 620 | } 621 | 622 | /** 623 | * A class to parse the Google Places in JSON format 624 | */ 625 | private class DrawDirectionTask extends AsyncTask> { 626 | // Parsing the data in non-ui thread 627 | @Override 628 | protected List doInBackground(String... jsonData) { 629 | List routes = null; 630 | 631 | try { 632 | routes = parseJsonFromGoogle(jsonData[0]); 633 | } catch (Exception e) { 634 | e.printStackTrace(); 635 | } 636 | return routes; 637 | } 638 | 639 | // Executes in UI thread, after the parsing process 640 | @Override 641 | protected void onPostExecute(List result) { 642 | latLngs = result; 643 | 644 | for (int z = 0; z < result.size() - 1; z++) { 645 | LatLng src = result.get(z); 646 | LatLng dest = result.get(z + 1); 647 | 648 | MarkerOptions markerOptions = new MarkerOptions(); 649 | markerOptions.icon(BitmapDescriptorFactory.fromResource(R.drawable.dot)); 650 | mGoogleMap.addMarker(markerOptions.position(new LatLng(src.latitude, src.longitude))); 651 | 652 | @SuppressWarnings("unused") 653 | Polyline line = mGoogleMap.addPolyline(new PolylineOptions() 654 | .add(new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude)) 655 | .width(15) 656 | .color(Color.BLUE).geodesic(true)); 657 | } 658 | 659 | routingFinished = true; 660 | } 661 | } 662 | 663 | } 664 | -------------------------------------------------------------------------------- /navigationlibrary/src/main/java/com/majidsoft/navigationlibrary/Point.java: -------------------------------------------------------------------------------- 1 | package com.majidsoft.navigationlibrary; 2 | 3 | /** 4 | * Model for Point 5 | * 6 | * @author Majid Mohammadnejad 7 | * @version 1.0 8 | * @email : majidrasht@gmail.com 9 | * @since 10/9/16 10 | */ 11 | 12 | public class Point { 13 | 14 | public double x; 15 | public double y; 16 | 17 | public Point(double x, double y) { 18 | this.x = x; 19 | this.y = y; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /navigationlibrary/src/main/res/drawable/dot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/navigationlibrary/src/main/res/drawable/dot.png -------------------------------------------------------------------------------- /navigationlibrary/src/main/res/drawable/gps_indicator.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/navigationlibrary/src/main/res/drawable/gps_indicator.png -------------------------------------------------------------------------------- /navigationlibrary/src/main/res/layout/fragment_navigation.xml: -------------------------------------------------------------------------------- 1 | 6 | 7 | 11 | 12 | 13 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /navigationlibrary/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/navigationlibrary/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /navigationlibrary/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/navigationlibrary/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /navigationlibrary/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/navigationlibrary/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /navigationlibrary/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/navigationlibrary/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /navigationlibrary/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammadnejad/navigation/d9051397aafe64bb041f6a2702738f6cadaa8c02/navigationlibrary/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /navigationlibrary/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /navigationlibrary/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | NavigationLibrary 3 | 4 | 5 | Hello blank fragment 6 | 7 | -------------------------------------------------------------------------------- /navigationlibrary/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /navigationlibrary/src/test/java/com/majidsoft/navigationlibrary/ExampleUnitTest.java: -------------------------------------------------------------------------------- 1 | package com.majidsoft.navigationlibrary; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * @see Testing documentation 11 | */ 12 | public class ExampleUnitTest { 13 | @Test 14 | public void addition_isCorrect() throws Exception { 15 | assertEquals(4, 2 + 2); 16 | } 17 | } -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':navigationlibrary' 2 | --------------------------------------------------------------------------------