How do i get my code to give my current location?
Date : January 11 2021, 03:32 PM
|
help you fix your problem I will try and assist. I will assume you have all the requisite libraries in your gradle. Check if you have implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.libraries.places:places:1.0.0'
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
public static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
String[] PERMISSIONS = {Manifest.permission.INTERNET,Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.CAMERA };
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, 1);
}
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
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.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.widget.AutocompleteSupportFragment;
import com.google.android.libraries.places.widget.listener.PlaceSelectionListener;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
public class SetPickUpLocation extends FragmentActivity implements OnMapReadyCallback {
SupportMapFragment mapFragment;
private GoogleMap mMap;
private GoogleMap.OnCameraIdleListener onCameraIdleListener;
private TextView resutText;
private FusedLocationProviderClient fusedLocationProviderClient;
private static final int MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 5445;
private Location currentLocation;
public static String latitude = null, longitude = null, location = null, area = null;
private boolean firstTimeFlag = true;
Button setLocation;
View mapView;
AutocompleteSupportFragment autocompleteFragment;
String TAG = "Google_Places";
int AUTOCOMPLETE_REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_pickup_location);
resutText = (TextView) findViewById(R.id.dragg_result);
setLocation = (Button) findViewById(R.id.setLocation);
autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment);
mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
mapView = mapFragment.getView();
Toast.makeText(SetPickUpLocation.this, ConstantValues.DRAG_MAP_MARKER, Toast.LENGTH_SHORT).show();
configureCameraIdle();
Places.initialize(getApplicationContext(), ConstantValues.GOOGLE_API_KEY);
setLocation.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (latitude != null && longitude != null) {
//you can put your logic here
}else{
//you can put your logic here
}
}
});
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME , Place.Field.LAT_LNG));
//autocompleteFragment.setTypeFilter(TypeFilter.REGIONS);
autocompleteFragment.setCountry("KE");
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
//Log.d(TAG , place.getName() + ", " + place.getId());
if(mMap != null){
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(place.getLatLng(), 16);
mMap.animateCamera(cameraUpdate);
autocompleteFragment.setText("");
}
//
//mMap.mo
}
@Override
public void onError(Status status) {
// TODO: Handle the error.
Log.d(TAG , "An error occurred: " + status);
}
});
}
@Override
protected void onStop() {
super.onStop();
if (fusedLocationProviderClient != null)
fusedLocationProviderClient.removeLocationUpdates(mLocationCallback);
}
@Override
protected void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
startCurrentLocationUpdates();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
fusedLocationProviderClient = null;
mMap = null;
}
private void configureCameraIdle() {
onCameraIdleListener = new GoogleMap.OnCameraIdleListener() {
@Override
public void onCameraIdle() {
LatLng latLng = mMap.getCameraPosition().target;
Geocoder geocoder = new Geocoder(SetPickUpLocation.this);
try {
List<Address> addressList = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if (addressList != null && addressList.size() > 0) {
String locality = addressList.get(0).getAddressLine(0);
String country = addressList.get(0).getCountryName();
latitude = Double.toString(latLng.latitude);
longitude = Double.toString(latLng.longitude);
if (!locality.isEmpty() && !country.isEmpty()) {
resutText.setText(locality);
location = locality;
try{
String city = addressList.get(0).getAdminArea();
if(!city.isEmpty()){
area = city;
}
}catch (Exception e){
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnCameraIdleListener(onCameraIdleListener);
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.
return;
}
mMap.setMyLocationEnabled(true);
if (mapView != null &&
mapView.findViewById(Integer.parseInt("1")) != null) {
// Get the button view
View locationButton = ((View) mapView.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
// and next place it, on bottom right (as Google Maps app)
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
// position on right bottom
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
layoutParams.setMargins(0, 0, 100, 330);
}
}
private final LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult.getLastLocation() == null)
return;
currentLocation = locationResult.getLastLocation();
if (firstTimeFlag && mMap != null) {
animateCamera(currentLocation);
firstTimeFlag = false;
}
//showMarker(currentLocation);
}
};
private void startCurrentLocationUpdates() {
LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(3000);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
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) {
ActivityCompat.requestPermissions(SetPickUpLocation.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION);
return;
}
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, mLocationCallback, Looper.myLooper());
}
private boolean isGooglePlayServicesAvailable() {
GoogleApiAvailability googleApiAvailability = GoogleApiAvailability.getInstance();
int status = googleApiAvailability.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status)
return true;
else {
if (googleApiAvailability.isUserResolvableError(status))
Toast.makeText(this, "Please Install google play services to use this application", Toast.LENGTH_LONG).show();
}
return false;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_DENIED)
Toast.makeText(this, "Permission denied by uses", Toast.LENGTH_SHORT).show();
else if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
startCurrentLocationUpdates();
}
}
private void animateCamera(@NonNull Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(getCameraPositionWithBearing(latLng)));
}
@NonNull
private CameraPosition getCameraPositionWithBearing(LatLng latLng) {
return new CameraPosition.Builder().target(latLng).zoom(16).build();
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".orders.SetPickUpLocation">
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.v7.widget.CardView
android:id="@+id/idCardView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
app:cardCornerRadius="4dp">
<fragment
android:id="@+id/autocomplete_fragment"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.v7.widget.CardView>
<ImageView
android:layout_width="36dp"
android:layout_height="36dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="@drawable/ic_google_map_marker"
android:text="TextView" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="#ffffff"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_horizontal_margin"
android:weightSum="3">
<ImageView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.2"
android:gravity="center_vertical"
android:src="@drawable/ic_google_map_marker" />
<TextView
android:id="@+id/dragg_result"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="2.8"
android:fontFamily="@font/museo"
android:gravity="left"
android:paddingLeft="3dp"
android:text="Select this location"
android:textColor="#000"
android:textSize="18dp" />
</LinearLayout>
<Button
android:id="@+id/setLocation"
style="?android:attr/borderlessButtonStyle"
android:layout_width="match_parent"
android:layout_height="65dp"
android:layout_marginBottom="@dimen/activity_horizontal_margin"
android:fontFamily="@font/museo"
android:text="Select this location"
android:textColor="#ffffff"
android:textSize="18sp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
Boards Message : |
You Must Login
Or Sign Up
to Add Your Comments . |
Share :
|
Using GPS to get current location i just use this following code But i dont get a Toast msg Like My current location is:
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Go to the Eclipse Toolbar Click on Window-> Show view -> DDMS -> Emulator control in the emulator control manually enter location Longitude and Latitude , then check hope it works fine !!!
|
getLastKnownLocation() does not necessarily give current location
Date : March 29 2020, 07:55 AM
Does that help Have you tried requesting permission to the ACCESS_FINE_LOCATION provider in your manifest and then from the LocationManager, calling getLastKnownLocation(LocationManager.GPS_PROVIDER)? It should return to you the last known location acquired by the GPS provider, else null if it can't get the location
|
Search specific keyword and give results nearer to our current location
Tag : php , By : Steve Jones
Date : March 29 2020, 07:55 AM
I wish this help you As I see you are already familiar with the geolocation filters provided by solr. So what is your problem here? Do you already provide the geolocation when you index your data? //The form you use for the submission of your search query
<form action="search.php" method="post">
//Here are your form elements below are the hidden fields.
<input type="hidden" name="long" value=""/>
<input type="hidden" name="lat" value=""/>
</form>
<script type="text/javascript">
//Getting the location once the page finished loading
$( document ).ready(
function()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
});
//Location callback. We set the long and lat values of the hidden fields.
function showPosition(position)
{
$('[name="lat"]').val(position.coords.latitude);
$('[name="long"]').val(position.coords.longitude);
}
</script>
//The form was submitted so in your form submission handling code:
$long = $_POST["long"];
$lat= $_POST["lat"];
//Now you have your variables. You can now put them inside your query
//DO your query
|
Get Current Location 0 in marshmallow where below 23 API its give exact current Location using fused Location
Date : March 29 2020, 07:55 AM
Any of those help I got exact problem after some debugging and searching GoogleAPIclient onConnected() not called so it called onConnectionFailed() method private synchronized void buildGoogleApiClient() {
Log.i("TAG", "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity().getApplicationContext())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
createLocationRequest();}
private void createLocationRequest() {
Log.i("TAG", "CreateLocationRequest");
mLocationRequest = new LocationRequest();
long UPDATE_INTERVAL = 10 * 1000;
mLocationRequest.setInterval(UPDATE_INTERVAL);
long FASTEST_INTERVAL = 10000;
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
builder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
//**************************
builder.setAlwaysShow(true); //this is the key ingredient
//**************************
}
private void startLocationUpdates() {
Log.i("TAG", "StartLocationUpdates");
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
} else {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
private void stopLocationUpdates() {
Log.i("TAG", "StopLocationUpdates");
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
@Override
public void onConnectionSuspended(int i) {
Log.i("TAG", "onConnectionSuspended");
if (i == CAUSE_SERVICE_DISCONNECTED) {
Toast.makeText(getActivity().getApplicationContext(), "Disconnected. Please re-connect.", Toast.LENGTH_SHORT).show();
} else if (i == CAUSE_NETWORK_LOST) {
Toast.makeText(getActivity().getApplicationContext(), "Network lost. Please re-connect.", Toast.LENGTH_SHORT).show();
}
mGoogleApiClient.connect();
}
@Override
public void onLocationChanged(Location location) {
Log.i("TAG", "OnLocationChanged");
Log.i("TAG", "Current Location==>" + location);
currentlatitude = location.getLatitude();
currentlongitude = location.getLongitude();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(getActivity(), connectionResult.RESOLUTION_REQUIRED);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.e("TAG", "Location services connection failed with code==>" + connectionResult.getErrorCode());
Log.e("TAG", "Location services connection failed Because of==> " + connectionResult.getErrorMessage());
}
}
@Override
public void onDestroy() {
super.onDestroy();
if (mGoogleApiClient != null)
mGoogleApiClient.disconnect();
}
@Override
public void onConnected(Bundle bundle) {
Location mCurrentLocation;
Log.i("TAG", "OnConnected");
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(getActivity().getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
// Note that this can be NULL if last location isn't already known.
if (mCurrentLocation != null) {
// Print current location if not null
Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
currentlatitude = mCurrentLocation.getLatitude();
currentlongitude = mCurrentLocation.getLongitude();
} else {
startLocationUpdates();
}
}
} else {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
// Note that this can be NULL if last location isn't already known.
if (mCurrentLocation != null) {
// Print current location if not null
Log.d("DEBUG", "current location: " + mCurrentLocation.toString());
currentlatitude = mCurrentLocation.getLatitude();
currentlongitude = mCurrentLocation.getLongitude();
}
// Begin polling for new location updates.
startLocationUpdates();
}
}
|
Give java.lang.NullPointerException: when i click on current location button
Date : December 26 2020, 03:01 AM
I wish did fix the issue. Check for location is enabled/ disabled state If location is disabled then result will be null.
|
|
|
Related QUESTIONS :
|