Kết quả 1 đến 7 của 7
  1. #1
    Ngày tham gia
    Jul 2015
    Bài viết
    1

    Hướng dẫn demo ứng dụng dẫn đường trên Android

    đối với bản đồ trên smartphone ngoài chức năng quan trọng là định vị thông qua gps, thì chức năng dẫn đường direction cũng không kém phần quan trọng. dưới đây là một demo nho nhỏ để minh họa chưc năng này.
    giao diện chính của chương trình:
    phần apikey các bạn có thể tìm hiểu trên google nhé. cái này rất quan trọng, nếu khoog ứng dụng của bạn sẽ không thể hiện thị bản độ được.
    một điều quan trọng là khi các bạn test phải chọn hệ điều hành là google api nhé nếu không sẽ báo lỗi khi code đó.


    Mã:
    <?xml version="1.0" encoding="utf-8"?>
    <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >
       
        <com.google.android.maps.mapview
                android:id="@+id/mapview"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:apikey="0f-2is_7smhtxg-qmkus2ciwq4fixhud0bcup8g"
                android:clickable="true"
                android:enabled="true" />
     
    </linearlayout>
    class main: ở đây mình lấy thông tin dẫn đường từ maps.google.com thông qua json và dùng asynctask để ứng dụng có thể hoạt động ok khi chạy trên nền tảng 4.0 trở lên nhé.


    Mã:
    package com.example.directionjson;
    import java.io.ioexception;
    import java.util.list;
    import java.util.locale;
     
    import com.google.android.maps.geopoint;
    import com.google.android.maps.mapactivity;
    import com.google.android.maps.mapcontroller;
    import com.google.android.maps.mapview;
     
    import android.location.address;
    import android.location.geocoder;
    import android.os.asynctask;
    import android.os.bundle;
    import android.graphics.color;
    import android.util.log;
     
    public class directionjson extends mapactivity {
     
        mapview mapview = null;
        mapcontroller mapcontroller;
        double long1 = 106.710340*1e6;
        double lati1 = 10.796380*1e6;
        double long2 = 106.658460*1e6;
        double lati2 = 10.770590*1e6;
        geopoint srcgeopoint;
        geopoint destgeopoint;
        double src_lat = 18.5535;
        double src_long = 73.7966;
        double dest_lat = 18.5535;
        double dest_long = 73.7966;
     
        @override
        public void oncreate(bundle savedinstancestate) {
            super.oncreate(savedinstancestate);
            setcontentview(r.layout.activity_direction_json);
            mapview = (mapview) findviewbyid(r.id.mapview);
            //khởi tạo thông tin vị trí cần chỉ đường cho ứng dụng
            geocoder coder = new geocoder(getapplicationcontext(),
                    locale.getdefault());
            list<address> address_src = null;
            list<address> address_dest = null;
            string diemdi="124 xo viet nghe tinh";
            string diemden="1 to hien thanh";
            try {
                address_src = coder
                        .getfromlocationname(
                                diemdi,
                                1);
                if (address_src.size() > 0) {
                    address loc = address_src.get(0);
                    src_lat = loc.getlatitude();
                    src_long = loc.getlongitude();
                }
                address_dest = coder.getfromlocationname(
                        diemden, 1);
                if (address_dest.size() > 0) {
                    address loc = address_dest.get(0);
                    dest_lat = loc.getlatitude();
                    dest_long = loc.getlongitude();
                }
            } catch (ioexception e) { // todo auto-generated catch block
                e.printstacktrace();
            }
            //hiển thị chỉ dẫn trên bản đồ của ứng dụng
            mapview.setbuiltinzoomcontrols(true);
            srcgeopoint = new geopoint((int) (src_lat * 1e6),
                    (int) (src_long * 1e6));
            destgeopoint = new geopoint((int) (dest_lat * 1e6),
                    (int) (dest_long * 1e6));
            directionstask getdirectionstask = new directionstask();
            getdirectionstask.execute();
        }
     
        private class directionstask extends asynctask<void, void, route> {
     
            protected route doinbackground(void... params) {
                    parser parser;
                    final string sbuf = makeurl(srcgeopoint, destgeopoint);
                    log.v("i came in url", sbuf.tostring());
                    parser = new googleparser(sbuf);
                    route r =  parser.parse();
                    return r;
            }
        protected void onpostexecute(route route) {
            routeoverlay routeoverlay = new routeoverlay(route, color.blue);
            mapview.getoverlays().add(routeoverlay);
            mapview.invalidate();
            mapview.getcontroller().animateto(srcgeopoint);
            mapview.getcontroller().animateto(destgeopoint);
            mapcontroller = mapview.getcontroller();
            mapcontroller.setzoom(18); // zoom 1 is world view
            mapview.getmapcenter();
        }
     
        }
     
      //khởi tạo url từ thông tin vị trí người dùng nhập
        private string makeurl(geopoint src, geopoint dest) {
            // todo auto-generated method stub
     
            stringbuilder urlstring = new stringbuilder();
     
            urlstring.append("http://maps.googleapis.com/maps/api/directions/json");
            urlstring.append("?origin=");// from
            urlstring.append(double.tostring((double) src.getlatitudee6() / 1.0e6));
            urlstring.append(",");
            urlstring
                    .append(double.tostring((double) src.getlongitudee6() / 1.0e6));
            urlstring.append("&destination=");// to
            urlstring
                    .append(double.tostring((double) dest.getlatitudee6() / 1.0e6));
            urlstring.append(",");
            urlstring
                    .append(double.tostring((double) dest.getlongitudee6() / 1.0e6));
            urlstring.append("&sensor=false");
     
            log.d("***", "url=" + urlstring.tostring());
            return urlstring.tostring();
        }
        @override
        protected boolean isroutedisplayed() {
            // todo auto-generated method stub
            return false;
        }
    }
    class googleparse: nhăm phân tích kết quả từ server dạng json để lấy thông tin dẫn đường mong muốn của mình.


    Mã:
    package com.example.directionjson;
     
    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 - " );
                }
                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;
                }
    }
    class parse


    Mã:
    package com.example.directionjson;
     
    public interface parser {
        public route parse();
    }
    class route


    Mã:
    package com.example.directionjson;
     
    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;
        }
     
    }
    class segment


    Mã:
    package com.example.directionjson;
     
    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;
        }
     
    }
    class routeoverlay: hiển thị dạng đồ họa thông tin chỉ dẫn trực tiếp trên googlemap.


    Mã:
    package com.example.directionjson;
     
    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;
     
    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);
        }
     
    }
    file cấu hình androidmanifest: phần thư viện "<uses-library android:name="com.google.android.maps" />" trong file cấu hình rất quan trọng nhé, nếu không có nó sẽ báo lỗi ngay từ khi các bạn thao tác với mapview đó.


    Mã:
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.directionjson"
        android:versioncode="1"
        android:versionname="1.0" >
     
        <uses-sdk
            android:minsdkversion="8"
            android:targetsdkversion="15" />
        <uses-permission android:name="android.permission.internet"/>
     
        <application
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/apptheme" >
            <uses-library android:name="com.google.android.maps" />
            <activity
                android:name=".directionjson"
                android:label="@string/title_activity_direction_json" >
                <intent-filter>
                    <action android:name="android.intent.action.main" />
     
                    <category android:name="android.intent.category.launcher" />
                </intent-filter>
            </activity>
        </application>
     
    </manifest>
    ok xong rồi, demo này chỉ hiện thị dẫn đường dạng đồ họa. nếu các bạn muốn lấy thông tin chi tiết từng con đường một thì trong phần lấy dữ liệu dạng json về đã có đầy đủ cả.
    đây là bản demo nên mình fix cứng điểm đi và điểm đến. nếu các bạn muốn phát triên thêm có thể dùng điểm đi là thông tin gps trả về từ smartphone, còn điểm đến do người dùng tự nhập.(trong code mình sẽ chỉ dẫn đi từ 124 xô viết nghệ tĩnh --> 1 tô hiến thành nhé, phần chuyển từ địa chỉ ra thông tin tọa độ, mình cũng làm trong code rồi) .
    ok xog ùi.

  2. #2
    Ngày tham gia
    Jan 2015
    Bài viết
    0
    bạn chạy ứng dụng này trên máy ảo hay máy thật vậy??

  3. #3
    Ngày tham gia
    Dec 2014
    Bài viết
    0
    Trích dẫn Gửi bởi thắng it
    bạn chạy ứng dụng này trên máy ảo hay máy thật vậy??
    máy ảo bạn ah.

  4. #4
    Ngày tham gia
    Feb 2014
    Bài viết
    0
    mình viết app google map api v2 chạy trên máy ảo toàn là ô vuông. mình đã cài google play services cho máy ảo luôn nhưng nó cũng vậy ???

  5. #5
    Ngày tham gia
    Apr 2015
    Bài viết
    0
    bạn ơi .. share full source được k bạn.

  6. #6
    Ngày tham gia
    Aug 2014
    Bài viết
    0
    bạn


    Trích dẫn Gửi bởi takeshi90
    máy ảo bạn ah.
    bạn cho mình hỏi là bạn chạy trên máy ảo nào được không, t load trên máy ảo thì hiện thị toàn ô vuông. nếu có thể thì hướng dẫn cách làm để load trên máy ảo. thank!

  7. #7
    Ngày tham gia
    Apr 2015
    Bài viết
    0
    cái này là map v2 hay v1 hả bạn ?

Quyền viết bài

  • Bạn Không thể gửi Chủ đề mới
  • Bạn Không thể Gửi trả lời
  • Bạn Không thể Gửi file đính kèm
  • Bạn Không thể Sửa bài viết của mình
  •