0

绘制从我的位置到目的地和 Lat Lng 目的地的路线这是来自 SQLite 的坐标 此代码 Map.java

public class Map extends FragmentActivity implements LocationListener {

    SQLiteDatabase SQL;
    GoogleMap map;
    myDBClass DB;
    Cursor cursor;
    ArrayList<LatLng> MarkerPoint;
    double latitude = 0;
    double longtitude = 0;
    GMapV2Direction md;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.show_map);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        map = ((SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map)).getMap();
        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        map.setMyLocationEnabled(true);

        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String provider = locationManager.getBestProvider(criteria, true);
        Location location = locationManager.getLastKnownLocation(provider);

        if (location != null) {
            onLocationChanged(location);
        }
        locationManager.requestLocationUpdates(provider, 5000, 0, this);

        // Destination Marker from Database SQLite
        if (MarkerPoint.size() > 1) {
            String Name = getIntent().getStringExtra("Name");
            DB = new myDBClass(this);
            SQL = DB.getWritableDatabase();

            cursor = SQL.rawQuery("SELECT *" + " FROM " + myDBClass.TABLE_NAME
                    + " WHERE " + myDBClass.NAME + " ='" + Name + "'", null);

            cursor.moveToFirst();
            /**String name = cursor.getString(cursor.getColumnIndex(myDBClass.NAME));
            double lat_db = cursor.getDouble(cursor.getColumnIndex(myDBClass.LAT));
            double lng_db = cursor.getDouble(cursor.getColumnIndex(myDBClass.LNG));
            map.addMarker(new MarkerOptions()
                    .position(new LatLng(lat_db, lng_db))
                    .title(name)
                    .icon(BitmapDescriptorFactory
                            .fromResource(R.drawable.ic_launcher)));**/
            latitude = cursor.getDouble(cursor.getColumnIndex(myDBClass.LAT));
            longtitude = cursor.getDouble(cursor.getColumnIndex(myDBClass.LNG));
            cursor.moveToNext();
            LatLng point = new LatLng(latitude, longtitude);
            drawMarker(point);
        }

        if (MarkerPoint.size() >= 2) {
            LatLng Start = MarkerPoint.get(0);
            LatLng End = MarkerPoint.get(1);

            map.addMarker(new MarkerOptions().position(Start).title("Start"));
            map.addMarker(new MarkerOptions().position(End).title("End"));

            Document doc = md.getDocument(Start, End,GMapV2Direction.MODE_DRIVING);
            int duration = md.getDurationValue(doc);
            String distance = md.getDistanceText(doc);
            String start_address = md.getStartAddress(doc);
            String copy_right = md.getCopyRights(doc);

            ArrayList<LatLng> directionPoint = md.getDirection(doc);
            PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);

            for (int i = 0; i < directionPoint.size(); i++) {
                rectLine.add(directionPoint.get(i));
            }

            map.addPolyline(rectLine);
        }

    }

    private void drawMarker(LatLng point) {
        MarkerPoint.add(point);

        // Creating MarkerOptions
        MarkerOptions options = new MarkerOptions();

        // Setting the position of the marker
        options.position(point);

        /**
         * For the start location, the color of marker is GREEN and for the end
         * location, the color of marker is RED.
         */
        if (MarkerPoint.size() == 1) {
            options.icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        } else if (MarkerPoint.size() == 2) {
            options.icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_RED));
        }

        // Add new marker to the Google Map Android API V2
        map.addMarker(options);
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub
        if (MarkerPoint.size() < 2) {

            latitude = location.getLatitude();
            longtitude = location.getLongitude();
            LatLng point = new LatLng(latitude, longtitude);

            // map.moveCamera(CameraUpdateFactory.newLatLng(point));
            // map.animateCamera(CameraUpdateFactory.zoomTo(12));

            drawMarker(point);
        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

这个代码Manifest.xml 我这个代码没问题,因为是代码bacis。

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="com.example.test.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <permission 
        android:name="com.example.test.MAPS_RECEIVE"
        android:protectionLevel="signature"/>

    <uses-feature android:glEsVersion="0x00020000" android:required="true"/>


<meta-data
           android:name="com.google.android.maps.v2.API_KEY"
           android:value="API_Key"/>
        <uses-library android:name="com.google.android.maps"/>

我已经在几天内编辑了这段代码。请帮帮我。

4

1 回答 1

0

您应该组织更多代码,分离主要功能。活动课上没有所有东西。这段代码并不完美,但也许可以帮助你重新思考你的代码,做笔记。

助手类示例:

public class DrawRouteHelper {
    /**
     * PRIVATE ATTRIBUTEQ
     */
    public final static String  MODE_DRIVING    = "driving";    // TODO: google map Driving or Walking choice
    public final static String  MODE_WALKING    = "walking";

    public Document getDocument(LatLng start, LatLng end, String mode) {

        String url = "http://maps.googleapis.com/maps/api/directions/xml?" + "origin=" + start.latitude + "," + start.longitude + "&destination=" + end.latitude + "," + end.longitude
                + "&sensor=false&units=metric&mode=driving";
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpContext localContext = new BasicHttpContext();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse response = httpClient.execute(httpPost, localContext);
            InputStream in = response.getEntity().getContent();
            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(in);
            return doc;
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public String getDurationText(Document doc) {

        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        Log.i("DurationText", node2.getTextContent());
        return node2.getTextContent();
    }

    public int getDurationValue(Document doc) {

        NodeList nl1 = doc.getElementsByTagName("duration");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        Log.i("DurationValue", node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String getDistanceText(Document doc) {

        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "text"));
        Log.i("DistanceText", node2.getTextContent());
        return node2.getTextContent();
    }

    public int getDistanceValue(Document doc) {

        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = nl1.item(0);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));
        Log.i("DistanceValue", node2.getTextContent());
        return Integer.parseInt(node2.getTextContent());
    }

    public String getStartAddress(Document doc) {

        NodeList nl1 = doc.getElementsByTagName("start_address");
        Node node1 = nl1.item(0);
        Log.i("StartAddress", node1.getTextContent());
        return node1.getTextContent();
    }

    public String getEndAddress(Document doc) {

        NodeList nl1 = doc.getElementsByTagName("end_address");
        Node node1 = nl1.item(0);
        Log.i("StartAddress", node1.getTextContent());
        return node1.getTextContent();
    }

    public String getCopyRights(Document doc) {

        NodeList nl1 = doc.getElementsByTagName("copyrights");
        Node node1 = nl1.item(0);
        Log.i("CopyRights", node1.getTextContent());
        return node1.getTextContent();
    }

    public ArrayList<LatLng> getDirection(Document doc) {

        NodeList nl1, nl2, nl3;
        ArrayList<LatLng> listGeopoints = new ArrayList<LatLng>();
        nl1 = doc.getElementsByTagName("step");
        if (nl1.getLength() > 0) {
            for (int i = 0; i < nl1.getLength(); i++) {
                Node node1 = nl1.item(i);
                nl2 = node1.getChildNodes();
                Node locationNode = nl2.item(getNodeIndex(nl2, "start_location"));
                nl3 = locationNode.getChildNodes();
                Node latNode = nl3.item(getNodeIndex(nl3, "lat"));
                double lat = Double.parseDouble(latNode.getTextContent());
                Node lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                double lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
                locationNode = nl2.item(getNodeIndex(nl2, "polyline"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "points"));
                ArrayList<LatLng> arr = decodePoly(latNode.getTextContent());
                for (int j = 0; j < arr.size(); j++) {
                    listGeopoints.add(new LatLng(arr.get(j).latitude, arr.get(j).longitude));
                }
                locationNode = nl2.item(getNodeIndex(nl2, "end_location"));
                nl3 = locationNode.getChildNodes();
                latNode = nl3.item(getNodeIndex(nl3, "lat"));
                lat = Double.parseDouble(latNode.getTextContent());
                lngNode = nl3.item(getNodeIndex(nl3, "lng"));
                lng = Double.parseDouble(lngNode.getTextContent());
                listGeopoints.add(new LatLng(lat, lng));
            }
        }
        return listGeopoints;
    }

    private int getNodeIndex(NodeList nl, String nodename) {

        for (int i = 0; i < nl.getLength(); i++) {
            if (nl.item(i).getNodeName().equals(nodename))
                return i;
        }
        return -1;
    }

    private ArrayList<LatLng> decodePoly(String encoded) {

        ArrayList<LatLng> poly = new ArrayList<LatLng>();
        int index = 0, len = encoded.length();
        int lat = 0, lng = 0;
        while (index < len) {
            int b, shift = 0, result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            }
            while (b >= 0x20);
            int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lat += dlat;
            shift = 0;
            result = 0;
            do {
                b = encoded.charAt(index++) - 63;
                result |= (b & 0x1f) << shift;
                shift += 5;
            }
            while (b >= 0x20);
            int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
            lng += dlng;
            LatLng position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
            poly.add(position);
        }
        return poly;
    }
}

如何在内部类示例中使用它:

    DrawRouteHelper             _drawRouteHelper    = new DrawRouteHelper();
    Document                    _document;
    GoogleMap                   _googleMap;

private class DrawRouteTask extends AsyncTask<String, Void, String> {
        private ProgressDialog  Dialog;
        String                  response    = "";

        @Override
        protected void onPreExecute() {

            Dialog = new ProgressDialog(ActivityGoogleMap.this);
            Dialog.setMessage(getString(R.string.msg_loading));
            Dialog.show();
        }

        @Override
        protected String doInBackground(String... urls) {

            // Get All Route values
            _document = _drawRouteHelper.getDocument(_locationFrom, _locationTo, DrawRouteHelper.MODE_DRIVING);
            response = "Success";
            return response;
        }

        @Override
        protected void onPostExecute(String result) {

            try {
                if (response.equalsIgnoreCase("Success")) {
                    ArrayList<LatLng> directionPoint = _drawRouteHelper.getDirection(_document);
                    PolylineOptions rectLine = new PolylineOptions().width(10).color(Color.RED);
                    for (int i = 0; i < directionPoint.size(); i++) {
                        rectLine.add(directionPoint.get(i));
                    }
                    // Adding route on the map
                    _googleMap.addPolyline(rectLine);
                }
            }
            catch (Exception e) {
                // TODO:ERROR TRACE ROUTE
            }
            Dialog.dismiss();
        }
    }
于 2013-08-27T15:45:23.970 回答