Android開(kāi)發(fā)速成簡(jiǎn)潔教程二十一:訪問(wèn)Internet繪制在線地圖
在例子Android簡(jiǎn)明開(kāi)發(fā)教程十七:Dialog 顯示圖像中我們留了一個(gè)例子DrawMap()沒(méi)有實(shí)現(xiàn),這個(gè)例子顯示在線地圖,目前大部分地圖服務(wù)器都是將地圖以圖片存儲(chǔ)以提高響應(yīng)速度。 一般大小為256X256個(gè)像素。具體可以參見(jiàn)離線地圖下載方法解析。
比如: URL http://www.mapdigit.com/guidebeemap/maptile.php?type=MICROSOFTMAP&x=7&y=4&z=14 顯示:
下面的例子訪問(wèn)Internet下載地圖圖片,并拼接成地圖顯示,這種方法也是引路蜂地圖開(kāi)發(fā)包實(shí)現(xiàn)的一個(gè)基本原則。
Android應(yīng)用訪問(wèn)Internet,首先需要賦予應(yīng)用有訪問(wèn)Internet的權(quán)限:在AndroidManifest.xml中添加:
- <uses-permission android:name=”android.permission.INTERNET” />
然后實(shí)現(xiàn)DrawMap()如下:
- private void drawMap(){
- try{
- graphics2D.clear(Color.WHITE);
- graphics2D.Reset();
- for(int x=6;x<8;x++)
- {
- for(int y=3;y<5;y++){
- String urlString="http://www.mapdigit.com/guidebeemap";
- urlString+="/maptile.php?type=MICROSOFTMAP";
- urlString+="&x="+x+"&y="+y+"&z=14";
- URL url=new URL(urlString);
- URLConnection connection=url.openConnection();
- HttpURLConnection httpConnection=(HttpURLConnection)connection;
- int responseCode=httpConnection.getResponseCode();
- if(responseCode==HttpURLConnection.HTTP_OK){
- InputStream stream=httpConnection.getInputStream();
- Bitmap bitmap=BitmapFactory.decodeStream(stream);
- int []buffer=new int[bitmap.getHeight()
- * bitmap.getWidth()];
- bitmap.getPixels(buffer, 0, bitmap.getWidth(), 0, 0,
- bitmap.getWidth(), bitmap.getHeight());
- graphics2D.drawImage(buffer,bitmap.getWidth(),
- bitmap.getHeight(),(x-6)*256,(y-3)*256);
- }
- }
- }
- graphic2dView.refreshCanvas();
- }catch(Exception e){
- }
- }
Android中訪問(wèn)Internet類主要定義在java.net.* 和android.net.*包中。上面顯示結(jié)果如下:
地圖沒(méi)有顯示滿屏是因?yàn)镚raphics2D創(chuàng)建的Canvas大小沒(méi)有創(chuàng)建滿屏,創(chuàng)建的大小是240X320,如果創(chuàng)建滿屏的,則可以滿屏顯示地圖。