About Me

Agus Haryanto,
Android Trainner,
GoogleMaps (JavaScript) Trainer
JQuery and JQuery Mobile Trainer
Java, Java Script and PHP Trainer
Freelance Developer Android
Freelance Developer Blackberry
Freelance Developer Web (GIS Googlemaps)
Freelance Developer SMS Gateway

jika ingin contact saya bisa emali ke agus.superwriter@gmail.com

ym: agus_h23

Pin BB : 2AD38B33

Facebook : Agus Haryanto


Article

Belajar Android Direction GoogleMap JSON

Belajar android lagi belajar android lagi, bosan ah yang lain dong. Tapi yang namanya belajar itu tidak boleh bosan. Sebetulnya bosan atau tidak itu relatif.

kalau kita sudah mau sidang, ternyata program yang kita siapkan tiba-tiba ada bagian yang tidak jalan. Contohnya saja yang program atau aplikasi androidnya ada yang menggunakan direction yang menggunakan kml, sejak tanggal 27 Juli 2012 sudah tidak disupport google. Tentu kita akan semangat 45 cari digoogle, tanya ke orang untuk alternatifnya. Ada beberapa email, serta komentar yang menanyakan masalah ini. Akhirnya saya ikut penasaran juga deh untuk cari solusinya, akhirnya ketemu petunjuk berharga dari stackoverflow. Yah harus diakui stackoverflow sangat membantu kita dalam mencari solusi terkait dengan pemrograman.


Sekarang mari kita implementasikan solusi tersebut kedalam project.

1 . Buat project dengan nama AndroidDirectionJSON

2. Edit file main.xml lalu ketikkan kode berikut

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <com.google.android.maps.MapView
        android:id="@+id/mapView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:enabled="true"
        android:clickable="true"
        android:apiKey="0bvY2ipiUvzSE4ybKkHjanqDBGKckFswnJuPw7A"
        />
</RelativeLayout>

3. Buat interface baru dengan nama Parser.java lalu ketikan kode berikut

package com.agusharyanto.net.map.direction.json;

public interface Parser {
	public Route parse();

}

4. Buat Class baru dengan nama XMLParser.java lalu ketikan kode berikut

package com.agusharyanto.net.map.direction.json;

import java.net.URL;
import java.io.IOException;
import java.net.MalformedURLException;
import java.io.InputStream;

import android.util.Log;

public class XMLParser {
        // names of the XML tags
        protected static final String MARKERS = "markers";
        protected static final String MARKER = "marker";

        protected URL feedUrl;

        protected XMLParser(final String feedUrl) {
                try {
                        this.feedUrl = new URL(feedUrl);
                } catch (MalformedURLException e) {
                        Log.d("*****", "XML parser - " + feedUrl);
                }
        }

        protected InputStream getInputStream() {
                try {
                        return feedUrl.openConnection().getInputStream();
                } catch (IOException e) {
                        Log.d("****", "XML parser - " + feedUrl);
                        return null;
                }
        }
}

5. Buat Class baru dengan nama Segmen.java lalu ketikkan kode berikut

package com.agusharyanto.net.map.direction.json;

import com.google.android.maps.GeoPoint;

public class Segment {
        /** Points in this segment. **/
        private GeoPoint start;
        /** Turn instruction to reach next segment. **/
        private String instruction;
        /** Length of segment. **/
        private int length;
        /** Distance covered. **/
        private double distance;

        /**
         * Create an empty segment.
         */

        public Segment() {
        }

        /**
         * Set the turn instruction.
         * @param turn Turn instruction string.
         */

        public void setInstruction(final String turn) {
                this.instruction = turn;
        }

        /**
         * Get the turn instruction to reach next segment.
         * @return a String of the turn instruction.
         */

        public String getInstruction() {
                return instruction;
        }

        /**
         * Add a point to this segment.
         * @param point GeoPoint to add.
         */

        public void setPoint(final GeoPoint point) {
                start = point;
        }

        /** Get the starting point of this
         * segment.
         * @return a GeoPoint
         */

        public GeoPoint startPoint() {
                return start;
        }

        /** Creates a segment which is a copy of this one.
         * @return a Segment that is a copy of this one.
         */

        public Segment copy() {
                final Segment copy = new Segment();
                copy.start = start;
                copy.instruction = instruction;
                copy.length = length;
                copy.distance = distance;
                return copy;
        }

        /**
         * @param length the length to set
         */
        public void setLength(final int length) {
                this.length = length;
        }

        /**
         * @return the length
         */
        public int getLength() {
                return length;
        }

        /**
         * @param distance the distance to set
         */
        public void setDistance(double distance) {
                this.distance = distance;
        }

        /**
         * @return the distance
         */
        public double getDistance() {
                return distance;
        }

}

6. Buat Class baru dengan nama Route.java lalu ketikkan kode berikut

package com.agusharyanto.net.map.direction.json;

import java.util.ArrayList;
import java.util.List;

import com.google.android.maps.GeoPoint;

public class Route {
        private String name;
        private final List<GeoPoint> points;
        private List<Segment> segments;
        private String copyright;
        private String warning;
        private String country;
        private int length;
        private String polyline;

        public Route() {
                points = new ArrayList<GeoPoint>();
                segments = new ArrayList<Segment>();
        }

        public void addPoint(final GeoPoint p) {
                points.add(p);
        }

        public void addPoints(final List<GeoPoint> points) {
                this.points.addAll(points);
        }

        public List<GeoPoint> getPoints() {
                return points;
        }

        public void addSegment(final Segment s) {
                segments.add(s);
        }

        public List<Segment> getSegments() {
                return segments;
        }

        /**
         * @param name the name to set
         */
        public void setName(final String name) {
                this.name = name;
        }

        /**
         * @return the name
         */
        public String getName() {
                return name;
        }

        /**
         * @param copyright the copyright to set
         */
        public void setCopyright(String copyright) {
                this.copyright = copyright;
        }

        /**
         * @return the copyright
         */
        public String getCopyright() {
                return copyright;
        }

        /**
         * @param warning the warning to set
         */
        public void setWarning(String warning) {
                this.warning = warning;
        }

        /**
         * @return the warning
         */
        public String getWarning() {
                return warning;
        }

        /**
         * @param country the country to set
         */
        public void setCountry(String country) {
                this.country = country;
        }

        /**
         * @return the country
         */
        public String getCountry() {
                return country;
        }

        /**
         * @param length the length to set
         */
        public void setLength(int length) {
                this.length = length;
        }

        /**
         * @return the length
         */
        public int getLength() {
                return length;
        }

        /**
         * @param polyline the polyline to set
         */
        public void setPolyline(String polyline) {
                this.polyline = polyline;
        }

        /**
         * @return the polyline
         */
        public String getPolyline() {
                return polyline;
        }

}


7. Buat Class baru dengan nama GoogleParser.java, lalu ketikkan kode berikut

package com.agusharyanto.net.map.direction.json;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.google.android.maps.GeoPoint;

public class GoogleParser extends XMLParser implements Parser {
        /** Distance covered. **/
        private int distance;

        public GoogleParser(String feedUrl) {
                super(feedUrl);
        }

        /**
         * Parses a url pointing to a Google JSON object to a Route object.
         * @return a Route object based on the JSON object.
         */

        public Route parse() {
                // turn the stream into a string
                final String result = convertStreamToString(this.getInputStream());
                //Create an empty route
                final Route route = new Route();
                //Create an empty segment
                final Segment segment = new Segment();
                try {
                        //Tranform the string into a json object
                        final JSONObject json = new JSONObject(result);
                        //Get the route object
                        final JSONObject jsonRoute = json.getJSONArray("routes").getJSONObject(0);
                        //Get the leg, only one leg as we don't support waypoints
                        final JSONObject leg = jsonRoute.getJSONArray("legs").getJSONObject(0);
                        //Get the steps for this leg
                        final JSONArray steps = leg.getJSONArray("steps");
                        //Number of steps for use in for loop
                        final int numSteps = steps.length();
                        //Set the name of this route using the start & end addresses
                        route.setName(leg.getString("start_address") + " to " + leg.getString("end_address"));
                        //Get google's copyright notice (tos requirement)
                        route.setCopyright(jsonRoute.getString("copyrights"));
                        //Get the total length of the route.
                        route.setLength(leg.getJSONObject("distance").getInt("value"));
                        //Get any warnings provided (tos requirement)
                        if (!jsonRoute.getJSONArray("warnings").isNull(0)) {
                                route.setWarning(jsonRoute.getJSONArray("warnings").getString(0));
                        }
                        /* Loop through the steps, creating a segment for each one and
                         * decoding any polylines found as we go to add to the route object's
                         * map array. Using an explicit for loop because it is faster!
                         */
                        for (int i = 0; i < numSteps; i++) {
                                //Get the individual step
                                final JSONObject step = steps.getJSONObject(i);
                                //Get the start position for this step and set it on the segment
                                final JSONObject start = step.getJSONObject("start_location");
                                final GeoPoint position = new GeoPoint((int) (start.getDouble("lat")*1E6),
                                        (int) (start.getDouble("lng")*1E6));
                                segment.setPoint(position);
                                //Set the length of this segment in metres
                                final int length = step.getJSONObject("distance").getInt("value");
                                distance += length;
                                segment.setLength(length);
                                segment.setDistance(distance/1000);
                                //Strip html from google directions and set as turn instruction
                                segment.setInstruction(step.getString("html_instructions").replaceAll("<(.*?)*>", ""));
                                //Retrieve & decode this segment's polyline and add it to the route.
                                route.addPoints(decodePolyLine(step.getJSONObject("polyline").getString("points")));
                                //Push a copy of the segment to the route
                                route.addSegment(segment.copy());
                        }
                } catch (JSONException e) {
                        Log.e(e.getMessage(), "Google JSON Parser - " + feedUrl);
                }
                return route;
        }

        /**
         * Convert an inputstream to a string.
         * @param input inputstream to convert.
         * @return a String of the inputstream.
         */

        private static String convertStreamToString(final InputStream input) {
        final BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        final StringBuilder sBuf = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sBuf.append(line);
            }
        } catch (IOException e) {
                Log.e(e.getMessage(), "Google parser, stream2string");
        } finally {
            try {
                input.close();
            } catch (IOException e) {
                Log.e(e.getMessage(), "Google parser, stream2string");
            }
        }
        return sBuf.toString();
    }

        /**
         * Decode a polyline string into a list of GeoPoints.
         * @param poly polyline encoded string to decode.
         * @return the list of GeoPoints represented by this polystring.
         */

        private List<GeoPoint> decodePolyLine(final String poly) {
                int len = poly.length();
                int index = 0;
                List<GeoPoint> decoded = new ArrayList<GeoPoint>();
                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 GeoPoint(
                        (int) (lat*1E6 / 1E5), (int) (lng*1E6 / 1E5)));
                }

                return decoded;
                }
}

8. Buat Class baru dengan nam RouteOverlay.java, lalu ketikkan kode berikut

package com.agusharyanto.net.map.direction.json;

import java.util.Iterator;
import java.util.List;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

public class RouteOverlay extends Overlay {
    /** GeoPoints representing this routePoints. **/
    private final List<GeoPoint> routePoints;
    /** Colour to paint routePoints. **/
    private int colour;
    /** Alpha setting for route overlay. **/
    private static final int ALPHA = 120;
    /** Stroke width. **/
    private static final float STROKE = 4.5f;
    /** Route path. **/
    private final Path path;
    /** Point to draw with. **/
    private final Point p;
    /** Paint for path. **/
    private final Paint paint;

    /**
     * Public constructor.
     *
     * @param route Route object representing the route.
     * @param defaultColour default colour to draw route in.
     */

    public RouteOverlay(final Route route, final int defaultColour) {
            super();
            routePoints = route.getPoints();
            colour = defaultColour;
            path = new Path();
            p = new Point();
            paint = new Paint();
    }

    @Override
    public final void draw(final Canvas c, final MapView mv,
                    final boolean shadow) {
            super.draw(c, mv, shadow);

            paint.setColor(colour);
            paint.setAlpha(ALPHA);
            paint.setAntiAlias(true);
            paint.setStrokeWidth(STROKE);
            paint.setStyle(Paint.Style.STROKE);

            redrawPath(mv);
            c.drawPath(path, paint);
    }

    /**
     * Set the colour to draw this route's overlay with.
     *
     * @param c  Int representing colour.
     */
    public final void setColour(final int c) {
            colour = c;
    }

    /**
     * Clear the route overlay.
     */
    public final void clear() {
            routePoints.clear();
    }

    /**
     * Recalculate the path accounting for changes to
     * the projection and routePoints.
     * @param mv MapView the path is drawn to.
     */

    private void redrawPath(final MapView mv) {
            final Projection prj = mv.getProjection();
            path.rewind();
            final Iterator<GeoPoint> it = routePoints.iterator();
            prj.toPixels(it.next(), p);
            path.moveTo(p.x, p.y);
            while (it.hasNext()) {
                    prj.toPixels(it.next(), p);
                    path.lineTo(p.x, p.y);
            }
            path.setLastPoint(p.x, p.y);
    }

}

9. Edit Class AndroidDirectionJSON.java, lalu ketikkan kode berikut

package com.agusharyanto.net.map.direction.json;

import android.graphics.Color;
import android.os.Bundle;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class AndroidDirectionJSONActivity extends MapActivity {
	MapView myMapView = null;
	MapController myMC = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		myMapView = (MapView) findViewById(R.id.mapView);

		myMapView.setSatellite(false);

		// STARTING POINT
		GeoPoint startGP = new GeoPoint((int) (-6.3039 * 1E6),
				(int) (106.8267 * 1E6));

		// ENDING POINT
		GeoPoint endGP = new GeoPoint((int) (-6.29436 * 1E6),
				(int) (106.8859 * 1E6));
		//
		myMC = myMapView.getController();
		myMC.setCenter(startGP);
		myMC.setZoom(14);

		Route route = getDirections(startGP, endGP);
		RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
		myMapView.getOverlays().add(routeOverlay);

		myMapView.getController().animateTo(startGP);
		myMapView.setBuiltInZoomControls(true);
		myMapView.displayZoomControls(true);

	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	private Route getDirections(final GeoPoint start, final GeoPoint dest) {
		Parser parser;
		String surl = "http://maps.googleapis.com/maps/api/directions/json?";
		final StringBuffer sBuf = new StringBuffer(surl);
		sBuf.append("origin=");
		sBuf.append(start.getLatitudeE6() / 1E6);
		sBuf.append(',');
		sBuf.append(start.getLongitudeE6() / 1E6);
		sBuf.append("&destination=");
		sBuf.append(dest.getLatitudeE6() / 1E6);
		sBuf.append(',');
		sBuf.append(dest.getLongitudeE6() / 1E6);
		sBuf.append("&sensor=true&mode=driving");
		parser = new GoogleParser(sBuf.toString());
		Route r = parser.parse();
		return r;
	}

}

Dari kode diatas yang menjadi titik mulai nya adalah startGP dana titik akhirnya adala endGP.
untuk menggambar directionyan kode diatas memanggil method getDirection

10. Edit file AndroidManifest.xml, lalu ketikkan kode berikut

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.agusharyanto.net.map.direction.json"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <uses-library android:name="com.google.android.maps" />
        <activity
            android:name=".AndroidDirectionJSONActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 <uses-permission android:name="android.permission.INTERNET"></uses-permission>

</manifest>

11. Saatnya kita merun projectnya, jika semua sudah benar maka hasilnya akan seperti ini

Semoga Bermanfaat,

Salam hangat

Agus Haryanto

Share

46 comments to Belajar Android Direction GoogleMap JSON

  • om.. ini jarak terpendek bukan?? getDirectionnya?? apa bisa diatur sendiri hasilnya?? apa nurutin kemauan google aja?? Thx before.. :)

  • agus

    thanks mas tutorialnya…
    ngomong2 tutorial direction yang sebelumnya di posting, kog sekarang setelah saya coba jadi force close ya mas..???..

  • Myrda

    bermanfaat sekali mas… tp ga ad sourcenya y mas?

  • pemula

    nice tutorial mas agus..

    btw bkin jga donk tutorial buat manggil API Json

    atau JSON Parser..

  • Nanang

    buat mas pemula, ane ada tutorial JSON Parser dari mysql database pake localhost di blog ane, tapi belom ane benerin keterangan source code-nya karena kesibukan ane.
    Insya Allah bisa jalan codingannya..

    http://yangtakterucap.wordpress.com/2012/07/12/belajar-android-listview-dari-mysql/

  • bro

    mntap mas..saya pikir servernya google maps down..trnyta kml me ud gk dipakai goolge lagi ya mas…

    prtnyaan saya,sama ama @dede pradana..ehehhe

  • pemula

    @nanang..
    Json Parser nya ngga dari Mysql / local host om.. tapi dari API.. ada ga?

  • learner

    mas tutorial di atas kan 2 titiknya kita sndiri yg tentukan,
    gmna cranya klw slah satunya aja kita tentukan yg satunya kita ambil dari
    posisi GPS . .
    mhon d blas ya mas agus

  • fatimah

    Terima kasih banyak..

  • Ali

    Mantab mas, hanya kurang penjelasannya…

  • newbi

    mas,,waktu saya nyobain Direction GoogleMap JSON di handphone rute udah muncul di peta goole maps,cuama kenapa ya jdi lemot bgt pas mau ngegeserin peta atau waktu klik zoom, respon hp nya lama bgt, kaya yng ngeheng gtu tpi pas drection nya di close hp normal lagi..mohon penjelasnya !!!!

  • fatimah

    error lagi sekarang mas,,kenapa ya?padahal kemaren bisa,,dan source code tidak saya otak-atik

  • ayu

    mas ini json buat semua koneksi ke google ya?kl nentuin my lokasi gmn?butuh info segera..makasi

  • wah terima kasih infonya gan…
    nice post :)

  • icalz

    mas agus, code yg ini kan udah di tentukan k 2 koordinatx
    gmna kalo salah satux aja yag kita tntukan yg satux lg
    dari GPS???

  • hendra

    Pak. request tutorial yang multiple table diakses pake adapter/multiple adapter.

    terima kasih.

  • Jank Eman

    Cociks pisan kang

  • altaf

    Mas agus kok error yah pas aku jalanin di SDK 10…

  • Agus Haryanto

    @altaf, errornya apa ?

  • Dicky

    mas agus, ym mas agus aktif?

  • Keren2 postingannya pakde.
    O y saya mau tanya pakde, saya kan rencana mau bikin aplikasi basis LBS nih makek android.

    Nah biasanya kan layanan petanya makek Google MAPS
    Btw, bisa gak kita bikin desain PETA kita sendiri pakde?
    Soalnya Lokasi daerah yang saya ambil sebagai objek, di google maps malah komplit info tentang lokasinya pakde

    Mohon solusinya pakde
    Terimakasih

  • altaf

    alhamdulillah udah bisa mas, ternyata error krn apikeynya, makasih tutornya mas, sangat bermanfaat sekali..

  • Hery

    project ini bisa ditambahkan dengan metode AntColony (semut) gk mas ??? ato emang google punya metode tertentu buat penentuan jalur terpendekx ???
    Thanks..

  • dynasty

    mas programnya aku coba kq eror y, force close, pertma run layar hitam habis itu force close,
    apa ada yng hrus diubah lg?, API key udh saya ganti
    mksih mas sblmnya

  • dynasty

    XML parser – http://maps.googleapis.com/maps/api/directions/json?origin=-6.3039,106.8267&destination=-6.29436,106.8859&sensor=true&mode=driving
    D/AndroidRuntime(29392): Shutting down VM
    W/dalvikvm(29392): threadid=1: thread exiting with uncaught exception (group=0×40015560)
    E/AndroidRuntime(29392): FATAL EXCEPTION: main
    E/AndroidRuntime(29392): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dsf/com.example.dsf.AndroidDirectionJSONActivity}: java.lang.NullPointerException

    klhtanya sdah bisa koneksinya mas tp hbis itu lngsung forcr close

  • orcneo

    pak tolong donk di share jga map direction between 2 pointnya..
    biar ada bayangan buat bikin mapnya heheheh makasih..

  • Adin

    Mas klo mau refresh mapnya pake koordinat yang baru gmn y, setiap sy masukin koordinat yg baru directionnya jadi dobel

  • latif

    kalo startGP nya dari GPS gimana caranya bang?
    udah tak coba antara projek myposisi dan Json gk jalan bang.
    untuk memanggil fungsi myposisi di Json gimana bang?

  • geloz

    mapnya kok gak keluar?
    cuma ada koordinatnya aja,,,,
    gimana solusinya?

  • keboganteng

    mas agus saya mau numpang tanya nih.. saya nyusun TA tentang Location Based Service.. pada saat di jalankan di emulator komputer.. semuanya berjalan dengan baik, map keluar sempurna.. tetapi pas di pindahin di samsung galaxy ace.. masalah timbul.. pada saat loading.. hanya muncul icon markernya beserta navigasinya.. tidak dengan mapsnya..pertama saya pikir karena sinyal, tetapi setelah saya coba aplikasi lain yg menggunakan Location Based Service di handphone android saya.. berjalan sempurna, mapnya keluar dengan cepat.. sedangkan di aplikasi saya mapnya ga keluar2 walaupun sudah ditunggu 30 menit.. kira2 ada masalah apa ya di aplikasi buatan saya..

    tolong di bantu mas di carikan solusinya..
    terima kasih banyak..

  • blogWalker

    penjelasan nya dikit banget.. gmna bisa ngerti detail nya..

    ini hasil copas dari tempat lain juga ya??

    jelasin point2 penting nya lebih detail donk

  • Nggak Jalan

    Nggak jalan om. ane liat di logcatnya network exception error. Padahal di manifestnya udah ditambahin permission internet. dan saya pakai wifi devicenya. Kalo browsing2 lancar. pas jalanin ini force close. saya juga udah pake api map saya sendiri. tetep error dijalanin. payah nih ah code.

  • Adin

    setelah saya coba di versi yang lebih kini ICS maupun JellyBean aplikasi ini error Exception android.os.NetworkOnMainThreadException, ketemulah solusinya di sini http://stackoverflow.com/questions/13667152/how-to-use-method-in-asynctask-in-android akhirnya dari situ saya dapat solusinya dengan menggunakan asynctask, code dari mas agus saya sedikit modifikasi menjadi kurang lebih

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    myMapView = (MapView) findViewById(R.id.mapView);

    myMapView.setSatellite(false);

    // STARTING POINT
    startGP = new GeoPoint((int) (-6.3039 * 1E6),
    (int) (106.8267 * 1E6));

    // ENDING POINT
    endGP = new GeoPoint((int) (-6.29436 * 1E6),
    (int) (106.8859 * 1E6));
    //
    myMC = myMapView.getController();
    myMC.setCenter(startGP);
    myMC.setZoom(14);

    rute task = new rute();
    task.execute();

    }

    private class rute extends AsyncTask{
    protected Route doInBackground(String… params){
    Route route = null;
    try{
    route = getDirections(startGP, endGP);
    }catch (Exception e){
    e.printStackTrace();
    }
    return route;
    }
    protected void onPostExecute(Route route){
    RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
    myMapView.getOverlays().add(routeOverlay);

    myMapView.getController().animateTo(startGP);
    myMapView.setBuiltInZoomControls(true);
    myMapView.displayZoomControls(true);

    }
    }

    CMIIW…Semoga bermanfaat

  • Agus Haryanto

    @adin, Betul untuk Android ICS ke atas untuk Call ke Server Harus menggunakan Assynctask. atau kalau masih nekat
    coba dalam method oncreate() tambahkan
    StrictMode.ThreadPolicy policy = new StrictMode.
    ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Tapi cara ini tidak dianjurkan

  • Joe

    @mas adin, kok ketika masuk d baris code :
    myMapView.getOverlays().add(routeOverlay);

    dia langsung eror ya?
    di logcat gk ada keterangannya error karna apa nya. tiba2 langsung force close aja..

  • Joe

    Adapun kode saya begini :

    package com.example.net.map.direction.json;

    import android.graphics.Color;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;

    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.MapActivity;
    import com.google.android.maps.MapController;
    import com.google.android.maps.MapView;

    public class AndroidDirectionJSON extends MapActivity {
    MapView myMapView = null;
    MapController myMC = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    myMapView = (MapView) findViewById(R.id.mapView);
    myMapView.setSatellite(false);

    GeoPoint startGP = new GeoPoint((int) (-6.3039 * 1E6), (int) (106.8267 * 1E6));
    myMC = myMapView.getController();
    myMC.setCenter(startGP);
    myMC.setZoom(14);

    rute task = new rute();
    task.execute();

    }

    private class rute extends AsyncTask{

    @Override
    protected Route doInBackground(String… params) {
    // STARTING POINT
    Route route = null;

    try {
    GeoPoint startGP = new GeoPoint((int) (-7.56229 * 1E6), (int) (110.816517 * 1E6));
    GeoPoint endGP = new GeoPoint((int) (-7.824269 * 1E6), (int) (110.364532 * 1E6));
    route = getDirections(startGP, endGP);
    } catch (Exception e) {
    e.printStackTrace();
    }
    return route;
    }
    @Override
    protected void onPostExecute(Route route){

    RouteOverlay rOverlay = new RouteOverlay(route, Color.BLUE);

    myMapView.getOverlays().add(rOverlay);

    myMapView.invalidate();
    }
    }

    private Route getDirections(final GeoPoint start, final GeoPoint dest) {
    Parser parser;
    String surl = “http://maps.googleapis.com/maps/api/directions/json?”;
    final StringBuffer sBuf = new StringBuffer(surl);
    sBuf.append(“origin=”);
    sBuf.append(start.getLatitudeE6() / 1E6);
    sBuf.append(‘,’);
    sBuf.append(start.getLongitudeE6() / 1E6);
    sBuf.append(“&destination=”);
    sBuf.append(dest.getLatitudeE6() / 1E6);
    sBuf.append(‘,’);
    sBuf.append(dest.getLongitudeE6() / 1E6);
    sBuf.append(“&sensor=true&mode=driving”);
    parser = new GoogleParser(sBuf.toString());
    Route r = parser.parse();
    return r;
    }

    @Override
    protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
    }

    }

  • Joe

    alhamdulillah udah ketemu solusinya. cm sekarang mau nanya donk mas agus. Gimana caranya kalo mau gabungin json direction yang disitu di tampilin posisi kita juga. Jadi kita di navigasi dari posisi kita sampai ke suatu tempat tujuan.

  • andreza

    @Joe
    bikin class gps lokasi kita,, habis itu gabungin class lokasi kita dengan titik posisi yang di inginkan. banyak tutor buat nampilin posisi kita.

    CMIIW.. mungkin begitu logikanya

  • abdul syukur

    kok ini eror yah pas di buka force close

  • Agus Haryanto

    @abdul syukur, coba pakai yang googlemaps v2

  • mas agus,untuk pake map v2 tinggal ganti API keynya aja y?atau ada yg hrus di tmbhin
    mhon pncrhannya mas
    trima kasih

  • Adzima Akhyar

    Mas kok Maps nya ga keluar yaa d emulator??
    di android gynger juga gaa keluar map nya??
    apa karena koneksi yaa??

  • makasih gan infonya dan semoga bermanfaat

  • mantap bos artikelnya dan sangat menarik

  • terimakasih mas buat infonya dan salam sukses

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Spam protection by WP Captcha-Free