在Google Map / Android上显示JSON输出

时间:2012-07-13 04:14:17

标签: android json android-intent

我有一个主Activity来解析我的MySQL中的JSON数据(表跟踪纬度和经度)。现在我想将此数据传递给我的MapActivity并将其显示在Google Maps上。任何帮助都非常感谢。谢谢!

这是我的JSONactivity

public class JSONActivity extends Activity{
  private JSONObject jObject;
  private String xResult ="";
  private String url = "http://10.0.2.2/labiltrack/daftartracking.php";
  @Override
  public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.daftartrack);
    TextView txtResult = (TextView)findViewById(R.id.TextViewResult);
    //url += "?lattitude=" + UserData.getEmail();
    xResult = getRequest(url);
    try {
      parse(txtResult);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

 private void parse(TextView txtResult) throws Exception {
    // TODO Auto-generated method stub
    jObject = new JSONObject(xResult);
    JSONArray menuitemArray = jObject.getJSONArray("joel");
    String sret="";
    for (int i = 0; i < menuitemArray.length(); i++) {
      sret +=menuitemArray.getJSONObject(i).getString("lattitude").toString()+" : ";
      System.out.println(menuitemArray.getJSONObject(i).
        getString("lattitude").toString());
      System.out.println(menuitemArray.getJSONObject(i).
        getString("longitude").toString());
      sret +=menuitemArray.getJSONObject(i).getString("lattitude").toString()+"\n";
  }
  txtResult.setText(sret);
}
private String getRequest(String url) {
  // TODO Auto-generated method stub
  String sret="";
  HttpClient client = new DefaultHttpClient();
  HttpGet request = new HttpGet(url);
  try{
    HttpResponse response = client.execute(request);
    sret =request(response);
  }catch(Exception ex){
    Toast.makeText(this,"jo "+sret, Toast.LENGTH_SHORT).show();
  }
  return sret;
}

private String request(HttpResponse response) {
  // TODO Auto-generated method stub
  String result = "";
  try{
    InputStream in = response.getEntity().getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    StringBuilder str = new StringBuilder();
    String line = null;
    while((line = reader.readLine()) != null){
      str.append(line + "\n");
    }
    in.close();
    result = str.toString();
  }catch(Exception ex){
    result = "Error";
  }
  return result;
}

这是我的mapActivity

public class mapactivity extends MapActivity {
  private MapView mapView;
  MapController mc;
  GeoPoint p;
  class MapOverlays extends com.google.android.maps.Overlay {
    @Override
    public boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when) {
      super.draw(canvas, mapView, shadow);
      //translate the geopoint to screen pixels
      Point screenPts = new Point();
      mapView.getProjection().toPixels(p, screenPts);
      Bitmap bmp = BitmapFactory.decodeResource(getResources (), R.drawable.pin_red);
      canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
      return true;
    }
    @Override
    public boolean onTouchEvent(MotionEvent event, MapView mapView) {
      //---when user lifts his finger---
      if (event.getAction() == 1) {
        GeoPoint p = mapView.getProjection().fromPixels(
          (int) event.getX(), (int) event.getY());
        Toast.makeText(getBaseContext(),
          p.getLatitudeE6() / 1E6 + "," + p.getLongitudeE6() /1E6 ,
          Toast.LENGTH_SHORT).show();
        mc.animateTo(p);
        Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
        try {
          List<Address> addresses = geoCoder.getFromLocation(
            p.getLatitudeE6()  / 1E6, p.getLongitudeE6() / 1E6, 1);
          String add = "";
          if (addresses.size() > 0) {
            for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
              add += addresses.get(0).getAddressLine(i) + "\n";
          }
          Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
          e.printStackTrace();
        }
        return true;
      } else
        return false;
      }
    }         

  /** Called when the activity is first created. */
  @SuppressWarnings("deprecation")
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mapview1);
    mapView = (MapView) findViewById(R.id.mapView);
    LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
    View zoomView = mapView.getZoomControls();
    zoomLayout.addView(zoomView, new LinearLayout.LayoutParams(
      LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    mapView.displayZoomControls(true);
    mc = mapView.getController();
    String coordinates[] = {"5.550381", "95.318699"};
    double lat = Double.parseDouble(coordinates[0]);
    double lng = Double.parseDouble(coordinates[1]);
    p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
    mc.animateTo(p);
    mc.setZoom(14);
    mapView.invalidate();
    MapOverlays mapOverlay = new MapOverlays();
    List<Overlay> listOfOverlays = mapView.getOverlays();
    listOfOverlays.clear();
    listOfOverlays.add(mapOverlay);
    mapView.invalidate();
  }
  public void btnSatelitClick(View v){
    mapView.setSatellite(true);
    mapView.setStreetView(false);
  }
  public void btnjalanClick (View v){
    mapView.setSatellite(false);
    mapView.setStreetView(true);
  }
  protected boolean isRouteDisplayed() {
    //auto generate method
    return false;
  }
}

我的JSONActivity将来自MySQL(字段“纬度”和“经度”)的数据导入列表视图,但现在我想在Google地图上显示该数据(纬度和经度)。我怎么能这样做?请帮助我,提前谢谢!

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解您的问题,但在较高的层面上,您可以执行以下操作:

1)您的JSON活动从网络调用获取数据并将信息存储在数据库中并填充列表视图。根据我在代码中看到的内容,请注意一点:不要直接在主UI线程中进行网络调用。在蜂窝和更高版本上,这将抛出异常。我建议使用AsyncTask

2)您可以捕获ListView onListItemClick,它可以为您提供元素的位置,然后您可以查找列表数据集合以确定要求显示的纬度和经度。然后,您需要使用startActivity启动mapActivity并将附加内容中的数据传递给意图。

3)在mapActivity中,获取意图并阅读额外内容,即纬度和经度,并将这些值用于coordinates变量。