2016-09-19 188 views
0

我正在開發一個應用程序,在這我使用谷歌地圖來顯示用戶當前的位置。問題是,當我第一次打開應用程序顯示藍色地圖屏幕,現在我再次打開地圖第二次然後在這個時候地圖顯示正確的結果與當前位置。這發生在targetsdkversion> 23和targetsdkversion < 23兩個版本。只有dosenot第一次顯示正確的地圖。以下是我使用的代碼。以及我如何驗證地圖是否顯示地圖正確位置與否?如何在Android中查找當前位置的谷歌地圖?

//java 

public class Start_Activity1 extends FragmentActivity implements 
     OnMapReadyCallback, 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener, 
     GoogleMap.OnMarkerDragListener, 
     GoogleMap.OnMapLongClickListener, 
     View.OnClickListener { 

    //Our Map 
    private GoogleMap mMap; 
    public static final int REQUEST_ID_ACCESS_COURSE_FINE_LOCATION = 100; 

    //To store longitude and latitude from map 
    private double longitude; 
    private double latitude; 
    String caddress; 
    EditText eddate; 
    EditText edtime; 
    EditText seats1 ; 
    public static TextView tvtime,tvdate; 
    Button btime,bdate; 

    //Buttons 
    private ImageButton buttonSave; 
    private ImageButton buttonCurrent; 
    private ImageButton buttonView; 

    private Button btnProceed, btnskip, btnClocation; 

    String strAdd, start_point, start_time, no_seats, mob_no, stime, seats; 
    TextView tvmap,textview; 
    int mYear, mMonth, mDay, mHour, mMinute; 

    private boolean loggedIn = false; 
    public static String email; 

    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 100; 

    private ProgressDialog myProgress; 

    //Google ApiClient 
    private GoogleApiClient googleApiClient; 
    SupportMapFragment mapFragment; 


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

     tvmap=(TextView)findViewById(R.id.tv_map); 
     textview=(TextView)findViewById(R.id.textView_euser); 

     tvdate=(TextView)findViewById(R.id.textView_sdate); 
     // tvtime=(TextView)findViewById(R.id.textView_stime); 
     seats1=(EditText)findViewById(R.id.editText_nseats); 

     //date and time 
     // datetime(); 
     Calendar cal = Calendar.getInstance(TimeZone.getDefault()); 
     SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss a", Locale.getDefault()); 
     tvdate.setText(cal.getTime().toLocaleString()); 
     // tvtime.setText(sdf.format(cal.getTime())); 


     //progress bar 
     myProgress = new ProgressDialog(this); 
     myProgress.setTitle("Map Loading ..."); 
     myProgress.setMessage("Please wait..."); 
     myProgress.setCancelable(true); 
     // Display Progress Bar. 
     myProgress.show(); 

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

     //Initializing googleapi client 
     googleApiClient = new GoogleApiClient.Builder(this) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .addApi(LocationServices.API) 
       .build(); 

     //Initializing views and adding onclick listeners 
     btnProceed=(Button)findViewById(R.id.button_sproceed); 
     // btnskip=(Button)findViewById(R.id.button_skip); 
     // btnClocation=(Button)findViewById(R.id.button_clocation); 

     btnProceed.setOnClickListener(this); 
     // btnClocation.setOnClickListener(this); 
    } 

    @Override 
    protected void onResume() { 

     LocationManager mlocManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); 
     boolean enabled = mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

     if(!enabled) { 
      showDialogGPS(); 
     } 

     super.onResume(); 
    } 

    private void showDialogGPS() { 
     AlertDialog.Builder builder = new AlertDialog.Builder(this); 
     builder.setCancelable(false); 
     builder.setTitle("Enable GPS"); 
     builder.setMessage("Please enable GPS"); 
     builder.setInverseBackgroundForced(true); 
     builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       startActivity(
         new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS)); 
       getCurrentLocation(); 
       moveMap(); 
      } 
     }); 
     builder.setNegativeButton("Ignore", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.dismiss(); 
      } 
     }); 
     AlertDialog alert = builder.create(); 
     alert.show(); 
    } 


    @Override 
    public void onClick(View v) { 
     if(v == btnProceed){ 

      SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE); 
      loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false); 
      mob_no = sharedPreferences.getString(Config.PHONE_SHARED_PREF, "Not Available"); 
      textview.setText(String.valueOf(mob_no)); 

      // getCurrentLocation(); 
      // moveMap(); 
      if (loggedIn) { 
       //We will start the Profile Activity 
       submitForm(); 
       hsubmitForm(); 
       Intent i=new Intent(Start_Activity1.this,Index_Activity.class); 
       startActivity(i); 
       // smsForm(); 
       // Toast.makeText(Start_Activity.this, "You Submitted Details Successfully", Toast.LENGTH_LONG).show(); 
      } 

     } 
    } 

    //saving to database 
    private void submitForm() { 

     start_point = tvmap.getText().toString(); 
     start_time = tvdate.getText().toString(); 
     no_seats = seats1.getText().toString(); 
     mob_no = textview.getText().toString(); 
     // Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show(); 
     new StartAsync(this).execute(start_point, start_time, no_seats, mob_no); 
    } 

    //saving to database 
    private void hsubmitForm() { 

     start_point = tvmap.getText().toString(); 
     stime = tvdate.getText().toString(); 
     seats = seats1.getText().toString(); 
     mob_no = textview.getText().toString(); 
     // Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show(); 
     new SHistoryAsync(this).execute(mob_no, start_point, seats, stime); 
    } 

    private void smsForm() { 

     mob_no = textview.getText().toString(); 
     // Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show(); 
     new SmsAsync(this).execute(mob_no); 
    } 

    @Override 
    protected void onStart() { 
     googleApiClient.connect(); 
     super.onStart(); 
    } 

    @Override 
    protected void onStop() { 
     googleApiClient.disconnect(); 
     super.onStop(); 
    } 

    //Getting current location 
    private void getCurrentLocation() { 
     mMap.clear(); 
     //Creating a location object 

     if(getApplicationInfo().targetSdkVersion>=23) { 
      if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       //  if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
       // here to request the missing permissions, and then overriding 
       // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
       //           int[] grantResults) 
       // to handle the case where the user grants the permission. See the documentation 
       // for ActivityCompat#requestPermissions for more details.// 

       ActivityCompat.requestPermissions(this, 
         new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 
         MY_PERMISSIONS_REQUEST_LOCATION); 
       return; 
      } 
     } 
     else if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 

      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
      return; 
     } 
     Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient); 

     if (location != null) { 
      //Getting longitude and latitude 
      longitude = location.getLongitude(); 
      latitude = location.getLatitude(); 

      // tvmap.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude()); 

      // strAdd = getCompleteAddressString(latitude, longitude); 
      // tvmap.setText("Current Address : " + strAdd); 
      getCompleteAddressString(latitude, longitude); 
      //moving the map to location 
      moveMap(); 
     } 

    } 

    //Function to move the map 
    private void moveMap() { 
     //String to display current latitude and longitude 
     String msg = latitude + ", "+longitude; 

     //Creating a LatLng Object to store Coordinates 
     LatLng latLng = new LatLng(latitude, longitude); 

     //Adding marker to map 
     mMap.addMarker(new MarkerOptions() 
       .position(latLng) //setting position 
       .draggable(true) //Making the marker draggable 
       .title("Current Location")); //Adding a title 

     //Moving the camera 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 

     //Animating the camera 
     mMap.animateCamera(CameraUpdateFactory.zoomTo(15)); 

    } 

    @Override 
    public void onMapReady(GoogleMap googleMap) { 

     mMap = googleMap; 
     LatLng latLng = new LatLng(-34, 151); 
     mMap.addMarker(new MarkerOptions().position(latLng).draggable(true)); 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 
     mMap.setOnMarkerDragListener(this); 
     mMap.setOnMapLongClickListener(this); 

    } 

    @Override 
    public void onConnected(Bundle bundle) { 
     getCurrentLocation(); 
     myProgress.dismiss(); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 

    } 

    @Override 
    public void onMapLongClick(LatLng latLng) { 
     //Clearing all the markers 
     mMap.clear(); 

     //Adding a new marker to the current pressed position 
     mMap.addMarker(new MarkerOptions() 
       .position(latLng) 
       .draggable(true)); 
    } 

    @Override 
    public void onMarkerDragStart(Marker marker) { 

    } 

    @Override 
    public void onMarkerDrag(Marker marker) { 

    } 

    @Override 
    public void onMarkerDragEnd(Marker marker) { 
     //Getting the coordinates 
     latitude = marker.getPosition().latitude; 
     longitude = marker.getPosition().longitude; 

     //Moving the map 
     moveMap(); 
    } 

    @SuppressLint("LongLogTag") 
    private String getCompleteAddressString(double LATITUDE, double LONGITUDE) { 
     String strAdd = ""; 
     Geocoder geocoder = new Geocoder(this, Locale.getDefault()); 
     try { 
      List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1); 
      if (addresses != null) { 
       Address returnedAddress = addresses.get(0); 
       StringBuilder strReturnedAddress = new StringBuilder("Address:"); 

       for (int i = 0; i < returnedAddress.getMaxAddressLineIndex(); i++) { 
        strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n"); 
       } 
       strAdd = strReturnedAddress.toString(); 
       tvmap.setText(strAdd); 
       Log.w("My Current loction address", "" + strReturnedAddress.toString()); 
      } else { 
       Log.w("My Current loction address", "No Address returned!"); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
      Log.w("My Current loction address", "Canont get Address!"); 
     } 
     return strAdd; 
    } 

    @Override 
    public void onRequestPermissionsResult(int requestCode, 
              String permissions[], int[] grantResults) { 
     switch (requestCode) { 
      case MY_PERMISSIONS_REQUEST_LOCATION: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        // permission was granted, yay! Do the 

        // contacts-related task you need to do. 
        // getCurrentLocation(); 
        // moveMap(); 
       } else { 
        // permission denied, boo! Disable the 
        // functionality that depends on this permission. 
        Toast.makeText(Start_Activity1.this, "Permission denied", Toast.LENGTH_SHORT).show(); 
       } 
       return; 
      } 
      // other 'case' lines to check for other 
      // permissions this app might request 
     } 
    } 

} 
+0

mmm ...我認爲「藍色地圖」是地圖中的水,也許它報告的是不好的位置,或者它可能需要很長時間來顯示位置,請嘗試更改當前位置的方法,或嘗試「硬編碼」的經緯度,並打開第一次,以證明是否你的位置或其他問題的方法 – Aspicas

回答

2

'藍屏'是大西洋。這是因爲第一次當前位置是0,0。出於這個原因,你應該在開始地圖之前得到當前位置。

+0

我這樣做? – rohiH

+0

你可以使用locationAcitivity並從locationActivity啓動mapActivity – padeg

+0

請參考我的代碼 – rohiH

相關問題