你好,我是android新手,我想知道如何从url中获取JSON数据,然后使用URL中的数据来设置android地图活动中的标记。
谢谢你的帮助
发布于 2016-03-23 17:43:19
使用HttpUrlConnection获取JSON数据,然后使用从服务器获得的JSON data ( url )创建一个新的JSONObject对象,现在只需通过尊重url提供的键从JSONObject获取信息。此时,只需将值传递给GoogleMap对象即可。例如:
让我们假设url响应这个JSON数据:
{
"long" : 25,
"lat" : 6
}通过使用HttpURLConnection恢复代码:
URL url = new URL("http://localhost_or_any_url/mypage.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
String buff = "", data= "";
InputStream is = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((buff = br.readLine()) != null) data+= buff;
JSONObject json= new JSONObject(data);
int long= json.getInt("long");
int lat= json.getInt("lat");现在,在两个变量(long,lat)上有您的位置(x,y) (经度、纬度),只需将它们传递给您的GoogleMap对象就可以创建如下标记:
LatLng myPosition= new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(myPosition).title("My position"));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(myPosition));
//the last line (the call to moveCamera method) is optional, it helps to move the camera to the marker in case the current map position is far from the marked position这是一个简单的例子,您需要知道从哪里从url获取数据(不能在主线程内部执行网络操作,必须创建一个AsyncTask或Thread),以及如何将数据传递给保存GoogleMap对象的类。
祝好运。
https://stackoverflow.com/questions/36184156
复制相似问题