Android简明开发教程二十一:访问Internet 绘制在线地图

jerry Android 2015年08月24日 收藏

在例子Android簡明開發教程十七:Dialog 顯示圖像 中我們留了一個例子DrawMap()沒有實現,這個例子顯示在線地圖,目前大部分地圖伺服器都是將地圖以圖片存儲以提高響應速度。 一般大小為256X256個像素。具體可以參見離線地圖下載方法解析。

比如: URL http://www.mapdigit.com/guidebeemap/maptile.php?type=MICROSOFTMAP&x=7&y=4&z=14 顯示:

下面的例子訪問Internet下載地圖圖片,並拼接成地圖顯示,這種方法也是引路蜂地圖開發包實現的一個基本原則。

Android應用訪問Internet,首先需要賦予應用有訪問Internet的許可權:在AndroidManifest.xml中添加:

<uses-permission android:name=”android.permission.INTERNET” />

然後實現DrawMap()如下:

  1. private void drawMap(){
  2. try{
  3.  
  4. graphics2D.clear(Color.WHITE);
  5. graphics2D.Reset();
  6. for(int x=6;x<8;x++)
  7. {
  8. for(int y=3;y<5;y++){
  9. String urlString="http://www.mapdigit.com/guidebeemap";
  10. urlString+="/maptile.php?type=MICROSOFTMAP";
  11. urlString+="&x="+x+"&y="+y+"&z=14";
  12. URL url=new URL(urlString);
  13. URLConnection connection=url.openConnection();
  14. HttpURLConnection httpConnection=(HttpURLConnection)connection;
  15. int responseCode=httpConnection.getResponseCode();
  16. if(responseCode==HttpURLConnection.HTTP_OK){
  17. InputStream stream=httpConnection.getInputStream();
  18. Bitmap bitmap=BitmapFactory.decodeStream(stream);
  19. int []buffer=new int[bitmap.getHeight()
  20. * bitmap.getWidth()];
  21. bitmap.getPixels(buffer, 0, bitmap.getWidth(), 0, 0,
  22. bitmap.getWidth(), bitmap.getHeight());
  23. graphics2D.drawImage(buffer,bitmap.getWidth(),
  24. bitmap.getHeight(),(x-6)*256,(y-3)*256);
  25.  
  26. }
  27. }
  28. }
  29. graphic2dView.refreshCanvas();
  30.  
  31. }catch(Exception e){
  32.  
  33. }
  34. }

Android中訪問Internet類主要定義在java.net.* 和android.net.*包中。上面顯示結果如下:

地圖沒有顯示滿屏是因為Graphics2D創建的Canvas大小沒有創建滿屏,創建的大小是240X320,如果創建滿屏的,則可以滿屏顯示地圖。