Google Map and GPS for Mobile !


Diễn đàn chia sẻ kiến thức, kinh nghiệm về IT và cuộc sống!
 
Trang ChínhGalleryTìm kiếmLatest imagesĐăng kýĐăng Nhập
Top posters
Sakura (1124)
Google Map and GPS for Mobile ! Vote_lcapGoogle Map and GPS for Mobile ! Voting_barGoogle Map and GPS for Mobile ! Vote_rcap 
hotboy (705)
Google Map and GPS for Mobile ! Vote_lcapGoogle Map and GPS for Mobile ! Voting_barGoogle Map and GPS for Mobile ! Vote_rcap 
Già Làng (373)
Google Map and GPS for Mobile ! Vote_lcapGoogle Map and GPS for Mobile ! Voting_barGoogle Map and GPS for Mobile ! Vote_rcap 
con_ca_nho90 (289)
Google Map and GPS for Mobile ! Vote_lcapGoogle Map and GPS for Mobile ! Voting_barGoogle Map and GPS for Mobile ! Vote_rcap 
that_true (154)
Google Map and GPS for Mobile ! Vote_lcapGoogle Map and GPS for Mobile ! Voting_barGoogle Map and GPS for Mobile ! Vote_rcap 
theanhkkt (143)
Google Map and GPS for Mobile ! Vote_lcapGoogle Map and GPS for Mobile ! Voting_barGoogle Map and GPS for Mobile ! Vote_rcap 
phamay (137)
Google Map and GPS for Mobile ! Vote_lcapGoogle Map and GPS for Mobile ! Voting_barGoogle Map and GPS for Mobile ! Vote_rcap 
lovelonelyman (134)
Google Map and GPS for Mobile ! Vote_lcapGoogle Map and GPS for Mobile ! Voting_barGoogle Map and GPS for Mobile ! Vote_rcap 
o0ovioletstaro0o (128)
Google Map and GPS for Mobile ! Vote_lcapGoogle Map and GPS for Mobile ! Voting_barGoogle Map and GPS for Mobile ! Vote_rcap 
stevenhung (122)
Google Map and GPS for Mobile ! Vote_lcapGoogle Map and GPS for Mobile ! Voting_barGoogle Map and GPS for Mobile ! Vote_rcap 
Âm - Dương lịch
Clock
Logo
11TH02 Pro!
Liên kết
Tin tức 60s
Tin công nghệ
Thời sự 24h
Game Moblie

Share
 

 Google Map and GPS for Mobile !

Xem chủ đề cũ hơn Xem chủ đề mới hơn Go down 
Tác giảThông điệp
Biofan4u

Google Map and GPS for Mobile ! Stars16
Biofan4u

Thú CƯng : Google Map and GPS for Mobile ! Pig-icon
Nam Scorpio

Số bài viết : 20
Điểm : 28
Được cảm ơn : 0
Ngày sinh : 21/11/1983
Tham gia ngày : 24/09/2010
Tuổi : 40
Đến từ : Java Land

Google Map and GPS for Mobile ! Empty
Bài gửiTiêu đề: Google Map and GPS for Mobile !   Google Map and GPS for Mobile ! I_icon_minitime8/4/2011, 09:43

Code JavaME về Google Map và GPS.
Phần mềm này chạy trên nền tảng Java MIDP 2.0 và CDLC 1.1 .Các bạn chỉ việc lên website của Java down về bộ công cụ Java ME .Cài đặt xong xuôi chạy chương trình và tạo 2 class

JMidlet.java (Class main sử dụng để hiển thị trên màn hình thiết bị di động)
Code:


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.location.*;

/**
 * @author Mr.Trinh
 */
public class JMidlet extends MIDlet implements CommandListener,LocationListener{
    private double lat,lon;
    private LocationProvider locationProvider;
    private Criteria cr;
    private Location location;
    private Coordinates coordinates;
    private Command exitCommand,refreshCommand; // The exit command
    private Display display;    // The display for this MIDlet
    private Form mForm;          // The main form to display
    private Image map;
    private ImageItem GGmap;

    public JMidlet (){
        display = Display.getDisplay(this);
        exitCommand = new Command("Exit", Command.EXIT, 0);
        refreshCommand = new Command("Refresh", Command.OK, 1);
    }
    public void startApp() {
        mForm = new Form("Google Maps");
        mForm.addCommand(exitCommand);
        mForm.addCommand(refreshCommand);
        mForm.setCommandListener(this);
        display.setCurrent(mForm);
    }

    public void pauseApp() {
    }

    public void destroyApp(boolean unconditional) {
    }

    public void commandAction(Command c, Displayable d) {
        if (c == exitCommand) {
            destroyApp(false);
            notifyDestroyed();
        }
        if(c== refreshCommand){
            cr = new Criteria();
            cr.setHorizontalAccuracy(500);
            try {
                locationProvider = LocationProvider.getInstance(cr);
            } catch (LocationException ex) {
                ex.printStackTrace();
            }
            try {
                location = locationProvider.getLocation(40);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            } catch (LocationException ex) {
                ex.printStackTrace();
            }
            coordinates =location.getQualifiedCoordinates();
            lat = coordinates.getLatitude();
            lon = coordinates.getLongitude();
            GoogleMaps gMap = new GoogleMaps("API_KEY");
            try {
                map = gMap.retrieveStaticImage(340,240,lat,lon, 14, "satellite","jpg");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            GGmap = new ImageItem(null,map,ImageItem.LAYOUT_CENTER,null);
            mForm.deleteAll();
            mForm.append(GGmap);
            display.setCurrent(mForm);
        }
    }

    public void locationUpdated(LocationProvider arg0, Location arg1) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public void providerStateChanged(LocationProvider arg0, int arg1) {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}

Tiếp theo tạo thêm 1 class Java: GoogleMaps.java
Code:

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Vector;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Image;

public class GoogleMaps {
    private static final String URL_UNRESERVED =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZ" +
        "abcdefghijklmnopqrstuvwxyz" +
        "0123456789-_.~";
    private static final char[] HEX = "0123456789ABCDEF".toCharArray();

    // these 2 properties will be used with map scrolling methods. You can remove them if not needed
    public static final int offset = 268435456;
    public static final double radius = offset / Math.PI;

    private String apiKey = null;
    public GoogleMaps(String key) {
        apiKey = key;
    }

    public double[] geocodeAddress(String address) throws Exception {
        byte[] res = loadHttpFile(getGeocodeUrl(address));
        String[] data = split(new String(res), ',');

        if (!data[0].equals("200")) {
            int errorCode = Integer.parseInt(data[0]);
            throw new Exception("Google Maps Exception: " + getGeocodeError(errorCode));
        }

        return new double[] {
                Double.parseDouble(data[2]), Double.parseDouble(data[3])
        };
    }

    public Image retrieveStaticImage(int width, int height, double lat, double lng, int zoom,String maptype,
            String format) throws IOException {
        byte[] imageData = loadHttpFile(getMapUrl(width, height, lng, lat, zoom, maptype, format));

        return Image.createImage(imageData, 0, imageData.length);
    }

    private static String getGeocodeError(int errorCode) {
        switch (errorCode) {
        case 400:
            return "Bad request";
        case 500:
            return "Server error";
        case 601:
            return "Missing query";
        case 602:
            return "Unknown address";
        case 603:
            return "Unavailable address";
        case 604:
            return "Unknown directions";
        case 610:
            return "Bad API key";
        case 620:
            return "Too many queries";
        default:
            return "Generic error";
        }
    }

    private String getGeocodeUrl(String address) {
        return "http://maps.google.com/maps/geo?q=" + urlEncode(address) + "&output=csv&key="
                + apiKey;
    }

    private String getMapUrl(int width, int height, double lng, double lat, int zoom, String maptype,String format) {
        return "http://maps.google.com/staticmap?center=" + lat + "," + lng + "&maptype="
                + maptype+"&format="+ format + "&zoom=" + zoom + "&size=" + width + "x" + height + "&key=" + apiKey;
    }

    private static String urlEncode(String str) {
        StringBuffer buf = new StringBuffer();
        byte[] bytes = null;
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(bos);
            dos.writeUTF(str);
            bytes = bos.toByteArray();
        } catch (IOException e) {
            // ignore
        }
        for (int i = 2; i < bytes.length; i++) {
            byte b = bytes[i];
            if (URL_UNRESERVED.indexOf(b) >= 0) {
                buf.append((char) b);
            } else {
                buf.append('%').append(HEX[(b >> 4) & 0x0f]).append(HEX[b & 0x0f]);
            }
        }
        return buf.toString();
    }

    private static byte[] loadHttpFile(String url) throws IOException {
        byte[] byteBuffer;

        HttpConnection hc = (HttpConnection) Connector.open(url);
        try {
            hc.setRequestMethod(HttpConnection.GET);
            InputStream is = hc.openInputStream();
            try {
                int len = (int) hc.getLength();
                if (len > 0) {
                    byteBuffer = new byte[len];
                    int done = 0;
                    while (done < len) {
                        done += is.read(byteBuffer, done, len - done);
                    }
                } else {
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] buffer = new byte[512];
                    int count;
                    while ( (count = is.read(buffer)) >= 0 ) {
                        bos.write(buffer, 0, count);
                    }
                    byteBuffer = bos.toByteArray();
                }
            } finally {
                is.close();
            }
        } finally {
            hc.close();
        }

        return byteBuffer;
    }

    private static String[] split(String s, int chr) {
        Vector res = new Vector();

        int curr;
        int prev = 0;

        while ( (curr = s.indexOf(chr, prev)) >= 0 ) {
            res.addElement(s.substring(prev, curr));
            prev = curr + 1;
        }
        res.addElement(s.substring(prev));

        String[] splitted = new String[res.size()];
        res.copyInto(splitted);

        return splitted;
    }
}

Chạy chương trình và test trên mobile
Về Đầu Trang Go down
Biofan4u

Google Map and GPS for Mobile ! Stars16
Biofan4u

Thú CƯng : Google Map and GPS for Mobile ! Pig-icon
Nam Scorpio

Số bài viết : 20
Điểm : 28
Được cảm ơn : 0
Ngày sinh : 21/11/1983
Tham gia ngày : 24/09/2010
Tuổi : 40
Đến từ : Java Land

Google Map and GPS for Mobile ! Empty
Bài gửiTiêu đề: Re: Google Map and GPS for Mobile !   Google Map and GPS for Mobile ! I_icon_minitime8/4/2011, 09:48

Up thêm tý nữa ! một số trang web tham khảo về GPS và Google map:

1) Định đạnh dữ liệu trả về từ GPS:
[You must be registered and logged in to see this link.]
2) Định dạng URL để nhận một Static Map (Google Map):
[You must be registered and logged in to see this link.]
3) Gói nhận và bắt tín hiệu GPS trên Java
[You must be registered and logged in to see this link.]
Về Đầu Trang Go down
 

Google Map and GPS for Mobile !

Xem chủ đề cũ hơn Xem chủ đề mới hơn Về Đầu Trang 
Trang 1 trong tổng số 1 trang

 Similar topics

-
» Hướng dẫn - Làm website bằng Google Site; Đăng ký và sử dụng Google Apps
» Google sắp ra mắt mạng xã hội Google+
» Google khiến trí nhớ mất dần
» Mạng xã hội mới đe dọa Facebook và Google+
» “Bạn thích gì?” – Dịch vụ mới của Google

Permissions in this forum:Bạn không có quyền trả lời bài viết
IT World! :: HỌC TẬP :: HỌC KỲ VI :: Lập trình ứng dụng mạng-