List of usage examples for android.location LocationManager getBestProvider
public String getBestProvider(Criteria criteria, boolean enabledOnly)
From source file:com.projectattitude.projectattitude.Activities.MapActivity.java
/** * Handles everything/* w w w .j a va 2 s . c om*/ * @param map */ @Override public void onMapReady(GoogleMap map) { mMap = map; LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); if (ContextCompat.checkSelfPermission(MapActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(MapActivity.this, new String[] { android.Manifest.permission.ACCESS_FINE_LOCATION }, MY_PERMISSION_ACCESS_COARSE_LOCATION); } /** * http://stackoverflow.com/questions/18425141/android-google-maps-api-v2-zoom-to-current-location 4/1/2017 4:20pm */ Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false)); if (location != null) { map.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(15) // Sets the zoom .bearing(0) // Sets the orientation of the camera to east .tilt(40) // Sets the tilt of the camera to 30 degrees .build(); // Creates a CameraPosition from the builder map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } enableMyLocation(); //couldn't get ColorMap to work, so made one for the meantime HashMap<String, BitmapDescriptor> hm = new HashMap<String, BitmapDescriptor>(); hm.put("Anger", BitmapDescriptorFactory.fromResource(R.drawable.ic_anger_colour_36px));//defaultMarker(356)); hm.put("Confusion", BitmapDescriptorFactory.fromResource(R.drawable.ic_confusion_colour_36px));//defaultMarker(19)); hm.put("Disgust", BitmapDescriptorFactory.fromResource(R.drawable.ic_disgust_colour_36px));//defaultMarker(65)); hm.put("Fear", BitmapDescriptorFactory.fromResource(R.drawable.ic_fear_colour_36px));//defaultMarker(42)); hm.put("Happiness", BitmapDescriptorFactory.fromResource(R.drawable.ic_happiness_colour_36px));//defaultMarker(160)); hm.put("Sadness", BitmapDescriptorFactory.fromResource(R.drawable.ic_sadness_colour_36px));//defaultMarker(60)); hm.put("Shame", BitmapDescriptorFactory.fromResource(R.drawable.ic_shame_colour_36px));//defaultMarker(200)); hm.put("Surprise", BitmapDescriptorFactory.fromResource(R.drawable.ic_surprise_colour_36px));//defaultMarker(22)); //Taken from https://developers.google.com/maps/documentation/android-api/marker //On March 21st at 17:53 map.setOnInfoWindowClickListener(this); if (getIntent().hasExtra("users")) { ArrayList<User> users = (ArrayList<User>) getIntent().getSerializableExtra("users"); GPSTracker gps = new GPSTracker(MapActivity.this); //LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); //LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) { latitude = Math.round(gps.getLatitude() * 10000d) / 10000d; longitude = Math.round(gps.getLongitude() * 10000d) / 10000d; if (latitude != 0 & longitude != 0) { Toast.makeText(MapActivity.this, "Found your location", Toast.LENGTH_LONG).show(); Log.d("Distance", "Current Location: " + latitude + " " + longitude); for (int i = 0; i < users.size(); i++) { Mood mood = users.get(i).getFirstMood(); // if(mood.getLatitude()!= null && mood.getLongitude() != null) { if (mood != null) { Double returned = calculateDistance(latitude, longitude, mood.getLatitude(), mood.getLongitude()); returned = returned / 1000; Log.d("Distance", "Current Distance: " + returned); Log.d("Distance", "Current comparison to: " + users.get(i).getUserName() + " " + mood.getEmotionState()); if (returned < 5) { map.addMarker(new MarkerOptions() .position(new LatLng(mood.getLatitude(), mood.getLongitude())) .title(mood.getMaker()).snippet(mood.getEmotionState()) .icon(hm.get(mood.getEmotionState()))).setTag(mood); } } } } else { Toast.makeText(MapActivity.this, "Could not find your location, please try again!", Toast.LENGTH_LONG).show(); } } else { Toast.makeText(MapActivity.this, "Please turn on GPS for locations!", Toast.LENGTH_LONG).show(); } } else if (getIntent().hasExtra("user")) { ArrayList<Mood> userMoodList = (ArrayList<Mood>) getIntent().getSerializableExtra("user"); for (int i = 0; i < userMoodList.size(); i++) { //TODO this will get EVERY mood from the user, which could be too many Mood mood = userMoodList.get(i); if (mood.getLongitude() == 0 && mood.getLatitude() == 0) { Log.d("MapMoods", "Mood: " + mood.getEmotionState() + "not mapped"); } else { map.addMarker(new MarkerOptions().position(new LatLng(mood.getLatitude(), mood.getLongitude())) .title(mood.getMaker()).snippet(mood.getEmotionState()) .icon(hm.get(mood.getEmotionState()))).setTag(mood); } } } else { Toast.makeText(MapActivity.this, "MIts Fucked, nothing go passed", Toast.LENGTH_LONG).show(); } }
From source file:com.example.angel.parkpanda.MainActivity.java
private Location MMgetMyLocation() { LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE); Criteria criteria = new Criteria(); String provider = service.getBestProvider(criteria, false); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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. }/*from ww w . j a va 2s .c o m*/ Location location = service.getLastKnownLocation(provider); return location; }
From source file:net.imatruck.betterweather.BetterWeatherExtension.java
/** * Starts the update process, will verify the reason before continuing * * @param reason Update reason, provided by DashClock or this app *///from w w w . j a va 2s. c om @Override protected void onUpdateData(int reason) { LOGD(TAG, "Update reason: " + getReasonText(reason)); // Whenever updating, set sLang to Yahoo's format(en-US, not en_US) // If sLang is set in elsewhere, and user changes phone's locale // without entering BW setting menu, then Yahoo's place name in widget // may be in wrong locale. Locale current = getResources().getConfiguration().locale; YahooPlacesAPIClient.sLang = current.getLanguage() + "-" + current.getCountry(); if (reason != UPDATE_REASON_USER_REQUESTED && reason != UPDATE_REASON_SETTINGS_CHANGED && reason != UPDATE_REASON_INITIAL && reason != UPDATE_REASON_INTERVAL_TOO_BIG) { LOGD(TAG, "Skipping update"); if ((System.currentTimeMillis() - lastUpdateTime > (sRefreshInterval * 1000 * 60)) && sRefreshInterval > 0) onUpdateData(UPDATE_REASON_INTERVAL_TOO_BIG); return; } LOGD(TAG, "Updating data"); if (sPebbleEnable) { LOGD(TAG, "Registered Pebble Data Receiver"); Pebble.registerPebbleDataReceived(getApplicationContext()); } getCurrentPreferences(); NetworkInfo ni = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)) .getActiveNetworkInfo(); if (ni == null || !ni.isConnected()) { LOGD(TAG, "No internet connection detected, scheduling refresh in 5 minutes"); scheduleRefresh(5); return; } LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); String provider; if (sUseOnlyNetworkLocation) provider = LocationManager.NETWORK_PROVIDER; else provider = lm.getBestProvider(sLocationCriteria, true); if (TextUtils.isEmpty(provider)) { LOGE(TAG, "No available location providers matching criteria, maybe permission is disabled."); provider = null; } requestLocationUpdate(lm, provider); }
From source file:org.mozilla.gecko.GeckoAppShell.java
public static void enableLocation(final boolean enable) { getMainHandler().post(new Runnable() { public void run() { LayerView v = GeckoApp.mAppContext.getLayerController().getView(); LocationManager lm = (LocationManager) GeckoApp.mAppContext .getSystemService(Context.LOCATION_SERVICE); if (enable) { Criteria criteria = new Criteria(); String provider = lm.getBestProvider(criteria, true); if (provider == null) return; Looper l = Looper.getMainLooper(); Location loc = lm.getLastKnownLocation(provider); if (loc != null) { GeckoApp.mAppContext.onLocationChanged(loc); }/* w ww . ja v a 2s . com*/ lm.requestLocationUpdates(provider, 100, (float) .5, GeckoApp.mAppContext, l); } else { lm.removeUpdates(GeckoApp.mAppContext); } } }); }
From source file:com.swetha.easypark.GetParkingLots.java
@Override protected void onCreate(Bundle savedInstanceState) { if (!isGooglePlayServicesAvailable()) { finish();/*from www . jav a2s .co m*/ } super.onCreate(savedInstanceState); setContentView(R.layout.getparkinglots); SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager() .findFragmentById(R.id.map); googleMap = supportMapFragment.getMap(); googleMap.setMyLocationEnabled(true); LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (gps_enabled) { Criteria criteria = new Criteria(); provider = locationManager.getBestProvider(criteria, true); if (provider != null && !provider.equals("")) { locationManager.requestLocationUpdates(provider, 500, 1, GetParkingLots.this); // Get the location from the given provider location = locationManager.getLastKnownLocation(provider); } } Log.i("GetParkingLots", "Value of network_enabled and location" + network_enabled + location); if (location == null && network_enabled) { location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 1, GetParkingLots.this); } if (location == null && !network_enabled && !gps_enabled) { Toast.makeText(getBaseContext(), "Enable your location services", Toast.LENGTH_LONG).show(); } if (location != null) onLocationChanged(location); else { Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show(); } tv_fromTime = (TextView) findViewById(R.id.tv_fromTime); fromTimeString = Constants.dtf.format(new Date()).toString(); tv_fromTime.setText(fromTimeString); long lval = DateTimeHelpers.convertToLongFromTime(Constants.dtf.format(new Date()).toString()); Log.i("GetParkingLots", "The value of current time:" + Constants.dtf.format(new Date()).toString() + "in long is" + lval); Log.i("GetParkingLots", "The value of current time:" + lval + "in long is" + DateTimeHelpers.convertToTimeFromLong(lval)); tv_toTime = (TextView) findViewById(R.id.tv_ToTime); // Parsing the date toTimeString = Constants.dtf.format(new Date()).toString(); tv_toTime.setText(toTimeString); btnFromTime = (Button) findViewById(R.id.fromButton); btnFromTime.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Create the dialog final Dialog mDateTimeDialog = new Dialog(GetParkingLots.this); // Inflate the root layout final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater() .inflate(R.layout.date_time_dialog, null); // Grab widget instance mDateTimePicker = (DateTimePicker) mDateTimeDialogView.findViewById(R.id.DateTimePicker); mDateTimePicker.setDateChangedListener(GetParkingLots.this); // Update demo TextViews when the "OK" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)) .setOnClickListener(new OnClickListener() { Calendar cal; @SuppressWarnings("deprecation") public void onClick(View v) { mDateTimePicker.clearFocus(); try { cal = new GregorianCalendar(mDateTimePicker.getYear(), Integer.parseInt(mDateTimePicker.getMonth()), mDateTimePicker.getDay(), mDateTimePicker.getHour(), mDateTimePicker.getMinute()); fromTimeString = DateTimeHelpers.dtf.format(cal.getTime()); tv_fromTime.setText(fromTimeString); } catch (Exception e) { final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this) .create(); alertDialog.setMessage("Enter a valid date"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }); alertDialog.show(); } mDateTimeDialog.dismiss(); } }); // Cancel the dialog when the "Cancel" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)) .setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimeDialog.cancel(); } }); // Reset Date and Time pickers when the "Reset" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)) .setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimePicker.reset(); } }); // Setup TimePicker // No title on the dialog window mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // Set the dialog content view mDateTimeDialog.setContentView(mDateTimeDialogView); // Display the dialog mDateTimeDialog.show(); } }); btnToTime = (Button) findViewById(R.id.toButton); btnToTime.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Create the dialog final Dialog mDateTimeDialog = new Dialog(GetParkingLots.this); // Inflate the root layout final RelativeLayout mDateTimeDialogView = (RelativeLayout) getLayoutInflater() .inflate(R.layout.date_time_dialog, null); // Grab widget instance final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView .findViewById(R.id.DateTimePicker); mDateTimePicker.setDateChangedListener(GetParkingLots.this); // Update demo TextViews when the "OK" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.SetDateTime)) .setOnClickListener(new OnClickListener() { Calendar cal; @SuppressWarnings("deprecation") public void onClick(View v) { mDateTimePicker.clearFocus(); Log.i("toButton", "Value of ToString before cal" + toTimeString); try { cal = new GregorianCalendar(mDateTimePicker.getYear(), Integer.parseInt(mDateTimePicker.getMonth()), mDateTimePicker.getDay(), mDateTimePicker.getHour(), mDateTimePicker.getMinute()); toTimeString = DateTimeHelpers.dtf.format(cal.getTime()); Log.i("toButton", "Value of ToString before cal" + toTimeString); tv_toTime.setText(toTimeString); } catch (Exception e) // fixing the bug where the user doesnt enter anything in the textbox { final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this) .create(); alertDialog.setMessage("Enter a valid date"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }); alertDialog.show(); } //dateTimeTo = new DateTime(mDateTimePicker.getYear(), Integer.parseInt(mDateTimePicker.getMonth()) , mDateTimePicker.getDay(), mDateTimePicker.getHour(), mDateTimePicker.getMinute()); ; mDateTimeDialog.dismiss(); } }); ((Button) mDateTimeDialogView.findViewById(R.id.CancelDialog)) .setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimeDialog.cancel(); } }); // Reset Date and Time pickers when the "Reset" button is clicked ((Button) mDateTimeDialogView.findViewById(R.id.ResetDateTime)) .setOnClickListener(new OnClickListener() { public void onClick(View v) { // TODO Auto-generated method stub mDateTimePicker.reset(); } }); // Setup TimePicker // No title on the dialog window mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); // Set the dialog content view mDateTimeDialog.setContentView(mDateTimeDialogView); // Display the dialog mDateTimeDialog.show(); } }); btnGetParkingLots = (Button) findViewById(R.id.getNearByParkingLotsButton); btnGetParkingLots.setOnClickListener(new View.OnClickListener() { @SuppressWarnings("deprecation") public void onClick(View v) { et_search = (EditText) findViewById(R.id.edittextsearch); rg = (RadioGroup) findViewById(R.id.rg); checkedRbId = rg.getCheckedRadioButtonId(); Log.i("LOG_TAG: GetParkingLots", "checked radiobutton id is" + checkedRbId); if (checkedRbId == R.id.rbradius) { isRadiusIndicator = true; radius = et_search.getText().toString(); } else { isRadiusIndicator = false; zipcode = et_search.getText().toString(); } final Intent intent = new Intent(GetParkingLots.this, DisplayVacantParkingLots.class); Log.i(TAG, "Inside getNearByParkingLots"); Log.i(TAG, "Value of fromString" + fromTimeString); long lFromVal = DateTimeHelpers.convertToLongFromTime(fromTimeString); Log.i(TAG, "Value of ToString" + toTimeString); long lToVal = DateTimeHelpers.convertToLongFromTime(toTimeString); if ((lToVal - lFromVal) < Constants.thrityMinInMilliSeconds) { final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create(); alertDialog.setMessage("You have to park the car for at least 30 min"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }); alertDialog.show(); } else { intent.putExtra(LATITUDE, latitude); intent.putExtra(LONGITUDE, longitude); intent.putExtra(FROMTIME, lFromVal); intent.putExtra(TOTIME, lToVal); intent.putExtra(RadiusOrZIPCODE, isRadiusIndicator); if (isRadiusIndicator) try { intent.putExtra(RADIUS, Double.parseDouble(radius)); startActivity(intent); } catch (Exception e) { final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create(); alertDialog.setMessage("Enter valid radius"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }); alertDialog.show(); } else { try { intent.putExtra(ZIPCODE, Long.parseLong(zipcode)); startActivity(intent); } catch (Exception e) { final AlertDialog alertDialog = new AlertDialog.Builder(GetParkingLots.this).create(); alertDialog.setMessage("Enter a valid Zip code"); alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { alertDialog.dismiss(); } }); alertDialog.show(); } } } } }); }
From source file:net.jongrakko.zipsuri.activity.PostUploadActivity.java
@Override public void onCheckedChanged(final CompoundButton buttonView, boolean isChecked) { if (isChecked) { switch (buttonView.getId()) { case R.id.radioButtonAddressGPS: mEditTextAddress.setOnClickListener(null); this.mGoogleMap.setOnMapClickListener(this); this.mGoogleMap.setOnMyLocationButtonClickListener(this); if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { mGoogleMap.setMyLocationEnabled(true); LocationProvider lprovider; LocationManager lm = (LocationManager) getActivity() .getSystemService(getActivity().LOCATION_SERVICE); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this); lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); String provider;// w w w .j ava 2 s . c o m Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); criteria.setPowerRequirement(Criteria.POWER_HIGH); provider = lm.getBestProvider(criteria, true); if (provider == null || provider.equals("passive")) { // ? ? ?? new AlertDialog.Builder(getActivity()).setTitle(" ??") .setNeutralButton("??", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { buttonView.toggle(); startActivityForResult( new Intent( android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0); } }).setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { dialog.dismiss(); } }).show(); } else { // ? ? lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this); Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (l != null) { Log.e("hello??", "okok"); } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { requestPermissions(new String[] { Manifest.permission.ACCESS_FINE_LOCATION }, MY_LOCATION_REQUEST_CODE); } } break; case R.id.radioButtonAddressSelf: this.mGoogleMap.setOnMapClickListener(null); mEditTextAddress.setOnClickListener(this); this.mGoogleMap.setOnMyLocationButtonClickListener(null); mGoogleMap.setMyLocationEnabled(false); mEditTextAddress.setOnClickListener(this); startActivityForResult(new Intent(getContext(), SearchAddressActivity.class), SEARCH_ADDRESS); break; } } }
From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java
private void getBestProvider(LocationManager lm) { Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_COARSE); criteria.setAccuracy(Criteria.ACCURACY_FINE); String bestProvider = lm.getBestProvider(criteria, true); if (bestProvider != null) { lm.requestLocationUpdates(bestProvider, 0, 0, this); location = lm.getLastKnownLocation(bestProvider); for (InputLayout input : locationInputs) { input.setLocation(location); }// w ww . j a v a 2 s.c o m } else { new AlertDialog.Builder(this).setMessage(R.string.need_location).setCancelable(true) .setPositiveButton(R.string.enable_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { launchGpsSettings(); dialog.dismiss(); } }).setNegativeButton(R.string.cancel_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }).create().show(); } }
From source file:com.metinkale.prayerapp.vakit.AddCity.java
@SuppressWarnings("MissingPermission") public void checkLocation() { if (PermissionUtils.get(this).pLocation) { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Location loc = null;//from w w w. j a v a 2 s. co m List<String> providers = lm.getProviders(true); for (String provider : providers) { Location last = lm.getLastKnownLocation(provider); // one hour==1meter in accuracy if ((last != null) && ((loc == null) || ((last.getAccuracy() - (last.getTime() / (1000 * 60 * 60))) < (loc.getAccuracy() - (loc.getTime() / (1000 * 60 * 60)))))) { loc = last; } } if (loc != null) onLocationChanged(loc); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_MEDIUM); criteria.setAltitudeRequired(false); criteria.setBearingRequired(false); criteria.setCostAllowed(false); criteria.setSpeedRequired(false); String provider = lm.getBestProvider(criteria, true); if (provider != null) { lm.requestSingleUpdate(provider, this, null); } } else { PermissionUtils.get(this).needLocation(this); } }
From source file:vn.co.taxinet.mobile.newactivity.MapActivity.java
private void displayLocation() { rider_send_request_information = (RelativeLayout) findViewById(R.id.rider_send_request_information); rider_send_request_information.setVisibility(View.GONE); rider_send_request_first_step = (RelativeLayout) findViewById(R.id.rider_send_request_first_step); rider_send_request_first_step.setVisibility(View.GONE); no_driver_nearby = (RelativeLayout) findViewById(R.id.no_driver_nearby); no_driver_nearby.setVisibility(View.GONE); rider_send_request_waiting_step = (RelativeLayout) findViewById(R.id.rider_send_request_waiting_step); rider_send_request_waiting_step.setVisibility(View.GONE); rider_send_request_driver_accept = (RelativeLayout) findViewById(R.id.rider_send_request_driver_accept); rider_send_request_driver_accept.setVisibility(View.GONE); pick_point = (RelativeLayout) findViewById(R.id.pick_point); pick_point.setVisibility(View.GONE); pick_start_point = (Button) findViewById(R.id.btn_pick_start_point); pick_end_point = (Button) findViewById(R.id.btn_pick_end_point); pick_start_point_value = (Button) findViewById(R.id.btn_pick_start_point_value); pick_end_point_value = (Button) findViewById(R.id.btn_pick_end_point_value); pick_start_point_value.setVisibility(View.GONE); pick_end_point_value.setVisibility(View.GONE); Button cancelWaitingRequest, cancelAcceptedRequest; cancelWaitingRequest = (Button) findViewById(R.id.btn_rider_cancel_waiting_request); cancelAcceptedRequest = (Button) findViewById(R.id.btn_rider_cancel_driver_accept_request); // Trip trip = databaseHandler.getTripStatus(); tripBO = new TripBO(); LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); Criteria criteria = new Criteria(); lastLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true)); Toast.makeText(getApplicationContext(), "111", Toast.LENGTH_SHORT).show(); if (lastLocation != null) { getDriverBO = new GetDriverBO(this, "" + lastLocation.getLatitude(), "" + lastLocation.getLongitude(), googleMap);/*from w ww . ja v a 2 s. com*/ // for (int i = 0; i < listDriver.size(); i++) { // Driver driver = listDriver.get(i); // LatLng latLng = new LatLng(driver.getLatitude(), // driver.getLongitude()); // MarkerOptions markerOptions = new MarkerOptions(); // markerOptions.title(driver.getFirstName() + " " // + driver.getLastName()); // markerOptions.snippet(distance); // markerOptions.position(latLng); // googleMap.addMarker(markerOptions); // } rider_current_position = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()); riderPosition = new MarkerOptions(); riderPosition.title("U stand here"); riderPosition.position(rider_current_position); googleMap.addMarker(riderPosition); // LatLng Taxi1 = new LatLng(21.009809, 105.523515); // LatLng Taxi2 = new LatLng(21.014917, 105.530317); // LatLng Taxi3 = new LatLng(21.010250, 105.532162); // final LatLng me = new LatLng(21.013475, 105.525425); // // MarkerOptions tx1 = new MarkerOptions(); // tx1.title("Nguyn Vn A"); // tx1.snippet("5KM"); // tx1.position(Taxi1); // MarkerOptions tx2 = new MarkerOptions(); // tx2.title("Nguyn Vn B"); // tx2.snippet("1KM"); // tx2.position(Taxi2); // MarkerOptions tx3 = new MarkerOptions(); // tx3.title("Nguyn Vn C"); // tx3.snippet("2KM"); // tx3.position(Taxi3); // MarkerOptions me1 = new MarkerOptions(); // me1.title("Here I stand"); // me1.position(me); // // googleMap.addMarker(tx1); // googleMap.addMarker(tx2); // googleMap.addMarker(tx3); // googleMap.addMarker(me1); googleMap.setMyLocationEnabled(true); googleMap.setOnMarkerClickListener(new OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { // TODO Auto-generated method stub List<Driver> drivers = AppController.getListDrivers(); for (int i = 0; i < drivers.size(); i++) { LatLng latLng = new LatLng(drivers.get(i).getLatitude(), drivers.get(i).getLongitude()); if (latLng.equals(marker.getPosition())) { driver = drivers.get(i); } } // Getting URL to the Google Directions API String url = getDirectionsUrl(rider_current_position, marker.getPosition()); DownloadTask downloadTask = new DownloadTask(); // Start downloading json data from Google Directions API downloadTask.execute(url); Toast.makeText(getApplicationContext(), "" + AppController.getDistance(), 3).show(); rider_send_request_information.setVisibility(View.VISIBLE); rider_send_request_first_step.setVisibility(View.VISIBLE); pick_point.setVisibility(View.VISIBLE); pick_start_point_value = (Button) findViewById(R.id.btn_pick_start_point_value); pick_end_point_value = (Button) findViewById(R.id.btn_pick_end_point_value); // Pich Start Point pick_start_point.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { pick_start_point_value.setVisibility(View.VISIBLE); // googleMap.clear(); PointLongitude = null; PointLatitude = null; googleMap.setOnMapClickListener(new OnMapClickListener() { @Override public void onMapClick(LatLng arg0) { Location targetLocation = new Location(""); targetLocation.setLatitude(arg0.latitude); targetLocation.setLongitude(arg0.longitude); PointLongitude = arg0.longitude; PointLatitude = arg0.latitude; if (lastMarker2 != null) { lastMarker2.remove(); } MarkerOptions startPoint = new MarkerOptions(); startPoint.position(arg0); startPoint.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_GREEN)); startPoint.title("Start Point"); Marker marker = googleMap.addMarker(startPoint); lastMarker2 = marker; } }); pick_start_point_value.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "" + PointLatitude, Toast.LENGTH_SHORT) .show(); if (PointLatitude != null & PointLongitude != null) { start_lat = PointLatitude; start_lng = PointLongitude; } else Toast.makeText(getApplicationContext(), "Please pick Start Point", Toast.LENGTH_LONG).show(); pick_start_point_value.setVisibility(View.GONE); pick_start_point.setText("Repick"); } }); } }); // Pick End Point pick_end_point.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { pick_end_point_value.setVisibility(View.VISIBLE); // googleMap.clear(); PointLongitude = null; PointLatitude = null; googleMap.setOnMapClickListener(new OnMapClickListener() { @Override public void onMapClick(LatLng arg0) { PointLongitude = arg0.longitude; PointLatitude = arg0.latitude; if (lastMarker3 != null) { lastMarker3.remove(); } MarkerOptions endPoint = new MarkerOptions(); endPoint.position(arg0); endPoint.icon(BitmapDescriptorFactory .defaultMarker(BitmapDescriptorFactory.HUE_YELLOW)); endPoint.title("End Point"); Marker marker = googleMap.addMarker(endPoint); lastMarker3 = marker; } }); pick_end_point_value.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (PointLatitude != null & PointLongitude != null) { end_lat = PointLatitude; end_lng = PointLongitude; } else Toast.makeText(getApplicationContext(), "Please pick End Point", Toast.LENGTH_LONG).show(); pick_end_point_value.setVisibility(View.GONE); pick_end_point.setText("Repick"); } }); } }); send_request = (Button) findViewById(R.id.btn_rider_send_request); send_request.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (Utils.isConnectingToInternet(getApplicationContext())) { DatabaseHandler handler = new DatabaseHandler(getApplicationContext()); Rider rider = handler.findRider(); driverid = driver.getId(); riderid = rider.getId(); tripBO.CreateTrip(MapActivity.this, riderid, driverid, "" + start_lat, "" + start_lng, "" + end_lat, "" + end_lng); rider_send_request_first_step.setVisibility(View.GONE); removeLayout(); rider_send_request_waiting_step.setVisibility(View.VISIBLE); handler.createTrip(AppController.getTripID(), TripStatus.NEW_TRIP); } else { // show error message alert.showAlertDialog(MapActivity.this, getResources().getString(R.string.alert_internet_error_title), getResources().getString(R.string.alert_internet_error_message), false); } } }); return false; } }); // Cancel Waiting Request cancelWaitingRequest.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { DatabaseHandler handler = new DatabaseHandler(getApplicationContext()); Rider rider = handler.findRider(); riderid = rider.getId(); tripBO.UpdateTrip(MapActivity.this, AppController.getTripID(), riderid, TripStatus.CANCELLED); rider_send_request_waiting_step.setVisibility(View.GONE); // rider_send_request_driver_accept.setVisibility(View.VISIBLE); } }); // Cancel Accepted Request cancelAcceptedRequest.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { DatabaseHandler handler = new DatabaseHandler(getApplicationContext()); Rider rider = handler.findRider(); riderid = rider.getId(); tripBO.UpdateTrip(MapActivity.this, AppController.getTripID(), riderid, TripStatus.CANCELLED); rider_send_request_driver_accept.setVisibility(View.GONE); } }); googleMap.setOnMapClickListener(new OnMapClickListener() { @Override public void onMapClick(LatLng arg0) { // TODO Auto-generated method stub // Hide infor box rider_send_request_first_step.setVisibility(View.GONE); rider_send_request_information.setVisibility(View.GONE); // Location targetLocation = new Location(""); // targetLocation.setLatitude(arg0.latitude); // targetLocation.setLongitude(arg0.longitude); // // float distanceInMeters = targetLocation // .distanceTo(lastLocation); // if (distanceInMeters > 1000) { // Toast.makeText(getApplicationContext(), "Out of range", // Toast.LENGTH_SHORT).show(); // } // Toast.makeText(getApplicationContext(), // " " + arg0.latitude + " " + arg0.longitude, // Toast.LENGTH_SHORT).show(); // if (lastMarker != null) { // lastMarker.remove(); // } // MarkerOptions hereIStand = new MarkerOptions(); // hereIStand.position(arg0); // Marker marker = googleMap.addMarker(hereIStand); // lastMarker = marker; } }); LatLng latLng = new LatLng(lastLocation.getLatitude(), lastLocation.getLongitude()); googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13)); CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng) // Sets the center of the map to location // user .zoom(15) // Sets the zoom .build(); // Creates a CameraPosition from the builder googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)); } }
From source file:com.seatgeek.placesautocompletedemo.MainFragment.java
private LatLng getLastKnownLocation(boolean isMoveMarker) { LocationManager lm = (LocationManager) TheApp.getAppContext().getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_LOW); String provider = lm.getBestProvider(criteria, true); if (provider == null) { return null; }/*from w ww .j a va 2 s .com*/ Activity activity = getActivity(); if (activity == null) { return null; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (activity.checkSelfPermission( Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && activity.checkSelfPermission( Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return null; } } Location loc = lm.getLastKnownLocation(provider); if (loc != null) { LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude()); if (isMoveMarker) { moveMarker(latLng); } return latLng; } return null; }