Giter Club home page Giter Club logo

easywaylocation's Introduction


See 1 Available Translations ๐Ÿ‡จ๐Ÿ‡ณ


Android - EasyWayLocation

This library contains all utils related to google location. like, getting lat or long, Address and Location Setting dialog, Draw Route, etc

Android Arsenal

What's New in Ver 2.4

  • Arc Route Draw

    a. simple.

    b. animation.

  • Draw Arc route between origin and destination.

  • Now , Dev can change parameter dynamically like origin, waypoints, etc

  • Get polyline details class in arrayList and HashMap.

  • Clear Polyline by using TAG for both Arc and waypoints polylines.

  • Fix Major Crash

  • Created one track demo in sample folder for more usage Help

Demo Images and Gif:

IMages1 alt Setting IMages2 alt Setting IMages3

gif1 gif2

Prerequisites

  • Android 16

Installing

Step 1:- Add it in your root build.gradle at the end of repositories:

all projects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }
  

Step 2:- Add the dependency:

        dependencies {
            implementation 'com.github.prabhat1707:EasyWayLocation:2.4'
        }
    

Library uses java 8 bytecode, so dont forget to enable java 8 in your application's build.gradle file.

android {
    compileOptions {
        sourceCompatibility 1.8
        targetCompatibility 1.8
    }
}

Usage

If the device is running Android 6.0 or higher, and your app's target SDK is 29 or higher then first check the permission of location then call it.

Add the required permissions

For fine location (GPS location), add the following permission in your AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

For coarse location (network location), add the following permission in your AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Retrieve the location from the device

public class MainActivity extends AppCompatActivity implements Listener {
    EasyWayLocation easyWayLocation;
    private TextView location, latLong, diff;
    private Double lati, longi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //--
        easyWayLocation = new EasyWayLocation(this, false,false,this);
    }

    @Override
    public void locationOn() {
        Toast.makeText(this, "Location ON", Toast.LENGTH_SHORT).show();    
    }

   @Override
    public void currentLocation(Location location) {
        StringBuilder data = new StringBuilder();
        data.append(location.getLatitude());
        data.append(" , ");
        data.append(location.getLongitude());
        latLong.setText(data);
        getLocationDetail.getAddress(location.getLatitude(), location.getLongitude(), "xyz");
    }
    
    @Override
    public void locationCancelled() {
         Toast.makeText(this, "Location Cancelled", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case LOCATION_SETTING_REQUEST_CODE:
                easyWayLocation.onActivityResult(resultCode);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        easyWayLocation.startLocation();
    }

    @Override
    protected void onPause() {
        super.onPause();
        easyWayLocation.endUpdates();

    }
}

Location Notifier

@Override
    public void locationOn() {
        Toast.makeText(this, "Location ON", Toast.LENGTH_SHORT).show();
        
    }

    @Override
    public void  currentLocation(Location location){
       // give lat and long at every interval 
    }

    @Override
    public void locationCancelled() {
        // location not on
    }
    

Constructor options

Points to Remember

  • if you want only last location then pass it true and if false then it gives you location update as per default location request.
  • if you don't pass then it takes default location request or you can pass your's one also(see constructor 2nd).
Context context = this;
boolean requireFineGranularity = false;
new EasyWayLocation(this, requireLastLocation = false,isDebuggable = true/false,listner = this);

or

request = new LocationRequest();
request.setInterval(10000);
request.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

new EasyWayLocation(this,locationRequest = request ,  requireLastLocation = false,isDebuggable = true/false,listner = this);


Calculate distance between two points


double startLatitude = 59.95;
double startLongitude = 30.3;
double endLatitude = 44.84;
double endLongitude = -0.58;
location.calculateDistance(startLatitude, startLongitude, endLatitude, endLongitude);

// or

Point startPoint = new EasyWayLocation.Point(59.95, 30.3);
Point endPoint = new EasyWayLocation.Point(44.84, -0.58);
location.calculateDistance(startPoint, endPoint);

Update Get Address Details of location.

  • if you want an address from the current location then you need to pass key and context.
  • why I want key here if android already provides Geocoder because in some cases or some devices geocoder not work well and throws Exception, so in that case, I use google geocode API for fetch address.
  • For this, you need to implement Callback, LocationData.AddressCallBack
GetLocationDetail getLocationDetail = new GetLocationDetail(callback = this, context = this);

getLocationDetail.getAddress(location.getLatitude(), location.getLongitude(), key = "xyz");

Google Map Route

If you want to add map route feature in your apps you can use this along with this lib by adding DirectionUtil Class to make you work more easier. This is lib will help you to draw route maps between two-point LatLng along it's with waypoints.

When Your GoogleMap Ready

Make sure you enable google map and google map direction in the google developer console.

First Initialize Direction Util

wayPoints.add(LatLng(37.423669, -122.090168))
        wayPoints.add(LatLng(37.420930, -122.085362))
                val directionUtil = DirectionUtil.Builder()
                .setDirectionKey("xyz")
                        .setOrigin(LatLng(37.421481, -122.092156))
                        .setWayPoints(wayPoints)
                        .setGoogleMap(mMap)
                        .setPolyLinePrimaryColor(R.color.black)
                        .setPolyLineWidth(5)
                        .setPathAnimation(true)
                        .setCallback(this)
                        .setPolylineTag(WAY_POINT_TAG)
                        .setDestination(LatLng(37.421519, -122.086809))
                        .build()

Add below line for route draw

First call init and then drawRoute

directionUtil.initPath()
directionUtil.drawPath(WAY_POINT_TAG)

Now from v2.4 you can change origin, color etc in between path

 directionUtil.serOrigin(LatLng(driverCurrentLocation.latitude,driverCurrentLocation.longitude),wayPoints)

Add below line for Arc draw

directionUtil.drawArcDirection(LatLng(37.421481, -122.092156),LatLng(37.421519, -122.086809),0.5,ARC_POINT_TAG)

Add below line to remove polyline according to corresponding TAG

directionUtil.clearPolyline(WAY_POINT_TAG)

There are two cases in it:

  • With Animation like Uber
  • without Animation.
  1. With Animation

    • setPathAnimation = true

gif1

  1. Without Animation

    • setPathAnimation = false
    • change its color by, setPolyLinePrimaryColor() property

gif2

Callbacks

When route draw path has done then it below callback is called


override fun pathFindFinish(polyLineDetails: HashMap<String, PolyLineDataBean>) {
       for (i in polyLineDetails.keys){
           Log.v("sample",polyLineDetails[i]?.time)
       }
    }
    

here, polyLineDetails contain each polyline or route detail as time, distance and road summary.

You can also change the route animation different properties like delay, primary color, a secondary color, etc, just explore it.

Bugs, Feature requests

Found a bug? Something that's missing? Feedback is an important part of improving the project, so, please open an issue

License

Copyright (c) delight.im <[email protected]>

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

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable la
w 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.

easywaylocation's People

Contributors

arta666 avatar babar-bashir avatar prabhat1707 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

easywaylocation's Issues

New Icon

Hi, @prabhat1707 I am a graphic designer, I want to help others in graphic design.
sorry for the closed issues. I accidentally clicked on it.
After I reviewed your project, you have no logo on this project. Therefore I want to contribute to this project by creating a new icon / logo. what do you think? you want it?

New Logo

Hi, @prabhat1707 I am a graphic designer, I want to help others in graphic design.

After I reviewed your project, you have no logo on this project. Therefore I want to contribute to this project by creating a new icon / logo. what do you think? you want it?

Work in Background

Is this library work in background even application not available in recent screen.
i need to get locaton always get from application even app killed.
Please responde @prabhat1707

Thank You

Not working:(((

override fun locationCancelled() {

}

override fun locationOn() {
}

override fun currentLocation(location: Location?) {

    data.append(location!!.latitude)
    data.append(" , ")
    data.append(location!!.longitude)
    lati = location.latitude
    longi = location.longitude
    Log.e("lat", lati.toString() + " " + longi)
    getLocationDetail!!.getAddress(location.latitude, location.longitude, "xyz")
}

override fun locationData(locationData: LocationData?) {
    Log.e("city", locationData?.city)
    binding.locationtxt.text = locationData?.city + " " + locationData?.country
}

fun permissionIsGranted(): Boolean {
    val permissionState = ActivityCompat.checkSelfPermission(
        this,
        Manifest.permission.ACCESS_COARSE_LOCATION
    )
    return permissionState == PackageManager.PERMISSION_GRANTED
}

private fun doLocationWork() {
    easyWayLocation.startLocation()
}

override fun onActivityResult(
    requestCode: Int,
    resultCode: Int,
    @Nullable data: Intent?
) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == LOCATION_SETTING_REQUEST_CODE) {
        easyWayLocation.onActivityResult(resultCode)
    }
}

private fun hideKeyboard() {
    // Check if no view has focus:v
    val view = currentFocus
    if (view != null) {
        val inputManager =
            getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        inputManager.hideSoftInputFromWindow(
            view.windowToken,
            InputMethodManager.HIDE_NOT_ALWAYS
        )
    }
}

override fun onPause() {
    super.onPause()
    easyWayLocation.endUpdates()
}

init{
getLocationDetail = GetLocationDetail(this, this)
easyWayLocation = EasyWayLocation(this, false, this)
if (permissionIsGranted()) {
doLocationWork()
} else {
// Permission not granted, ask for it
}
}
}

Current Address 0.0 0.0

Hi,
thanks for this library dear.
i want use your library but when run application show me Current Address 0.0 0.0
and not show me my address info!

how can i fix it?

exception onResume

@Override
protected void onResume() {
    super.onResume();
    easyWayLocation.startLocation();  // here is exception
}

Da un error con algunas direcciones

2023-03-28 10:49:13.024 24616-24616/com.carlosvicente.uberkotlin E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.carlosvicente.uberkotlin, PID: 24616
java.lang.NullPointerException: Attempt to read from field 'double com.google.android.gms.maps.model.LatLng.latitude' on a null object reference
at com.example.easywaylocation.draw_path.RouteEvaluator.evaluate(RouteEvaluator.java:11)
at com.example.easywaylocation.draw_path.RouteEvaluator.evaluate(RouteEvaluator.java:8)
at android.animation.KeyframeSet.getValue(KeyframeSet.java:202)
at android.animation.PropertyValuesHolder.calculateValue(PropertyValuesHolder.java:1017)
at android.animation.ValueAnimator.animateValue(ValueAnimator.java:1561)
at android.animation.ObjectAnimator.animateValue(ObjectAnimator.java:987)
at android.animation.ValueAnimator.setCurrentFraction(ValueAnimator.java:692)
at android.animation.ValueAnimator.start(ValueAnimator.java:1089)
at android.animation.ValueAnimator.start(ValueAnimator.java:1106)
at android.animation.ObjectAnimator.start(ObjectAnimator.java:852)
at android.animation.ValueAnimator.startWithoutPulsing(ValueAnimator.java:1099)
at android.animation.AnimatorSet.handleAnimationEvents(AnimatorSet.java:1149)
at android.animation.AnimatorSet.doAnimationFrame(AnimatorSet.java:1053)
at android.animation.AnimationHandler.doAnimationFrame(AnimationHandler.java:146)
at android.animation.AnimationHandler.access$100(AnimationHandler.java:37)
at android.animation.AnimationHandler$1.doFrame(AnimationHandler.java:54)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1035)
at android.view.Choreographer.doCallbacks(Choreographer.java:845)
at android.view.Choreographer.doFrame(Choreographer.java:775)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1022)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)

Additional context

private fun easyDrawRoute() {

    if (originLatLng != null && destinationLatLng != null && originLatLng!!.latitude != 0.0 && originLatLng!!.longitude != 0.0 && destinationLatLng!!.latitude != 0.0 && destinationLatLng!!.longitude != 0.0) {
    wayPoints.add(originLatLng!!)
        Log.d("PLACESTRIP", "easyDrawRoute:$destinationLatLng Y ${destinationLatLng!!.latitude} ")
        Log.d("PLACESTRIP", "wayPoints:$wayPoints Y $googleMap ")
    wayPoints.add(destinationLatLng!!)
    directionUtil = DirectionUtil.Builder()
        .setDirectionKey(resources.getString(R.string.google_maps_key))
        .setOrigin(originLatLng!!)
        .setWayPoints(wayPoints)
        .setGoogleMap(googleMap!!)
        .setPolyLinePrimaryColor(R.color.green)
        .setPolyLineWidth(15)
        .setPathAnimation(true)
        .setCallback(this)
        .setDestination(destinationLatLng!!)
        .build()

    directionUtil.initPath()
    }

}

polyline

How can I change the size of the polyline when the origin coordinates change? without having to delete it and redo it?

Update play-services-location to 21 make the lib crash

If you update

implementation 'com.google.android.gms:play-services-location:20.0.0'

to

implementation 'com.google.android.gms:play-services-location:21.0.0'

The lib crash on checkLocationSetting(), specifically:

SettingsClient client = LocationServices.getSettingsClient(context);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

when executing client.checkLocationSettings this exception occurs:

Found interface com.google.android.gms.location.SettingsClient, but class was expected (declaration of 'com.google.android.gms.location.SettingsClient'

With version 20 it works fine

getting exception

java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/gms/common/api/Api$zzf;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.