logo
down
shadow

get current location


get current location

By : enongene
Date : October 25 2020, 07:29 PM
hope this fix your issue I'm done creating an android program that adds a marker to a location. But I need to show CURRENT MY LOCATION in the MAP. I know this is done thru location based services but I don't know how to incorporate it into my program , In order to get the current location of your phone I use
code :


Share : facebook icon twitter icon
How to assign current geo-coordinates to draw path from current location to target location?

How to assign current geo-coordinates to draw path from current location to target location?


By : Madhumita Nandakumar
Date : March 29 2020, 07:55 AM
Does that help I am able to draw path between two sets of geo-coordinates from reference of , Its very Simple---
Make your Activity like this:--
code :
 public class GoogleMapLocationActivity extends MapActivity {

 private LocationManager myLocationManager;
 private LocationListener myLocationListener;
 private TextView myLongitude, myLatitude;
 private MapView myMapView;
 private MapController myMapController;
 LinearLayout zoomLayout;
 GeoPoint myLastPosition;
 AddItemizedOverlay mapOvlay;

 private void CenterLocatio(GeoPoint centerGeoPoint)
 {
  myMapController.animateTo(centerGeoPoint);

  List<Overlay> mapOverlays = myMapView.getOverlays();
  Drawable drawable = this.getResources().getDrawable(R.drawable.map_point);

  if(myLastPosition != null){
  mapOvlay = new AddItemizedOverlay(myLastPosition ,centerGeoPoint,drawable );
  OverlayItem overlayitem = new OverlayItem(centerGeoPoint,"","" );
  mapOvlay.addOverlay(overlayitem);
  mapOverlays.add(mapOvlay);
  }
      myLastPosition = centerGeoPoint;

};

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  myMapView = (MapView)findViewById(R.id.mapview);
         myLastPosition = null;
     myMapController = myMapView.getController();
     myMapController.setZoom(18); //Fixed Zoom Level

  myLocationManager = (LocationManager)getSystemService(
    Context.LOCATION_SERVICE);

  myLocationListener = new MyLocationListener();

  myLocationManager.requestLocationUpdates(
    LocationManager.GPS_PROVIDER,
    0,
    0,
    myLocationListener);

 private class MyLocationListener implements LocationListener{

      public void onLocationChanged(Location argLocation) {
        GeoPoint myGeoPoint = new GeoPoint(
        (int)(argLocation.getLatitude()*1000000),
         (int)(argLocation.getLongitude()*1000000));

     GeoPoint newGeoPoint = new  GeoPoint(myGeoPoint.getLatitudeE6() ,myGeoPoint.getLongitudeE6());
   CenterLocatio(newGeoPoint);
  }

  public void onProviderDisabled(String provider) {
      Toast.makeText(getBaseContext(),"GPS Disabled" ,Toast.LENGTH_SHORT).show();
  }

  public void onProviderEnabled(String provider) {
      Toast.makeText(getBaseContext(),"GPS Enabled" ,Toast.LENGTH_SHORT).show();
  }

  public void onStatusChanged(String provider,
    int status, Bundle extras) {
      Toast.makeText(getBaseContext(),"GPS Unavailable" ,Toast.LENGTH_SHORT).show();
  }
 }

 @Override
 protected boolean isRouteDisplayed() {
  return false;
 };

}
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {

       private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();

       private Context context;
       private GeoPoint mGpt1;
       private GeoPoint mGpt2;

       public AddItemizedOverlay(GeoPoint gp1,GeoPoint gp2, Drawable defaultMarker) {

            super(boundCenterBottom(defaultMarker));
             mGpt1 = gp1;
             mGpt2 = gp2;
        }


       public AddItemizedOverlay(Drawable defaultMarker) {
            super(boundCenterBottom(defaultMarker));
       }

       public AddItemizedOverlay(Drawable defaultMarker, Context context) {
            this(defaultMarker);
            this.context = context;
       }

       @Override
       protected OverlayItem createItem(int i) {
          return mapOverlays.get(i);
       }

       @Override
       public int size() {
          return mapOverlays.size();
       }

       @Override
       protected boolean onTap(int index) {
          Log.e("Tap", "Tap Performed");
          return true;
       }

       public void addOverlay(OverlayItem overlay) {
          mapOverlays.add(overlay);
           this.populate();
       }

       public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
                long when) {
             super.draw(canvas, mapView, shadow);
             Paint paint;
             paint = new Paint();
             paint.setColor(Color.RED);
             paint.setAntiAlias(true);
             paint.setStyle(Style.STROKE);
             paint.setStrokeWidth(2);
             Point pt1 = new Point();
             Point pt2 = new Point();
             Projection projection = mapView.getProjection();
             projection.toPixels(mGpt1, pt1);
             projection.toPixels(mGpt2, pt2);
             canvas.drawLine(pt1.x, pt1.y, pt2.x, pt2.y, paint);
             return true;
          }
    }
Get Current Location 0 in marshmallow where below 23 API its give exact current Location using fused Location

Get Current Location 0 in marshmallow where below 23 API its give exact current Location using fused Location


By : virat virat
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
code :
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();
    }
}
Else than current location, how to take user input from google map in android?(not the current location)

Else than current location, how to take user input from google map in android?(not the current location)


By : Devanshi Ganegoda
Date : March 29 2020, 07:55 AM
will help you As I understand you want to click on any place on the map and select it.
Read here how to do that.
Will location manager find the current location repeatedly after it finds the current location in iPhone?

Will location manager find the current location repeatedly after it finds the current location in iPhone?


By : user3874440
Date : March 29 2020, 07:55 AM
To fix this issue According to the CoreLocationManager reference
why getting the current location using google map and android sometimes return the last location not the current locatio

why getting the current location using google map and android sometimes return the last location not the current locatio


By : Dirk Fromhein
Date : March 29 2020, 07:55 AM
this will help You are calling getLastLocation(); that will return the last time your GPS device was able to fetch a location.
If you want to force the device to fetch a location try:
Related Posts Related Posts :
  • Getting a string value from the strings.xml resource file and set it in an interface class
  • Flutter, sign with both debug keys and release keys on Android
  • will an android service run code from the Xamarin Forms Project even when the app is closed?
  • Change boolean values on listviewitems in firebase
  • Android Studio 3.2.1: mixing versions can lead to runtime crashes when connect firebase
  • FCM migration without losing the old token
  • Change reported Version Number in Fabric Crashlytics
  • lateinit property mMap has not been initialized
  • Android - PWA does not open in standalone mode with service worker
  • Does LeakCanary has callback?
  • How to disable back button after splash screen in React Native
  • Assets Folder Not Including HTML Files In NativeScript Android Build
  • Dagger: What if I *WANT* a new instance every time?
  • How to get mailto working on android chrome?
  • SSO web login in android app with customtabs
  • how to make specific button side curved
  • remove item onlongclick from listview
  • header image alignment coming wrongly in NavigationView android
  • How to add many spaces after the text in TextView
  • how to set "Back Button" , closing activies except main activity in android?
  • Unable to run emulator on Android Studio || Windows 10
  • How can I achieve this requirement using Rx Java
  • How to tilt a Node(or TransformableNode)object downwards in Sceneform(Ar Core)?
  • When to use RTL and LTR?
  • How to create a tab view (category) similar to instagram's explore tab
  • Glide, RecyclerView: Glide returns the same picture over and over again even with different data inputs
  • how to stop open activity while splash screen killed
  • Changing the Color of the Dynamically loaded Buttons onclick
  • Listview: Add arrows as dividers
  • Show confirmation on back/up in Fragment with Navigation Architecture Component
  • How to find the corresponding maven artifact/gradle module of an Android class from the API Docs?
  • ZXing 3.6.0 in portrait mode?
  • Can't use Subversion command line client: svn The path to the Subversion executable is probably wrong android
  • how to set spinner list value first position showing empty
  • When using PersistableBundle in onCreate, it shows me a blank page
  • Failed to resolve Bintray dependency
  • jacoco code coverage not working for Android applications
  • How to change the color of the Android scroll bumper
  • Why run Handler in main Looper thread
  • Android Studio combined chart crashes
  • Setting suggested width and height to a custom view in android
  • How to set input type and format in EditText using kotlin?
  • how to define Android Oncreate optionmenu
  • Exception on orientation change from two-pane mode to one-pane mode
  • How to access members of nested struct and assign them the values read from device tree?
  • How to measure upload progress of a huge String with Retrofit 2?
  • Runtime app localization doesn't work with app bundles
  • How create View and Putting TextView inside it in kotlin
  • how to integrate app action using actions.xml?
  • ConstraintLayout - center TextView in the root but don't override Button
  • Android Studio Text not conforming to layout_margin when I run App on Emulator
  • verifyReleaseResources apk release - react native
  • My app is not visible in share dialog even with intent filters in place
  • How to use cache or local storage?
  • Unhandled Exception in Recycler view xamarin
  • Android Workmanger PeriodicWorkRequest API work only once?
  • Using Touch ID or Face ID without storing user biometrics
  • React Native 3 button and 3 Modal
  • Token Expiration after 1 Hour in Authentication using Retrofit 2 and Logging Interceptor
  • JNI DETECTED ERROR IN APPLICATION: JNI NewGlobalRef called with pending exception java.lang.ClassNotFoundException:
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org