Java Android正在尝试使用多段线在地图上绘制/记录自行车骑行

Java Android正在尝试使用多段线在地图上绘制/记录自行车骑行,java,android,google-maps,android-maps-v2,polyline,Java,Android,Google Maps,Android Maps V2,Polyline,我仍在紧握android,并试图制作一款应用程序,在谷歌地图上画出我骑车的路径。我已成功显示地图,并可以使用以下代码在两个坐标之间绘制简单的多段线: //Draws a thin red line from London to New York. Polyline line = googlemap.addPolyline(new PolylineOptions() .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0)) .width(5) .c

我仍在紧握android,并试图制作一款应用程序,在谷歌地图上画出我骑车的路径。我已成功显示地图,并可以使用以下代码在两个坐标之间绘制简单的多段线:

//Draws a thin red line from London to New York.
Polyline line = googlemap.addPolyline(new PolylineOptions()
.add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
.width(5)
.color(Color.RED));
我试图创建一段位于“LocationChanged”方法中的代码,我假设每次位置更改时都会调用该方法,并在打开应用程序后立即开始执行该操作(位于代码底部的方法)。它获取当前位置坐标和以前的当前位置坐标,并在它们之间绘制一条多边形线

我已经在Location Changed方法中添加了一个toast,这样我就可以看到它何时运行,但是,它从来没有显示过,所以我猜代码中高层出现了一些错误,没有运行/调用它

(我已经用GPS信号在户外测试了应用程序,但它没有画出界限) (应用程序运行时没有错误,但没有画线)

我正在寻找一些帮助,让应用程序划清界限,任何帮助将不胜感激

这是我的java类文件内容:

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;

import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Calendar;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.app.Activity;
import android.view.View;
import android.widget.TextView;

public class Record_screen_activity extends FragmentActivity implements
        LocationListener, OnClickListener {

    GoogleMap googlemap, draw;

    Location currentLocation;
    Location myLocation2;

    Button sqlUpdate, sqlView, sqlModify, sqlLoad, sqlDelete, startChrono, pauseChrono;
    EditText sqlNotes, sqlRouteName, sqlLocation, sqlRow;
    TextView sqlDate;
    Chronometer sqlChrono;
    long time = 0;
    int drawing = 1;

//add above here ===========================================================

    // above I am declaring the references that I will use in this file they are
    // linked below to the

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.record_screen); // Names the layout file which
                                                // is linked to this activity


        startChrono = (Button) findViewById(R.id.b_Start);
        pauseChrono = (Button) findViewById(R.id.b_Pause);


        startChrono.setOnClickListener(this);
        pauseChrono.setOnClickListener(this);


        sqlUpdate = (Button) findViewById(R.id.bSQL_Update);
        sqlRouteName = (EditText) findViewById(R.id.etSQL_RouteName);
        sqlLocation = (EditText) findViewById(R.id.etSQL_Location);
        sqlNotes = (EditText) findViewById(R.id.etSQL_Notes);
        sqlChrono = (Chronometer) findViewById(R.id.c_Timer);
        sqlDate = (TextView) findViewById(R.id.tv_Date);

//add above here ===========================================================

        // the above lines link the buttons and EditText fields from the xml
        // Layout file to the references stated at the top of this file

        sqlView = (Button) findViewById(R.id.bSQL_View);
        sqlView.setOnClickListener(this);
        sqlUpdate.setOnClickListener(this);

        sqlRow = (EditText) findViewById(R.id.etSQL_Rowid);
        sqlModify = (Button) findViewById(R.id.bSQL_Modify);
        sqlLoad = (Button) findViewById(R.id.bSQL_Load);
        sqlDelete = (Button) findViewById(R.id.bSQL_Delete);
        // above references link buttons and tv's to the actual buttons and tv's
        // in th xml file
        sqlModify.setOnClickListener(this);
        sqlLoad.setOnClickListener(this);
        sqlDelete.setOnClickListener(this);

        SupportMapFragment mf = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.mvMain);
        googlemap = mf.getMap();
        googlemap.setMyLocationEnabled(true);
        googlemap.setMapType(GoogleMap.MAP_TYPE_TERRAIN); // map tiles type can
                                                            // be changed here
                                                            // i.e. to satalite
                                                            // view

        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location = locationManager
                .getLastKnownLocation(locationManager.getBestProvider(criteria,
                        false));
        if (location != null) {
            googlemap
                    .animateCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(location.getLatitude(), location
                                    .getLongitude()), 13));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location.getLatitude(), location
                            .getLongitude())) // Sets the center of the map to
                                                // location user
                    .zoom(17) // Sets the zoom
                    .bearing(0) // Sets the orientation of the camera to east
                    .tilt(0) // Sets the tilt of the camera to 30 degrees
                    .build(); // Creates a CameraPosition from the builder
            googlemap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));
            currentLocation = location;


        }





// Add a thin red line from London to New York.
    //  Polyline line = googlemap.addPolyline(new PolylineOptions()
    //     .add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
        //  .width(5)
             //.color(Color.RED));
// Add a thin red line from London to New York.










//setting the date 

int yy;
int mm;;
int dd;

        final Calendar c = Calendar.getInstance();
        yy = c.get(Calendar.YEAR);
        mm = c.get(Calendar.MONTH);
        dd = c.get(Calendar.DAY_OF_MONTH);

        // set current date into textview
        sqlDate.setText(new StringBuilder()
        // Month is 0 based, just add 1
                .append(dd).append("").append("/").append(mm + 1).append("/")
                .append(yy));


    }



    public void onClick(View arg0) {

    switch(arg0.getId()){

    case R.id.b_Start:
        sqlChrono.setBase(SystemClock.elapsedRealtime() + time); //mabe get rid of nanos
        sqlChrono.start();

        Dialog d = new Dialog(this);
        d.setTitle("Route Now Recording"); // sets the dialog box with
                                    // success message
        TextView tv = new TextView(this);
        tv.setText("Please Lock your Screen");
        d.setContentView(tv);
        d.show();

        //sets these variables before the loop is run


        break;







    case R.id.b_Pause:

        time = sqlChrono.getBase() - SystemClock.elapsedRealtime();
        sqlChrono.stop();

        drawing = 1;


        break;
    }






// ===============================================
// ================Update(save) button============
// ===============================================      
        switch (arg0.getId()) {
        case R.id.bSQL_Update:
            boolean didItWork = true;
            try {
                String routename = sqlRouteName.getText().toString();
                String location = sqlLocation.getText().toString();
                String notes = sqlNotes.getText().toString();
                String chrono = sqlChrono.getText().toString();
                String date = sqlDate.getText().toString();
//add above here ===========================================================

                SQL_management_activity entry = new SQL_management_activity(
                        Record_screen_activity.this);
                entry.open();
                entry.createEntry(routename, location, notes, chrono, date);
//add above here ===========================================================

                entry.close();
            } catch (Exception e) {
                didItWork = false;
                String error = e.toString();// the error string will be printed
                                            // to the dialog box to display the
                                            // error code to the user
                Dialog d = new Dialog(this);
                d.setTitle("Error ohh no..."); // sets the diaog box with
                                                // success mesasge
                TextView tv = new TextView(this);
                tv.setText(error);
                d.setContentView(tv);
                d.show();
            } finally {
                if (didItWork) {
                    // didItWork = true;
                    Dialog d = new Dialog(this);
                    d.setTitle("Saving  Route"); // sets the diaog box with
                                                // success mesasge
                    TextView tv = new TextView(this);
                    tv.setText("Status: Success");
                    d.setContentView(tv);
                    d.show();

                    Thread timer = new Thread() { // this is the same timer as
                                                    // on the spalshcren
                        public void run() { // it automaticaly moves to the
                                            // review page after 500 miliseconds
                            try {
                                sleep(1000); // duration the splash screen is
                                            // displayed for
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } finally {
                                //Intent openMain_menu = new Intent(
                                //      "com.hew235.mapapp.REVIEW_SCREEN_ACTIVITY");
                            //  startActivity(openMain_menu);
                            }

                        }
                    };
                    timer.start();

                }
            }

            break;

        // ===============================================
        // ==================View button================== the end of tutorial
        // 18 will help make a main menu button
        // ===============================================
        case R.id.bSQL_View: // opens the view page
            Intent i = new Intent("com.hew235.mapapp.REVIEW_SCREEN_ACTIVITY");
            startActivity(i);
            break;

        // ===============================================
        // ==================Load button==================
        // ===============================================
        case R.id.bSQL_Load:
            boolean didItWork2 = true;

            try {
                String s = sqlRow.getText().toString();// this string will
                                                        // return whatever is in
                                                        // the edit text
                long l = Long.parseLong(s);// converts whatever is in the above
                                            // string into a long type variable
                SQL_management_activity sma = new SQL_management_activity(this);
                sma.open();
                String returnedRoutename = sma.getRoutename(l);// method
                String returnedLocation = sma.getLocation(l);// method
                String returnedNotes = sma.getNotes(l);// method
                String returnedChrono = sma.getChrono(l);// method
                String returnedDate = sma.getDate(l);// method
//add above here ===========================================================

                sma.close();

                sqlRouteName.setText(returnedRoutename);
                sqlLocation.setText(returnedLocation);
                sqlNotes.setText(returnedNotes);
                sqlChrono.setText(returnedChrono);
                sqlDate.setText(returnedDate);
//add above here ===========================================================

            } catch (Exception e) {
                didItWork2 = false;
                String error = e.toString();// the error string will be printed
                                            // to the dialog box to display the
                                            // error code to the user
                Dialog d = new Dialog(this);
                d.setTitle("Error ohh no..."); // sets the diaog box with
                                                // success mesasge
                TextView tv = new TextView(this);
                tv.setText(error);
                d.setContentView(tv);
                d.show();
            } finally {
                if (didItWork2) {
                    // didItWork = true;
                    Dialog d = new Dialog(this);
                    d.setTitle("Loading Data"); // sets the diaog box with
                                                // success mesasge
                    TextView tv = new TextView(this);
                    tv.setText("Status: Success");
                    d.setContentView(tv);
                    d.show();

                }
            }
            break;



        // ===============================================
        // ==================Modify button================
        // ===============================================
        case R.id.bSQL_Modify:
            boolean didItWork4 = true;
            try {
                String sRow = sqlRow.getText().toString();
                String mRoutename = sqlRouteName.getText().toString();
                String mLocation = sqlLocation.getText().toString();
                String mNotes = sqlNotes.getText().toString();
                String mChrono = sqlChrono.getText().toString();
                String mDate = sqlDate.getText().toString();


//add above here ===========================================================            

                long lRow = Long.parseLong(sRow);

                SQL_management_activity ex = new SQL_management_activity(this);
                ex.open();
                ex.updateEntry(lRow, mRoutename, mLocation, mNotes, mChrono, mDate); // these are the
                                                                // fields that
                                                                // are being
                                                                // updated
//add above here ===========================================================    

                ex.close();
            } catch (Exception e) {
                didItWork4 = false;
                String error = e.toString();// the error string will be printed
                                            // to the dialog box to display the
                                            // error code to the user
                Dialog d = new Dialog(this);
                d.setTitle("Error ohh no..."); // sets the diaog box with
                                                // success mesasge
                TextView tv = new TextView(this);
                tv.setText(error);
                d.setContentView(tv);
                d.show();
            } finally {
                if (didItWork4) {
                    // didItWork = true;
                    Dialog d = new Dialog(this);
                    d.setTitle("Modifying Record"); // sets the diaog box with
                                                    // success mesasge
                    TextView tv = new TextView(this);
                    tv.setText("Status: Success");
                    d.setContentView(tv);
                    d.show();

                    Thread timer = new Thread() { // this is the same timer as//
                                                    // on the spalshcren
                        public void run() { // it automaticaly moves to the//
                                            // review page after 500 miliseconds
                            try {
                                sleep(1200); // duration the splash screen is//
                                                // displayed for
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } finally {
                                Intent openMain_menu = new Intent(
                                        "com.hew235.mapapp.REVIEW_SCREEN_ACTIVITY");
                                startActivity(openMain_menu);
                            }

                        }
                    };
                    timer.start();

                }
            }
            break;

        // ===============================================
        // ==================Delete button================
        // ===============================================
        case R.id.bSQL_Delete:
            boolean didItWork3 = true;
            try {
                String sRow1 = sqlRow.getText().toString();
                long lRow1 = Long.parseLong(sRow1);
                SQL_management_activity ex1 = new SQL_management_activity(this);
                ex1.open();
                ex1.deleteEntry(lRow1);
                ex1.close();

            } catch (Exception e) {
                didItWork3 = false;
                String error = e.toString();// the error string will be printed
                                            // to the dialog box to display the
                                            // error code to the user
                Dialog d = new Dialog(this);
                d.setTitle("Error ohh no..."); // sets the diaog box with
                                                // success mesasge
                TextView tv = new TextView(this);
                tv.setText(error);
                d.setContentView(tv);
                d.show();
            } finally {
                if (didItWork3) {
                    // didItWork = true;
                    Dialog d = new Dialog(this);
                    d.setTitle("Deleting Record"); // sets the diaog box with
                                                    // success mesasge
                    TextView tv = new TextView(this);
                    tv.setText("Status: Success");
                    d.setContentView(tv);
                    d.show();

                    Thread timer = new Thread() { // this is the same timer as
                                                    // on the spalshcren
                        public void run() { // it automaticaly moves to the
                                            // review page after 500 miliseconds
                            try {
                                sleep(1200); // duration the splash screen is
                                                // displayed for
                            } catch (InterruptedException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } finally {
                                Intent openMain_menu = new Intent(
                                        "com.hew235.mapapp.REVIEW_SCREEN_ACTIVITY");
                                startActivity(openMain_menu);
                            }

                        }
                    };
                    timer.start();

                }
            }
            break;

        }
    }

    private static MapController getController() {
        // TODO Auto-generated method stub

        return null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.map1_screen_activity, menu);
        GoogleMap map;

        return true;
    }


















    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

        Context context = getApplicationContext();
        CharSequence text = "Hello toast! r u hungry";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();


        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();

        Location location1 = locationManager
                .getLastKnownLocation(locationManager.getBestProvider(criteria,
                        false));
        if (location1 != null) {
            googlemap
                    .animateCamera(CameraUpdateFactory.newLatLngZoom(
                            new LatLng(location1.getLatitude(), location1
                                    .getLongitude()), 13));

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(new LatLng(location1.getLatitude(), location1
                            .getLongitude())) // Sets the center of the map to
                                                // location user
                    .zoom(17) // Sets the zoom
                    .bearing(0) // Sets the orientation of the camera to east
                    .tilt(0) // Sets the tilt of the camera to 30 degrees
                    .build(); // Creates a CameraPosition from the builder
            googlemap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));
            location1 = currentLocation;

        }



         currentLocation = myLocation2;


                        Polyline line = googlemap.addPolyline(new PolylineOptions()
                        .add(new LatLng (myLocation2.getLatitude(), myLocation2
                                .getLongitude()), 
                                new LatLng (currentLocation.getLatitude(), currentLocation
                                        .getLongitude()))
                        .width(5)
                                .color(Color.RED)); 

                        currentLocation = myLocation2; //sets the location variables ready for the lines to join the dots

    }

    @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
        Context context = getApplicationContext();
        CharSequence text = "status changed";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }

}

我还没有读过你所有的代码,但这一部分,你应该在那里打印你的行,让我困惑:

     currentLocation = myLocation2;

     Polyline line = googlemap.addPolyline(new PolylineOptions()
         .add(new LatLng (myLocation2.getLatitude(), myLocation2.getLongitude()), new LatLng (currentLocation.getLatitude(), currentLocation.getLongitude())).width(5)
         .color(Color.RED)); 
     currentLocation = myLocation2; //sets the location variables ready for the lines to join the dots

为什么要从X到X绘制多段线?这可能会导致一个空行,因此根本没有行。试着从X到Y划一条线。

请只包括相关代码,而不是整个班级。请看一下如何接收位置更新。谢谢,我查看了LucationUpdates文档,发现了一个示例应用程序,它具有我需要的更新功能