9

I am trying to draw path between two latitude,longitude. Here is my MapsActivity.java.

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment)
getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        find = (Button) findViewById(R.id.btnFindPath);
        or = (EditText) findViewById(R.id.etOrigin);
        dest = (EditText) findViewById(R.id.etDestination);


        find.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View view) {

            sendRequest();

            }
        });
    }

    public void sendRequest(){

        String origin = or.getText().toString();
        String destination = dest.getText().toString();

        if(origin.isEmpty()){
            Toast.makeText(this,"Please Enter the Origin" , Toast.LENGTH_SHORT).show();
        }

        if(destination.isEmpty()){
            Toast.makeText(this,"Please Enter the Destination" , Toast.LENGTH_SHORT).show();
        }

        DirectionFinder directionFinder = new DirectionFinder(origin, destination);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        /*double array [] = {44.968046 ,-94.420307 ,44.33328,-89.132008, 33.755787,-116.359998,33.844843,-116.54911 ,44.92057 ,-93.44786};
        // Add a marker in Sydney and move the camera
        for ( int i = 0 ; i< array.length ; i = i+2){

            LatLng place = new LatLng( array[i], array[i+1]);
            mMap.addMarker(new MarkerOptions().position(place).title("Marker in"+  i));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(place));

        }

    }
}

My DirectionFinder.java is:

     public DirectionFinder( String or , String dest) {



        if(or.equals("PRAN RFL")){
            double lat1 = 23.781388 ;
            double lon1 = 90.425500 ;
            LatLng origin = new LatLng( lat1, lon1);
        }

        if(dest.equals("Gulshan")){

            double lat2 = 23.780270 ;
            double lon2 = 23.780270 ;
            LatLng destination = new LatLng( lat2, lon2);

        }

        //this.listener = listener;
       // this.origin = origin;
       // this.destination = destination;
    }

    public void execute() throws UnsupportedEncodingException {
        listener.onDirectionFinderStart();
        new DownloadRawData().execute(createUrl());
    }

    private String createUrl() throws UnsupportedEncodingException {
        String urlOrigin = URLEncoder.encode(origin, "utf-8");
        String urlDestination = URLEncoder.encode(destination, "utf-8");

        return DIRECTION_URL_API + "origin=" + urlOrigin + "&destination=" + urlDestination + "&key=" + GOOGLE_API_KEY;
    }

    private class DownloadRawData extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            String link = params[0];
            try {
                URL url = new URL(link);
                InputStream is = url.openConnection().getInputStream();
                StringBuffer buffer = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));

                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line + "\n");
                }

                return buffer.toString();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String res) {
            try {
                parseJSon(res);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    private void parseJSon(String data) throws JSONException {
        if (data == null)
            return;

        List<Route> routes = new ArrayList<Route>();
        JSONObject jsonData = new JSONObject(data);
        JSONArray jsonRoutes = jsonData.getJSONArray("routes");
        for (int i = 0; i < jsonRoutes.length(); i++) {
            JSONObject jsonRoute = jsonRoutes.getJSONObject(i);
            Route route = new Route();

            JSONObject overview_polylineJson = jsonRoute.getJSONObject("overview_polyline");
            JSONArray jsonLegs = jsonRoute.getJSONArray("legs");
            JSONObject jsonLeg = jsonLegs.getJSONObject(0);
            JSONObject jsonDistance = jsonLeg.getJSONObject("distance");
            JSONObject jsonDuration = jsonLeg.getJSONObject("duration");
            JSONObject jsonEndLocation = jsonLeg.getJSONObject("end_location");
            JSONObject jsonStartLocation = jsonLeg.getJSONObject("start_location");

            route.distance = new Distance(jsonDistance.getString("text"), jsonDistance.getInt("value"));
            route.duration = new Duration(jsonDuration.getString("text"), jsonDuration.getInt("value"));
            route.endAddress = jsonLeg.getString("end_address");
            route.startAddress = jsonLeg.getString("start_address");
            route.startLocation = new LatLng(jsonStartLocation.getDouble("lat"), jsonStartLocation.getDouble("lng"));
            route.endLocation = new LatLng(jsonEndLocation.getDouble("lat"), jsonEndLocation.getDouble("lng"));
            route.points = decodePolyLine(overview_polylineJson.getString("points"));

            routes.add(route);
        }

        listener.onDirectionFinderSuccess(routes);
    }

    private List<LatLng> decodePolyLine(final String poly) {
        int len = poly.length();
        int index = 0;
        List<LatLng> decoded = new ArrayList<LatLng>();
        int lat = 0;
        int lng = 0;

        while (index < len) {
            int b;
            int shift = 0;
            int result = 0;
            do {
                b = poly.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;

            shift = 0;
            result = 0;
            do {
                b = poly.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            } while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;

            decoded.add(new LatLng(
                    lat / 100000d, lng / 100000d
            ));
        }

        return decoded;
    }
}

my activity layout is:

 <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.pran.trackingapp.MapsActivity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"  >

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/etOrigin"
        android:hint="Enter origin address" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Enter destination address"
        android:id="@+id/etDestination" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Find path"
            android:id="@+id/btnFindPath" />
        <ImageView
            android:layout_marginLeft="20dp"
            android:layout_marginTop="5dp"
            android:layout_width="40dp"
            android:layout_height="40dp" />
        <TextView
            android:layout_marginLeft="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0 km"
            android:id="@+id/tvDistance" />

        <ImageView
            android:layout_marginLeft="20dp"
            android:layout_marginTop="5dp"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:padding="5dp" />
        <TextView
            android:layout_marginLeft="5dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="0 min"
            android:id="@+id/tvDuration" />
    </LinearLayout>


    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

But after clicking the button findpath it generated the error: **

E/DynamiteModule: Failed to load DynamiteLoader: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.dynamite.DynamiteModule$DynamiteLoaderClassLoader" on path: DexPathList[[zip file "/data/app/com.pran.trackingapp-2/base.apk"],nativeLibraryDirectories

** my build.gradle (Module) is:

 apply plugin: 'com.android.application'

    android {
        compileSdkVersion 25
        buildToolsVersion "25.0.0"

        defaultConfig {
            applicationId "com.pran.trackingapp"
            minSdkVersion 16
            targetSdkVersion 25
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:25.0.0'
        compile 'com.google.android.gms:play-services:9.8.0'
    }

my build.gradle(Project) is:

  // Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.0.0'
        classpath 'com.google.gms:google-services:3.0.0'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and path are not drawn.What Can I do now?

demo demo
  • 151
  • 2
  • 4
  • 15

1 Answers1

2

Make following changes in your app's gradle files.

This one is for build.gradle(Project://your project name)

add classpath 'com.google.gms:google-services:3.0.0' in dependenies

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.2'
        classpath 'com.google.gms:google-services:3.0.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

And this one is for your build.gradle (Module:app) Don't add this line if you aren't using other service from google expect maps just add this on the top or bottom of the file apply plugin: 'com.google.gms.google-services'

I hope this will help you.

Zeeshan Shabbir
  • 6,704
  • 4
  • 38
  • 74
  • I added,bt nothing is changed :( – demo demo Nov 20 '16 at 07:16
  • paste both gradle files please – Zeeshan Shabbir Nov 20 '16 at 07:21
  • Done, I have added both gradle files – demo demo Nov 20 '16 at 07:34
  • add ```apply plugin: 'com.google.gms.google-services'``` in gradle.build app module please – Zeeshan Shabbir Nov 20 '16 at 07:36
  • 1
    After I added "apply plugin: 'com.google.gms.google-services'" , I have got error : **"Error:Execution failed for task ':app:processDebugGoogleServices'. > Please fix the version conflict either by updating the version of the google-services plugin (information about the latest version is available at https://bintray.com/android/android-tools/com.google.gms.google-services/) or updating the version of com.google.android.gms to 9.0.0."** – demo demo Nov 20 '16 at 08:48
  • add this ```compile 'com.google.android.gms:play-services:9.0.0'``` instead of ```compile 'com.google.android.gms:play-services:9.8.0'``` in gradle.build app module – Zeeshan Shabbir Nov 20 '16 at 08:56
  • after add **compile 'com.google.android.gms:play-services:9.0.0'** , i have got error: **Error:Execution failed for task ':app:processDebugGoogleServices'. > File google-services.json is missing. The Google Services Plugin cannot function without it. Searched Location: E:\Android sample projects\TrackingApp\app\src\debug\google-services.json E:\Android sample projects\TrackingApp\app\google-services.json** – demo demo Nov 20 '16 at 09:01
  • ```apply plugin: 'com.google.gms.google-services'``` remove this from build.gradle and compile now. I hope this will remove the errors now – Zeeshan Shabbir Nov 20 '16 at 09:05
  • Accept the answer please – Zeeshan Shabbir Nov 20 '16 at 10:06
  • @ZeeshanShabbir are there some explanation for this? Why do we need google-services – Tima Nov 23 '16 at 12:59
  • what do you mean? – Zeeshan Shabbir Nov 23 '16 at 14:03
  • When you want to use services that are provided by google then you'd have to use google-services. For example for maps you have to use it. But if you want to use google analytics then you'd have to add it with a json file that woud be provided by the google – Zeeshan Shabbir Nov 23 '16 at 14:07
  • 2
    I don't understand.. you first tell him to add the apply plugin line and after he gets errors you tell him to remove the same line??? – CodeMonkey Dec 05 '16 at 14:01
  • @YonatanNir I thought he was using more services from google like analytics and maps. Maps doesn't require that line. But analytics requries that also you have to provide configuration file which is created the at google api console – Zeeshan Shabbir Dec 05 '16 at 14:39
  • 1
    Hi @ZeeshanShabbir I have same problem but I still got no solution for it. I guess I got this problem when I was adding firebase to my project, can I post it and get a little help? – MiguelHincapieC Jan 13 '17 at 20:16
  • @MiguelHincapieC You might have missed the configuration file. I see my answer is little confusing and different in questions. I'll update it sooner. – Zeeshan Shabbir Feb 13 '18 at 12:47