0

我正在使用 Google Map V2 并在两个位置和互联网连接(仅调用 web 服务)之间绘制路线,并且没有后台服务以及线程和接收器。

但它仍然占用了太多的内存。请看附图。有什么办法可以减少。

public class LocationMapFragment extends FragmentActivity {


    private ArrayList<LatLng> latLongArrayList = new ArrayList<LatLng>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.map_layout);

        context = this;

        Location location = Utils.getGPSLocation(context);
        if(location != null) {
            currentLatitude = location.getLatitude();
            currentLongitude = location.getLongitude();
            setLayout();
        }

    }


    public void setLayout() {
        display = this.getWindowManager().getDefaultDisplay();

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

        if(getIntent().getBooleanExtra("isFromSameActivity", false)) {
            // Getting reference to SupportMapFragment of the activity_main
            map.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("You are Here"));

            latitude = getIntent().getDoubleExtra("selectLatitude", 0);
            longitude = getIntent().getDoubleExtra("selectLongitude", 0);

            latLongArrayList.add(new LatLng(latitude, longitude));

            if(searchLatitude != 0 && searchLongitude != 0) {
                new SearchGetNearestATM().execute();
                latLongArrayList.add(new LatLng(searchLatitude, searchLongitude));
            } else {
                new GetNearestATM().execute();
                if(currentLatitude != 0 && currentLongitude != 0)
                    latLongArrayList.add(new LatLng(currentLatitude, currentLongitude));
            }
        }
        else if(!getIntent().getBooleanExtra("isAtmClick", false)) {
            // Getting reference to SupportMapFragment of the activity_main
            map.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("You are Here"));
            if(searchLatitude != 0 && searchLongitude != 0) {
                new SearchGetNearestATM().execute();
                latLongArrayList.add(new LatLng(searchLatitude, searchLongitude));
            } else {
                new GetNearestATM().execute();
                if(currentLatitude != 0 && currentLongitude != 0)
                    latLongArrayList.add(new LatLng(currentLatitude, currentLongitude));
            }
        }
        else {
            isATMCLick = true;
            latitude = getIntent().getDoubleExtra("selectLatitude", 0);
            longitude = getIntent().getDoubleExtra("selectLongitude", 0);

            if(searchLatitude != 0 && searchLongitude != 0)
                latLongArrayList.add(new LatLng(searchLatitude, searchLongitude));
            else {
                if(currentLatitude != 0 && currentLongitude != 0)
                    latLongArrayList.add(new LatLng(currentLongitude, currentLongitude));
            }
            map.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("You are Here"));

            double latitudeArray[] = getIntent().getDoubleArrayExtra("latitude");
            double longitudeArray[] = getIntent().getDoubleArrayExtra("longitude");
            String namesArray[] = getIntent().getStringArrayExtra("names");
            String typeArray[] = getIntent().getStringArrayExtra("typeList");

            for(int index = 0; index < latitudeArray.length; index++) {
                latLongArrayList.add(new LatLng(latitudeArray[index], longitudeArray[index]));
                if(!getIntent().getStringExtra("selectName").equals(namesArray[index])) {

                    if(typeArray[index].equals("1")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.first)));
                    } else if(typeArray[index].equals("2")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.second)));
                    } else if(typeArray[index].equals("3")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.third)));
                    } else if(typeArray[index].equals("4")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.fourth)));
                    } else if(typeArray[index].equals("5")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.fifth)));
                    } else if(typeArray[index].equals("6")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.sixth)));
                    } else if(typeArray[index].equals("7")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.seventh)));
                    } else if(typeArray[index].equals("8")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.eight)));
                    } else if(typeArray[index].equals("9")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ninth)));
                    }
                }
                else {
                    if(typeArray[index].equals("1")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.first)));
                    } else if(typeArray[index].equals("2")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.second)));
                    } else if(typeArray[index].equals("3")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.third)));
                    } else if(typeArray[index].equals("4")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.fourth)));
                    } else if(typeArray[index].equals("5")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.fifth)));
                    } else if(typeArray[index].equals("6")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.sixth)));
                    } else if(typeArray[index].equals("7")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.seventh)));
                    } else if(typeArray[index].equals("8")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\nClick to Get Directions") 
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.eight)));
                    } else if(typeArray[index].equals("9")) {
                        map.addMarker(new MarkerOptions().position(new LatLng(
                                latitudeArray[index], longitudeArray[index])).title(namesArray[index] + "\net Directions")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.n)));
                    }

                    //Driving Direction
                    new GetDrivingDirectionsAsync().execute();

                    map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
                    //Marker Click Listener
                    map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
                        @Override
                        public void onInfoWindowClick(Marker marker) {
                            LatLng latLng = marker.getPosition();
                            latitude = latLng.latitude;
                            longitude = latLng.longitude;
                            Intent intent = new Intent(context, AndroidTabLayoutActivity.class);
                            intent.putExtra("isFromSameActivity", true);
                            intent.putExtra("selectLatitude", latitude);
                            intent.putExtra("selectLongitude", longitude);
                            startActivity(intent);
                        }
                    });
                }
            }
        }
    }

    @Override
    public boolean onPrepareOptionsMenu (Menu menu) {
        if(!isATMCLick) {
            menu.removeItem(R.id.navigate);
        }
        menu.removeItem(R.id.settings);
        return super.onCreateOptionsMenu(menu);
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.navigate:
                startActivity(new Intent("android.intent.action.VIEW", Uri.parse("http://maps.google.com/maps?daddr=" + latitude + "," + longitude + "&saddr=" + currentLatitude + "," + currentLongitude)));
                break;
            case R.id.settings:
                startActivity(new Intent(context, ChangeLanguageActivity.class));
                break;
        }
        return true;
    }

    /**
     * It fetch the nearest ATM on basis of latitude and longitude.
     * @author Ankit
     */
    private class GetNearestATM extends AsyncTask<Void, Void, Void> {

        String xmlResponse;
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            progressDialog =  new ProgressDialog(context);
            progressDialog.setTitle(getString(R.string.app_name));
            progressDialog.setMessage(getString(R.string.please_wait));
            progressDialog.setIndeterminate(true);
            progressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            if(currentLatitude != 0 && currentLongitude != 0) {
                xmlResponse = new Utils().getXmlFromUrl("http://www.bankomaty.sk/service/?n=" + currentLatitude + "&e=" + currentLongitude +
                        "&t=" + Utils.getFilterSettings(context));
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, getString(R.string.no_gps_fetch), Toast.LENGTH_LONG).show();
                    }
                });
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            try { 
                progressDialog.cancel();
            } catch(Exception e) { 

            }
            if(xmlResponse != null && !xmlResponse.equals("")) {
                XMLParser xmlParser = new XMLParser();
                Document document = xmlParser.getDomElement(xmlResponse);

                if(document != null) {
                    NodeList nodeList = document.getElementsByTagName("bankomaty");
                    if(nodeList.getLength() > 0) {
                        nodeList = document.getElementsByTagName("bankomat");
                        for(int index = 0; index < nodeList.getLength(); index++) {
                            try {
                                Element element = (Element) nodeList.item(index);
                                String locationCoordinates[] = xmlParser.getValue(element, "latlng").replaceAll(" ", "").split(",");
                                double latitude = Double.valueOf(locationCoordinates[0].trim()).doubleValue();
                                double longitude = Double.valueOf(locationCoordinates[1].trim()).doubleValue();

                                latLongArrayList.add(new LatLng(latitude, longitude));

                                String type = xmlParser.getValue(element, "type");

                                if(type.equals("1")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.first)));
                                } else if(type.equals("2")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.second)));
                                } else if(type.equals("3")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.third)));
                                } else if(type.equals("4")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.fourth)));
                                } else if(type.equals("5")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.fifth)));
                                } else if(type.equals("6")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.sixth)));
                                } else if(type.equals("7")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.seventh)));
                                } else if(type.equals("8")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.eight)));
                                } else if(type.equals("9")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ninth)));
                                }
                            } catch(Exception e) {
                                //Exception
                            }
                        }

                        if(!getIntent().getBooleanExtra("isFromSameActivity", false))
                            setCameraAnimation(map);

                        if(getIntent().getBooleanExtra("isFromSameActivity", false))
                            new GetDrivingDirectionsAsync().execute();

                        map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
                        //Marker Click Listener
                        map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
                            @Override
                            public void onInfoWindowClick(Marker marker) {
                                LatLng latLng = marker.getPosition();
                                latitude = latLng.latitude;
                                longitude = latLng.longitude;
                                Intent intent = new Intent(context, AndroidTabLayoutActivity.class);
                                intent.putExtra("isFromSameActivity", true);
                                intent.putExtra("selectLatitude", latitude);
                                intent.putExtra("selectLongitude", longitude);
                                startActivity(intent);
                            }
                        });
                    }
                }
            }
        }
    }


    /**
     * It fetch the nearest ATM on basis of latitude and longitude from seach on basis of street and city.
     * @author Ankit
     */
    private class SearchGetNearestATM extends AsyncTask<Void, Void, Void> {

        String xmlResponse;
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            progressDialog =  new ProgressDialog(context);
            progressDialog.setTitle(getString(R.string.app_name));
            progressDialog.setMessage(getString(R.string.please_wait));
            progressDialog.setIndeterminate(true);
            progressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            if(LocationMapFragment.searchLatitude != 0 && LocationMapFragment.searchLongitude != 0) {
                xmlResponse = new Utils().getXmlFromUrl("http://www.bankomaty.sk/service/?n=" + LocationMapFragment.searchLatitude + "&e=" + LocationMapFragment.searchLongitude +
                        "&t=" + Utils.getFilterSettings(context));
            } else {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, getString(R.string.no_gps_fetch), Toast.LENGTH_LONG).show();
                    }
                });
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            try { 
                progressDialog.cancel();
            } catch(Exception e) { 

            }
            if(xmlResponse != null && !xmlResponse.equals("")) {
                XMLParser xmlParser = new XMLParser();
                Document document = xmlParser.getDomElement(xmlResponse);

                if(document != null) {
                    NodeList nodeList = document.getElementsByTagName("bankomaty");
                    if(nodeList.getLength() > 0) {
                        nodeList = document.getElementsByTagName("bankomat");
                        for(int index = 0; index < nodeList.getLength(); index++) {
                            try {
                                Element element = (Element) nodeList.item(index);
                                String locationCoordinates[] = xmlParser.getValue(element, "latlng").replaceAll(" ", "").split(",");
                                double latitude = Double.valueOf(locationCoordinates[0].trim()).doubleValue();
                                double longitude = Double.valueOf(locationCoordinates[1].trim()).doubleValue();

                                latLongArrayList.add(new LatLng(latitude, longitude));

                                String type = xmlParser.getValue(element, "type");

                                if(type.equals("1")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.first)));
                                } else if(type.equals("2")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.second)));
                                } else if(type.equals("3")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.third)));
                                } else if(type.equals("4")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.fourth)));
                                } else if(type.equals("5")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.fifth)));
                                } else if(type.equals("6")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.sixth)));
                                } else if(type.equals("7")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.seventh)));
                                } else if(type.equals("8")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.eight)));
                                } else if(type.equals("9")) {
                                    map.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title(new String(xmlParser.getValue(element, "name").getBytes("ISO-8859-1")) + "\nClick to Get Directions")
                                            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ninth)));
                                }
                            } catch(Exception e) {
                                //Exception
                            }
                        }

                        if(!getIntent().getBooleanExtra("isFromSameActivity", false))
                            setCameraAnimation(map);

                        if(getIntent().getBooleanExtra("isFromSameActivity", false))
                            new GetDrivingDirectionsAsync().execute();

                        map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));

                        //Marker Click Listener
                        map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
                            @Override
                            public void onInfoWindowClick(Marker marker) {
                                LatLng latLng = marker.getPosition();
                                latitude = latLng.latitude;
                                longitude = latLng.longitude;
                                Intent intent = new Intent(context, AndroidTabLayoutActivity.class);
                                intent.putExtra("isFromSameActivity", true);
                                intent.putExtra("selectLatitude", latitude);
                                intent.putExtra("selectLongitude", longitude);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                            }
                        });
                    }
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.getParent().onBackPressed();
    }

    /**
     * Async Task
     */
    private class GetDrivingDirectionsAsync extends AsyncTask<Void, Void, Void> {

        ProgressDialog progressDialog;
        Document document;
        GMapV2Direction md;

        @Override
        protected void onPreExecute() {
            progressDialog =  new ProgressDialog(context);
            progressDialog.setTitle(getString(R.string.app_name));
            progressDialog.setMessage(getString(R.string.please_wait));
            progressDialog.setIndeterminate(true);
            progressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            LatLng fromPosition = null;
            if(searchLatitude != 0 && searchLongitude != 0)
                fromPosition = new LatLng(searchLatitude, searchLongitude);
            else
                fromPosition = new LatLng(currentLatitude, currentLongitude);
            LatLng toPosition = new LatLng(latitude, longitude);

            md = new GMapV2Direction();
            document = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);
            return null;
        }

        @Override
        protected void onPostExecute(Void param) {
            try {
                progressDialog.cancel();
            } catch(Exception e) {

            }

            try {
                ArrayList<LatLng> directionPoint = md.getDirection(document);
                latLongArrayList.addAll(directionPoint);
                setCameraAnimation(map);
                PolylineOptions rectLine = new PolylineOptions().width(4).color(Color.BLUE);

                for(int i = 0 ; i < directionPoint.size() ; i++) {          
                    rectLine.add(directionPoint.get(i));
                }
                map.addPolyline(rectLine);
            } catch(Exception e) {
                setCameraAnimation(map);
            }
        }

    }

    /**
     * Driving Directions
     * @author Ankit
     */
    private class GMapV2Direction {
        public final static String MODE_DRIVING = "driving";

        public GMapV2Direction() { }

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

    /**
     * Auto Zoom
     * @param map
     */
    public void setCameraAnimation(GoogleMap map) {
        double[] minMaxLocationsPoints = getMinMaxLocationPoints();
        map.animateCamera(CameraUpdateFactory.newLatLngBounds(new LatLngBounds(new LatLng(minMaxLocationsPoints[0], 
                minMaxLocationsPoints[1]), new LatLng(minMaxLocationsPoints[2], minMaxLocationsPoints[3])),
                display.getWidth() , display.getHeight(), 10));
    }

    /**
     * Get the Min and Max Points
     * @return Min and Max Location Points
     */
    public double[] getMinMaxLocationPoints() {
        double[] points = new double[4];
        ArrayList<Double> latitudeArrayList = new ArrayList<Double>();
        ArrayList<Double> longitudeArrayList = new ArrayList<Double>();
        for(int index = 0; index < latLongArrayList.size(); index++) {
            LatLng latLong = latLongArrayList.get(index);
            latitudeArrayList.add(latLong.latitude);
            longitudeArrayList.add(latLong.longitude);
        }

        Double minLatitude = Collections.min(latitudeArrayList);
        Double maxLatitude = Collections.max(latitudeArrayList);

        Double minLongitude = Collections.min(longitudeArrayList);
        Double maxLongitude = Collections.max(longitudeArrayList);

        points[0] = minLatitude;
        points[1] = minLongitude;
        points[2] = maxLatitude;
        points[3] = maxLongitude;
    }


}

提前致谢。

4

0 回答 0