---
title: "Android简明开发教程二十一：访问Internet 绘制在线地图"
author: "mapdigit"
date: "2011-05-18T09:54:00Z"
tags: []
slug: "android-internet"
draft: false
lastmod: "2013-03-22T14:10:59Z"
id: 1834796
url: "https://mapdigit.iteye.com/blog/1834796"
---

在例子[Android简明开发教程十七：Dialog 显示图像](../?p=955 "链向 Android简明开发教程十七：Dialog 显示图像 的固定链接") 中我们留了一个例子DrawMap()没有实现，这个例子显示在线地图，目前大部分地图服务器都是将地图以图片存储以提高响应速度。 一般大小为256X256个像素。具体可以参见[离线地图下载方法解析](../?p=763 "链向 离线地图下载方法解析 的固定链接") 。

比如： URL [http://www.mapdigit.com/guidebeemap/maptile.php?type=MICROSOFTMAP&x=7&y=4&z=14](http://www.mapdigit.com/guidebeemap/maptile.php?type=MICROSOFTMAP&x=7&y=4&z=14) 显示：

[![](http://www.imobilebbs.com/wordpress/wp-content/uploads/2011/04/microsoftmap.png "microsoftmap")](http://www.imobilebbs.com/wordpress/wp-content/uploads/2011/04/microsoftmap.png) 下面的例子访问Internet下载地图图片，并拼接成地图显示,这种方法也是引路蜂地图开发包实现的一个基本原则。

Android应用访问Internet，首先需要赋予应用有访问Internet的权限：在AndroidManifest.xml中添加：

&lt;uses-permission android:name=”android.permission.INTERNET” /&gt;

然后实现DrawMap()如下：

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

`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中访问Internet类主要定义在java.net.* 和android.net.\*包中。上面显示结果如下：

[![](http://www.imobilebbs.com/wordpress/wp-content/uploads/2011/04/20110419001.png "20110419001")](http://www.imobilebbs.com/wordpress/wp-content/uploads/2011/04/20110419001.png) 地图没有显示满屏是因为Graphics2D创建的Canvas大小没有创建满屏，创建的大小是240X320，如果创建满屏的，则可以满屏显示地图。