0

当我运行此代码时,它显示错误。请帮帮我。我试图在安卓操作系统的谷歌地图中找到从一个地方到另一个地方的路线。

我已经提交了我所有的代码。我想我不需要提交我的 xml 布局代码。比方说,它只是地图视图。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.screenfive);
    coder = new Geocoder(this);
    EditText startedit =(EditText) findViewById(R.id.startedit);
    EditText finishedit =(EditText) findViewById(R.id.finishedit);
    Button go=(Button) findViewById(R.id.go);
    Spinner spinnercategory = (Spinner) findViewById (R.id.spinnercategory);
    Category =(TextView) findViewById(R.id.category);


    mapView = (MapView) findViewById(R.id.mymapview2);
    mapView.setBuiltInZoomControls(true);
    mMapController = mapView.getController();
    //          mMapController.setZoom(18);
    // Two points in Mexico about 1km apart

            //Take any two points

    GeoPoint point1 = new GeoPoint(19240000,-99120000);
    GeoPoint point2 = new GeoPoint(19241000,-99121000);

    mMapController.setCenter(point2);
    // Pass the geopoints to the overlay class
    mapOvlay = new MapOverlay(point1, point2);
    mapView.getOverlays().add(mapOvlay);
    spinnercategory.setOnItemSelectedListener(this);

    ArrayAdapter aa=new ArrayAdapter(this, android.R.layout.simple_spinner_item,category);
    aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnercategory.setAdapter(aa);
    go.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            new GetLatLong().execute();


        }
    });

}

public void onItemSelected(AdapterView<?> parent, View v, int position,
        long id) {
    //          Category.setText(category[position]);

}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

}

@Override
protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;
}
public class MapOverlay extends com.google.android.maps.Overlay {

    private GeoPoint mGpt1;
    private GeoPoint mGpt2;

    protected MapOverlay(GeoPoint gp1, GeoPoint gp2 ) {
        mGpt1 = gp1;
        mGpt2 = gp2;
    }
    @Override
    public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
            long when) {
        super.draw(canvas, mapView, shadow);
        Paint paint;
        paint = new Paint();
        paint.setColor(Color.BLUE);
        paint.setAntiAlias(true);
        paint.setStyle(Style.STROKE);
        paint.setStrokeWidth(2);
        Point pt1 = new Point();
        Point pt2 = new Point();
        Projection projection = mapView.getProjection();
        projection.toPixels(mGpt1, pt1);
        projection.toPixels(mGpt2, pt2);
        canvas.drawLine(pt1.x, pt1.y, pt2.x, pt2.y, paint);
        return true;
    }


    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
}


class GetLatLong extends AsyncTask<String, Void, String>
{


protected void onPreExecute() {
    // TODO Auto-generated method stub
    super.onPreExecute();
    ProgressDialog=new ProgressDialog(MapActivityForScreen5.this);
    ProgressDialog.setTitle("Loading");
    ProgressDialog.show();
}

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

        try{
            addressgone = coder.getFromLocationName(startedit.getText().toString(),5);
            if (addressgone == null) {

            }
            Address locationgone = addressgone.get(0);
            locationgone.getLatitude();
            locationgone.getLongitude();

            pone = new GeoPoint((int) (locationgone.getLatitude() * 1E6),
                    (int) (locationgone.getLongitude() * 1E6));
        }
        catch(Exception e)
        {

        }

        try{
            addressgtwo = coder.getFromLocationName(startedit.getText().toString(),5);
            if (addressgtwo == null) {

            }
            Address locationgtwo = addressgtwo.get(0);
            locationgtwo.getLatitude();
            locationgtwo.getLongitude();

            ptwo = new GeoPoint((int) (locationgtwo.getLatitude() * 1E6),
                    (int) (locationgtwo.getLongitude() * 1E6));
        }
        catch(Exception e)
        {

        }

        return null;
    }
    @Override
        protected void onPostExecute(String result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            ProgressDialog.cancel();

            mMapController.setCenter(ptwo);
            // Pass the geopoints to the overlay class
            mapOvlay = new MapOverlay(pone, ptwo);
            mapView.getOverlays().add(mapOvlay);
        }
}

}

4

2 回答 2

1

从工作线程访问 UI 组件是一种糟糕的编程实践。AsyncTask工作线程独立于 UI 线程运行,它们可能无法访问 textView 并因此startedit.getText().toString()返回 null。

好的风格是你在execute()方法中传递这些值,所以试试

`new GetLatLong().execute(startedit.getText().toString());`

在 中doInBackground(String... params),正确的实现将是

    String value=params[0];
try{
        addressgone = coder.getFromLocationName(value,5);
        if (addressgone == null) {

 }`...
于 2012-12-24T23:09:33.703 回答
0

最后我做到了。我发布这个答案是为了对你有用。我通过使用 JSON(在 EditText 中获取纬度和经度)来做到这一点,并使用谷歌地图服务绘制了 2 个地方之间的路线。

这是代码:

    JSONObject jsonObjectto = getLocationInfo(ToEditTextt.getText().toString());
                JSONObject jsonObjectfrom = getLocationInfo(FromEditTextt.getText().toString());
                Log.v("P1 Value",jsonObjectto+"");
                getLatLongto(jsonObjectto);
                getLatLongfrom(jsonObjectfrom);
                try{
                    gp1 = new GeoPoint((int) (latittudefrom * 1E6),
                            (int) (longittutefrom * 1E6));

                    gp2 = new GeoPoint((int) (latittudeto * 1E6),
                            (int) (longittuteto * 1E6));


                    Log.v("To Value",gp2+"");

                    Log.v("From Value",gp1+"");
                    try{
                        mode=Modes.drivingmode;
                        if(routeoverlayy!=null){
                            mapView.getOverlays().remove(routeoverlayy);
                        }


                        if(gp1!=null && gp2!=null){
                            Route route = directions(gp1, gp2,mode);

                            routeoverlayy = new RouteOverlay(route, Color.BLUE);
                            mapView.postInvalidate();
                            //                                      routeOverlay.redrawPath(mMapView);
                            mapView.postInvalidate();
                            mapcontrol.setCenter(gp1);
                            mapcontrol.setZoom(10);

                            mapcontrol.animateTo(gp1);
                            mapView.getOverlays().add(routeoverlayy);
                            pw.dismiss();
                        }
                    }
                    catch(Exception e){

                    }
                }
                catch(Exception e)
                {

                }


                // search pressed and perform your functionality.  
                return true;
            } 
            /*InputMethodManager
              imm=(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);

              imm.hideSoftInputFromWindow(.getWindowToken(), 0); */
            return false; 
        }


    });
}

public static JSONObject getLocationInfo(String address) {
    StringBuilder stringBuilder = new StringBuilder();
    try {

        address = address.replaceAll(" ","%20");    

        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


        response = client.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return jsonObject;
}
public static boolean getLatLongto(JSONObject jsonObject) {

    try {

        longittuteto = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");

        Log.v("Longitude", longittuteto+"");

        latittudeto = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");

        Log.v("Latitude", latittudeto+"");

    } catch (JSONException e) {
        return false;

    }

    return true;
}

public static boolean getLatLongfrom(JSONObject jsonObject) {

    try {

        longittutefrom = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lng");

        Log.v("Longitude", longittutefrom+"");

        latittudefrom = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
                .getJSONObject("geometry").getJSONObject("location")
                .getDouble("lat");

        Log.v("Latitude", latittudefrom+"");

    } catch (JSONException e) {
        return false;

    }

    return true;
}

public class RouteOverlay extends Overlay{

    /** GeoPoints representing this routePoints. **/
    private final List<GeoPoint> routePoints;
    /** Colour to paint routePoints. **/
    private int colour;
    /** Alpha setting for route overlay. **/
    private static final int ALPHA = 120;
    /** Stroke width. **/
    private static final float STROKE = 4.5f;
    /** Route path. **/
    private final Path path;
    /** Point to draw with. **/
    private final Point p;
    /** Paint for path. **/
    private final Paint paint;


    /**
     * Public constructor.
     * 
     * @param route Route object representing the route.
     * @param defaultColour default colour to draw route in.
     */

    public RouteOverlay(final Route route, final int defaultColour) {
        super();
        routePoints = route.getPoints();
        colour = defaultColour;
        path = new Path();
        p = new Point();
        paint = new Paint();
    }

    @Override
    public final void draw(final Canvas c, final MapView mv,
            final boolean shadow) {
        super.draw(c, mv, shadow);

        paint.setColor(colour);
        paint.setAlpha(ALPHA);
        paint.setAntiAlias(true);
        paint.setStrokeWidth(STROKE);
        paint.setStyle(Paint.Style.STROKE);

        redrawPath(mv);
        c.drawPath(path, paint);
    }

    /**
     * Set the colour to draw this route's overlay with.
     * 
     * @param c  Int representing colour.
     */
    public final void setColour(final int c) {
        colour = c;
    }

    /**
     * Clear the route overlay.
     */
    public final void clear() {
        routePoints.clear();
    }

    /**
     * Recalculate the path accounting for changes to
     * the projection and routePoints.
     * @param mv MapView the path is drawn to.
     */

    private void redrawPath(final MapView mv) {
        final Projection prj = mv.getProjection();
        path.rewind();
        final Iterator<GeoPoint> it = routePoints.iterator();
        prj.toPixels(it.next(), p);
        path.moveTo(p.x, p.y);
        while (it.hasNext()) {
            prj.toPixels(it.next(), p);
            path.lineTo(p.x, p.y);
        }
        path.setLastPoint(p.x, p.y);
    }

}
private  Route directions(final GeoPoint start, final GeoPoint dest,int mode) {

    Parser parser;
    String jsonURL = "http://maps.googleapis.com/maps/api/directions/json?";
    final StringBuffer sBuf = new StringBuffer(jsonURL);
    sBuf.append("origin=");
    sBuf.append(start.getLatitudeE6()/1E6);
    sBuf.append(',');
    sBuf.append(start.getLongitudeE6()/1E6);
    sBuf.append("&destination=");
    sBuf.append(dest.getLatitudeE6()/1E6);
    sBuf.append(',');
    sBuf.append(dest.getLongitudeE6()/1E6);
    if(mode==1){
        sBuf.append("&sensor=true&mode=driving");
    }
    if(mode==3){
        System.currentTimeMillis();

        try{
            sBuf.append("&sensor=true&departure_time=1343605500&mode=google.maps.TravelMode.TRANSIT&vehicle.type=VehicleType.BUS");
        }catch(Exception e){
            Toast.makeText(ScreenOfOnMyWay.this, "Route not available", Toast.LENGTH_SHORT).show();
        }
    }
    if(mode==2){
        sBuf.append("&sensor=true&mode=walking");
    }
    parser = new GoogleParser(sBuf.toString());
    Route r =  parser.parse();
    return r;
}   
于 2013-01-02T15:11:59.623 回答