0

I have a main Activity which parses the JSON data from my MySQL (table tracking latitude and longitude). Now I want to pass this data to my MapActivity and display it on Google Maps. Any help is highly appreciated. Thanks!

This my 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;
}

And this my 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;
  }
}

My JSONActivity gets data from MySQL (field "latitude" and "longitude") into a listview, but now I want to display that data (latitude and longitude) on a Google map. How could I do this? Please help me, thanks in advance!

1 Answer 1

0

I am not sure if I understand your question but at a high level, you can do the following:

1) Your JSON Activity gets the data from a network call and stores the information in the database and populates the list view. One note of caution here based on what I see in the code: Do not make network calls directly in your main UI thread. On honeycomb and higher versions, this will throw an Exception. I suggest to use AsyncTask for that.

2) You can trap the ListView onListItemClick, which can give you the position of the element and then you can lookup your list data collection to figure out what latitude and longitude was asked to be displayed. You will then need to use startActivity to launch your mapActivity and pass the data in the Extras to the intent.

3) In your mapActivity, get the Intent and read the extras i.e. latitude and longitude and use those values for your coordinates variable.

Sign up to request clarification or add additional context in comments.

1 Comment

hii, can you do this ? or just a little example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.