如何将OnPostExecute()的LatLng结果发送到url

时间:2015-04-17 07:24:03

标签: google-maps android-asynctask

我正在使用 Googlemaps v2 我必须将 latlng 的值,即:routePoints发送到服务器。

我在 onlocationchanged()中显示 latlng
我需要将这些值发送到URL。

这是我的代码。

public class MapDetail extends FragmentActivity implements
    GooglePlayServicesClient.ConnectionCallbacks,

    GooglePlayServicesClient.OnConnectionFailedListener, LocationListener,
    OnMapLongClickListener {
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
private static final String TAG_SUCCESS = "successfully stored";
GoogleMap mMap;
LocationClient mLocationClient;
Marker marker;
LatLng ll; 
LatLng point1;
LatLng cLocation, pLocation;
List<LatLng> routePoints;
private List<MarkerOptions> markerOptions = new ArrayList<MarkerOptions>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (serviceOk()) {
        setContentView(R.layout.activity_map);
        if (initMap()) {

            // mMap.setMyLocationEnabled(true);
            mLocationClient = new LocationClient(this, this, this);
            mLocationClient.connect();
        } else {
            Toast.makeText(this, "Map Not Avialable !!", Toast.LENGTH_LONG)
                    .show();
        }

    } else {
        setContentView(R.layout.activity_main);
    }

    routePoints = new ArrayList<LatLng>();

}

public boolean serviceOk() {
    int isAvailable = GooglePlayServicesUtil
            .isGooglePlayServicesAvailable(this);
    if (isAvailable == ConnectionResult.SUCCESS) {
        return true;
    } else if (GooglePlayServicesUtil.isUserRecoverableError(isAvailable)) {
        Dialog dialog = GooglePlayServicesUtil.getErrorDialog(isAvailable,
                this, GPS_ERRORDIALOG_REQUEST);
        dialog.show();
    } else {
        Toast.makeText(this, "can not connect google play services",
                Toast.LENGTH_LONG).show();
    }
    return false;

}

private boolean initMap() {
    if (mMap == null) {
        SupportMapFragment mapFrag = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mMap = mapFrag.getMap();
        if (mMap != null) {

        }
    }
    return (mMap != null);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.activity:
        Intent i = new Intent(this, ComInfo.class);
        startActivity(i);
        break;
    default:
        break;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onConnectionFailed(ConnectionResult arg0) {

}

@Override
public void onConnected(Bundle arg0) {
    Toast.makeText(this, "Connected To Location Service", Toast.LENGTH_LONG)
            .show();
    LocationRequest request = LocationRequest.create();
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    request.setInterval(5000);
    request.setFastestInterval(1000);
    mLocationClient.requestLocationUpdates(request, this);
    mMap.setOnMapLongClickListener(this);

}

@Override
public void onDisconnected() {

}

@Override
public void onLocationChanged(Location location) {
    String msg = "Location:" + location.getLatitude() + ","
            + location.getLongitude();
    Toast.makeText(this, msg, Toast.LENGTH_LONG).show();


    drawCircle(location);
    for (int i = 0; i < this.markerOptions.size(); i++) {
        mMap.addMarker(markerOptions.get(i));
    }

    LatLng ll1 = new LatLng(location.getLatitude(), location.getLongitude());
    routePoints.add(ll1);

    for (int i = 0; i < routePoints.size(); i++) {
        Polyline route = mMap.addPolyline(new PolylineOptions().width(5)
                .color(Color.GREEN).geodesic(true).zIndex(10));
        route.setPoints(routePoints);
                }
    new AttemptSave().execute();
}

private void drawCircle(Location location) {
    mMap.clear();
    LatLng currentPosition = new LatLng(location.getLatitude(),
            location.getLongitude());
    mMap.addCircle(new CircleOptions().center(currentPosition).radius(50)
            .fillColor(0x330000FF).strokeColor(Color.BLUE).strokeWidth(3));

    double latitude = location.getLatitude();
    double longitude = location.getLongitude();
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(new LatLng(latitude, longitude)).zoom(15f).build();
    mMap.animateCamera(CameraUpdateFactory
            .newCameraPosition(cameraPosition));

}

@Override
protected void onPause() {
    mLocationClient.disconnect();
    super.onPause();
}

@Override
protected void onResume() {
    mLocationClient.connect();
    super.onResume();
}

@Override
protected void onStop() {
    mLocationClient.disconnect();
    super.onStop();
}

@Override
public void onMapLongClick(LatLng point) {

    this.point1 = point;

    MarkerOptions moMarkerOptions = new MarkerOptions()
            .position(point)
            .title("se guarda el punto")
            .icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_RED));

    Marker marker = mMap.addMarker(moMarkerOptions);
    this.markerOptions.add(moMarkerOptions);
    new AttemptSave().execute("test");
}



class AttemptSave extends AsyncTask<String, String, String> {

    @Override
    protected String doInBackground(String... args0) {
        String res = sendJSON();
        Log.d("InputStream", res);
        return res;

    }
    private String sendJSON() {
        InputStream inputStream = null;
        String result = "";

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("MY_URL");

            String json = "";

            json = this.getJSONObject().toString();

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

            nameValuePairs.add(new BasicNameValuePair("data", json));

            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse httpResponse = httpclient.execute(httpPost);
            inputStream = httpResponse.getEntity().getContent();

            if (inputStream != null)
                result = convertInputStreamToString(inputStream);
            else
                result = "Did not work!";
        } catch (IOException e) {
            Log.d("InputStream", e.getLocalizedMessage()); // e.getLocalizedMessage());
        }
        return result;
    }

    private String convertInputStreamToString(InputStream inputStream)
            throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;
        inputStream.close();
        return result;
    }

    private JSONObject getJSONObject() {
        JSONObject obj = new JSONObject();
        try {
            obj.put("id", 1);
            obj.put("lat", point1.latitude);
            obj.put("long", point1.longitude);
            obj.put("track", "");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }
     protected void onPostExecute(List<List<HashMap<String, String>>> result) {
            ArrayList<LatLng> points = null;
            PolylineOptions lineOptions = null;
            MarkerOptions markerOptions = new MarkerOptions();

            for(int i=0;i<result.size();i++){
                points = new ArrayList<LatLng>();
                lineOptions = new PolylineOptions();

                List<HashMap<String, String>> path = result.get(i);

                for(int j=0;j<path.size();j++){
                    HashMap<String,String> point = path.get(j);

                    double lat = Double.parseDouble(point.get("lat"));
                    double lng = Double.parseDouble(point.get("lng"));
                    LatLng position = new LatLng(lat, lng);

                    points.add(position);
                    new Saveroute().execute();
                }

                // Adding all the points in the route to LineOptionslineOptions.addAll(points) lineOptions.width(2);lineOptions.color(Color.RED);
            }

        }
    }
class Saveroute extends AsyncTask<String, String, String >{

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub

        return null;
    }}

}

1 个答案:

答案 0 :(得分:0)

onLocationChanged(Location location)中,您没有初始化point1,请按照与onMapLongClick()

相同的方式进行操作
@Override
public void onLocationChanged(Location location) { 
       point1=new LatLng(location.getLatitude(),location.getLongitude());
       ...
}
相关问题