2016-09-30 2 views
0

사용자가 '시작'버튼을 누르면 10 초마다 사용자의 현재 위치를 계속 유지하는 타이머가 시작되고 previos에서 폴리 라인을 그릴 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

아래의 두 가지 기능을 확인하십시오.

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

이봐, 내 코드를 편집 해 주시고, 불편을 끼쳐 드려 죄송합니다. 실제로 처리기 코드에 주석을 달았으며 다른 것을 시도했지만 잘못된 코드를 게시했습니다. 변경 사항은 플래그 기능을 가진 타이머 기능에서만 볼 수 있습니다! –