2014-03-31 24 views
0

我仍然在与android握手,并试图制作一个应用程序,该应用程序会在Google地图上绘制我已循环的路径。我已经成功地显示的地图,并且可以使用该代码绘制两个坐标之间的简单折线: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(); 
    } 

} 
+0

请只包括相关代码而不是您的全班 – tyczj

+0

看看[docs](https://developer.android.com/training/location/receive-location-updates.html)如何接收位置更新。 –

+0

谢谢,我看了一下LucationUpdates文档,发现了一个示例应用程序,它具有我需要的更新功能 – user3480901

回答

1

我没有看到所有的代码,但是这部分,在那里你理应打印线,让我困惑:

 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的线条代替。