2016-09-30 18 views
0

私は、ユーザーが「開始」ボタンを押すと、10秒ごとにユーザーの現在の位置を取得するタイマーが開始され、プレビオからポリラインを描画するGoogleマップを持っていますユーザーが「追跡を停止する」ボタンを押すまで現在の位置に移動します。 今、私はポリラインを除いてすべての細かい作業を行っていますが、ポリラインをタイマーで作っているわけではありません。そして、もし私が '開始'ボタンを押した場合は(ポリオラインを現在の位置に追加します。私のアプリケーションはポリラインを追加し続けますが、開始ボタンを押し続けますが、このようにしたくありません。私はそれがボタンを押すことでタイマーではなく、タイマーを押すようにしたい。AndroidのGoogleマップのタイマーを使ってポリラインを追加する

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     LocationListener { 

    private GoogleMap mMap; 
    Button start,stop,track_record; 
    GPSTracker gps; 
    ArrayList<String> cordsList= new ArrayList<String>(); 
    ArrayList<LatLng> MarkerPoints; 
    ArrayList<Double> arrLat= new ArrayList<Double>(); 
    ArrayList<Double> arrLng = new ArrayList<Double>(); 
    GoogleApiClient mGoogleApiClient; 
    Location mLastLocation; 
    Marker mCurrLocationMarker; 
    LocationRequest mLocationRequest; 
    private final int TIME_INTERVAL = 10000; 
    Timer timer=new Timer(); 
    double longitude,latitude; 
    private static LatLng prev = new LatLng(0,0); 
    int Flag = 0; 
    static int begin = 0; 
    private LatLng fixedBegin ; 
    private LatLng listPoints = new LatLng(0,0); 
    ArrayList<LatLng> listP= new ArrayList<LatLng>(); 

    Handler m_handler; 
    Runnable m_handlerTask ; 
    int t=0; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_maps); 

     stop = (Button) findViewById(R.id.btn_stop); 
     track_record = (Button) findViewById(R.id.btn_TR); 




     // track record activity 
     track_record.setOnClickListener(new View.OnClickListener() { 
              @Override 
              public void onClick(View v) { 
               Toast.makeText(getApplication(), "Your Tracking is started now", Toast.LENGTH_SHORT).show(); 



               ///////*************************************//////// 
               // create class object 
               gps = new GPSTracker(MapsActivity.this); 
               timer.scheduleAtFixedRate(new TimerTask() { 

                @SuppressLint("DefaultLocale") 
                @TargetApi(Build.VERSION_CODES.GINGERBREAD) 
                @Override 

                public void run() { 
                 runOnUiThread(new Runnable() { 
                  @Override 
                  public void run() { 

                   LatLng current = new LatLng(latitude = gps.getLatitude(),longitude = gps.getLongitude()); 

                   if (begin == 0) { 
                   fixedBegin = current; 

                    // create marker 
                    MarkerOptions marker = new MarkerOptions().position(fixedBegin).title("Begin "); 

                    // Changing the color babyyy 
                    marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)); 
                    // adding marker 
                   mMap.addMarker(marker); 

                                      // drawing polyline here 


                   if(Flag==0) //when the first update comes, we have no previous points,hence this 
                    { 
                     prev=current; 
                     Flag=1; 
                    } 
                    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(current, 16); 
                    mMap.animateCamera(update); 
                    mMap.addPolyline((new PolylineOptions()) 
                      .add(prev, current).width(6).color(Color.BLUE) 
                      .visible(true)); 
                    prev=current; 
                    current = null; 



                   } 
                   begin++; 

                   Log.i("OK", "lat------ " + latitude); 
                   Log.i("OK", "lng-------- " + longitude); 

                   arrLat.add(latitude); 
                   arrLng.add(longitude); 



                   //////////// TRYING /////////// 
                   // And it Worked :D 

/* 
                   if(Flag==0) //when the first update comes, we have no previous points,hence this 
                   { 
                    prev=current; 
                    Flag=1; 
                   } 
                   CameraUpdate update = CameraUpdateFactory.newLatLngZoom(current, 16); 
                   mMap.animateCamera(update); 
                   mMap.addPolyline((new PolylineOptions()) 
                     .add(prev, current).width(6).color(Color.BLUE) 
                     .visible(true)); 
                   prev=current; 
                   current = null; 
*/ 


                  } 
                 }); 


                } 
               }, 0, TIME_INTERVAL); 


               // check if GPS enabled 
               if (gps.canGetLocation()) { 
                Log.i("ok", "Mai to hogaya true"); 
                latitude = gps.getLatitude(); 
                longitude = gps.getLongitude(); 
                String longlat = String.valueOf(latitude) + ":" + String.valueOf(longitude); 
                cordsList.add(longlat); 
                // \n is for new line 
                Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
               } else { 
                Toast.makeText(getApplicationContext(), "Sorry cant get location", Toast.LENGTH_LONG).show(); 
                // can't get location 
                // GPS or Network is not enabled 
                // Ask user to enable GPS/network in settings 
                // gps.showSettingsAlert(); 
               } 

               Log.i("Finall", "Location-> " + cordsList.toString()); 

              } 
             } 
     ); 

     if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      checkLocationPermission(); 
     } 
     // Initializing 
     MarkerPoints = new ArrayList<>(); 

     // Obtain the SupportMapFragment and get notified when the map is ready to be used. 
     SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager() 
       .findFragmentById(R.id.map); 
     mapFragment.getMapAsync(this); 

     // Toast on stop 
     stop.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Toast.makeText(getApplication(), "Your Tracking is over now, yellow marker shows your destination", Toast.LENGTH_SHORT).show(); 
       ///////// 
       //yaha kaam karna hai abhi 
       // create marker 
       MarkerOptions marker = new MarkerOptions().position(new LatLng(gps.getLatitude(), gps.getLongitude())).title("REACHED :D "); 

       // Changing the color babyyy 
       marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)); 
       // adding marker 
       mMap.addMarker(marker); 

       Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 



       timer.cancel(); 
      } 

     }); 
    } 
    /** 
    * Manipulates the map once available. 
    * This callback is triggered when the map is ready to be used. 
    * This is where we can add markers or lines, add listeners or move the camera. In this case, 
    * we just add a marker near Sydney, Australia. 
    * If Google Play services is not installed on the device, the user will be prompted to install 
    * it inside the SupportMapFragment. This method will only be triggered once the user has 
    * installed Google Play services and returned to the app. 
    */ 
    @Override 
    public void onMapReady(GoogleMap googleMap) { 
     mMap = googleMap; 

     //Initialize Google Play Services 
     if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
      if (ContextCompat.checkSelfPermission(this, 
        Manifest.permission.ACCESS_FINE_LOCATION) 
        == PackageManager.PERMISSION_GRANTED) { 
       buildGoogleApiClient(); 
       mMap.setMyLocationEnabled(true); 
      } 
     } 
     else { 
      buildGoogleApiClient(); 
      mMap.setMyLocationEnabled(true); 
     } 

     // Setting onclick event listener for the map 
     mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() { 

             @Override 
             public void onMapClick(LatLng point) { 

              // Already two locations 
              if (MarkerPoints.size() >= 1) { 
               MarkerPoints.clear(); 
               mMap.clear(); 
              } 

              // Adding new item to the ArrayList 
              MarkerPoints.add(point); 

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

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


              if (MarkerPoints.size() == 1) { 
               options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); 
              } 
              // Below ELSE is not used any more due to the fetched location of user TADAAAA xD 
              else if (MarkerPoints.size() == 2) { 
               options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)); 
              } 


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


              // Checks, whether start and end locations are captured 
              if (MarkerPoints.size() >= 1) { 
               //>>>> LatLng origin = MarkerPoints.get(0); 
               LatLng latLng1 = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude()); 
               LatLng origin = latLng1; 
               LatLng dest = MarkerPoints.get(0); 

               // Getting URL to the Google Directions API 
               String url = getUrl(origin, dest); 
               Log.d("onMapClick", url.toString()); 
               FetchUrl FetchUrl = new FetchUrl(); 

               // Start downloading json data from Google Directions API 
               FetchUrl.execute(url); 
               //move map camera 
               mMap.moveCamera(CameraUpdateFactory.newLatLng(origin)); 
               mMap.animateCamera(CameraUpdateFactory.zoomTo(11)); 
              } 

             } 
            } 
     ); 


    } 

    private String getUrl(LatLng origin, LatLng dest) { 

     // Origin of route 
     String str_origin = "origin=" + origin.latitude + "," + origin.longitude; 

     // Destination of route 
     String str_dest = "destination=" + dest.latitude + "," + dest.longitude; 


     // Sensor enabled 
     String sensor = "sensor=false"; 

     // Building the parameters to the web service 
     String parameters = str_origin + "&" + str_dest + "&" + sensor; 

     // Output format 
     String output = "json"; 

     // Building the url to the web service 
     String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + parameters; 


     return url; 
    } 

    /** 
    * A method to download json data from url 
    */ 
    private String downloadUrl(String strUrl) throws IOException { 
     String data = ""; 
     InputStream iStream = null; 
     HttpURLConnection urlConnection = null; 
     try { 
      URL url = new URL(strUrl); 

      // Creating an http connection to communicate with url 
      urlConnection = (HttpURLConnection) url.openConnection(); 

      // Connecting to url 
      urlConnection.connect(); 

      // Reading data from url 
      iStream = urlConnection.getInputStream(); 

      BufferedReader br = new BufferedReader(new InputStreamReader(iStream)); 

      StringBuffer sb = new StringBuffer(); 

      String line = ""; 
      while ((line = br.readLine()) != null) { 
       sb.append(line); 
      } 

      data = sb.toString(); 
      Log.d("downloadUrl", data.toString()); 
      br.close(); 

     } catch (Exception e) { 
      Log.d("Exception", e.toString()); 
     } finally { 
      iStream.close(); 
      urlConnection.disconnect(); 
     } 
     return data; 
    } 


    // Fetches data from url passed 
    private class FetchUrl extends AsyncTask<String, Void, String> { 

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

      // For storing data from web service 
      String data = ""; 

      try { 
       // Fetching the data from web service 
       data = downloadUrl(url[0]); 
       Log.d("Background Task data", data.toString()); 
      } catch (Exception e) { 
       Log.d("Background Task", e.toString()); 
      } 
      return data; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 

      ParserTask parserTask = new ParserTask(); 

      // Invokes the thread for parsing the JSON data 
      parserTask.execute(result); 

     } 
    } 

答えて

0

以下の2つの機能を確認してください。

public void Draw_Map(List<LatLng> val) { 
     if(val.size() > 1) { 
      mGoogleMap.addPolyline(new PolylineOptions() 
        .add(val.get(mSource), val.get(mDestination)) 
        .width(8) 
        .color(Color.BLACK)); 
      mSource++; 
      mDestination++; 
     } 
} 

private void drawFinalPolygon() { 
     mLatLngList.add(mLatLngList.get(0)); 
     PolygonOptions polygonOptions = new PolygonOptions(); 
     polygonOptions.addAll(mLatLngList); 
     polygonOptions.strokeColor(Color.BLACK); 
     polygonOptions.strokeWidth(8); 
     polygonOptions.fillColor(Color.TRANSPARENT); 
     Polygon polygon = mGoogleMap.addPolygon(polygonOptions); 

     mGoogleMap.addMarker(new MarkerOptions() 
         .title("Marker Title here") 
         .snippet("Hello, I am marker snippet!") 
         .position(mLatLngList.get(0))); 
} 

コールDraw_Map()メソッドたび場所の変更、ユーザーが停止の追跡をクリックするとdrawFinalPolygon()メソッドを呼び出します。

+0

あなたは私のコードを通してそれを詳しく説明できますか? –

+0

位置を取得しているm_handlerTaskハンドラ内にDraw_Map()関数を実装します。その後、追跡を停止するたびに最終ポリゴンを描画します。 –

+0

ねえ、私は私のコードを編集して再チェックしてください、そしてご迷惑をおかけして申し訳ありません。実際に私はハンドラのコードにコメントしています。 変更は、フラグ機能のあるタイマー機能にのみあります。 –

関連する問題