我目前正在设计一个需要在MapView上绘制路线的应用程序。为了使其正常运行,我需要从我得到的KML文档中获取数据:
我创建了一个测试项目,以确保正确接收此数据。问题是它在我的模拟器上运行得很好,但在实际的Android手机上却没有。
单击一个按钮,获取输入流响应(KML)时,以下代码启动一个线程。
public void onClick(View v) {
if (v.getId()== R.id.btn1)
{
new Thread() {
@Override
public void run() {
String url = "http://maps.google.com/maps?f=d&hl=en&saddr=-33.882993,18.63486&daddr=-33.870162,18.657837&ie=UTF8&0&om=0&output=kml";
InputStream is = getConnection(url);
mRoad = RouteProvider.getRoute(is);
mHandler.sendEmptyMessage(0);
}
}.start();
}
}
private InputStream getConnection(String url) {
InputStream is = null;
try {
HttpURLConnection conn = (HttpURLConnection)new URL(url).openConnection();
conn.connect();
is = conn.getInputStream();
conn = null;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return is;
}
目前,getRoute()需要做的就是在KML文档中提供“LineString”元素的内容。这些内容是可用于绘制路线的坐标列表。
public class RouteProvider {
/** Gets data from KML response **/
public static Road getRoute(InputStream is) {
Road road = new Road();
try
{
Document xmlDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(is);
NodeList a = xmlDoc.getElementsByTagName("LineString");
System.out.println(a.item(0).getTextContent());
road.mName = a.item(0).getTextContent();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
return road;
}
在我运行的模拟器上,road.mName中显示了正确的值,这是一个坐标列表。在Android手机上显示为空?
我正在eclipse上为Android 2.3.3构建,我使用三星Galaxy S2进行测试。
答案 0 :(得分:1)
毕竟不需要使用KML。刚刚使用谷歌地图提供xml格式。更容易。 https://developers.google.com/maps/documentation/directions/