Java Code Examples for android.location.Location#getLatitude()

The following examples show how to use android.location.Location#getLatitude() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SensorDataUtil.java    From sensordatacollector with GNU General Public License v2.0 7 votes vote down vote up
/**
 * Checks if new location is
 * remarkably diffrent from
 * the new location
 */
public static boolean isRemarkableChange(Location oldLocation, Location newLocation)
{
    if(oldLocation == null || newLocation == null) {
        return true;
    }

    long m = 10000;

    double diffLong = (oldLocation.getLatitude() - newLocation.getLatitude()) * m;
    double diffLat = (oldLocation.getLatitude() - newLocation.getLatitude()) * m;

    double diff = Math.sqrt(diffLong * diffLong + diffLat * diffLat);

    return diff > 7;
}
 
Example 2
Source File: MapLoadFragment.java    From Stayfit with Apache License 2.0 6 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    // Add a marker in Sydney and move the camera
    LatLng sydney = new LatLng(AskLocationActivity.address1.getLatitude(), AskLocationActivity.address1.getLongitude());
    mMap.addMarker(new MarkerOptions().position(sydney).title(AskLocationActivity.place1));
    // mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    //move camera when location changed
    LatLng latLng_Now = new LatLng(location.getLatitude(), location.getLongitude());
    CameraPosition cameraPosition = new CameraPosition.Builder()
            .target(sydney)      // Sets the center of the map to LatLng (refer to previous snippet)
            .zoom(17)                   // Sets the zoom
            .bearing(90)                // Sets the orientation of the camera to east
            .tilt(45)                   // Sets the tilt of the camera to 45 degrees
            .build();                   // Creates a CameraPosition from the builder
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    if (latLng_Prev == null) {
        latLng_Prev = latLng_Now;
    }
    //draw line between two locations:
   /* Polyline line = mMap.addPolyline(new PolylineOptions()
            .add(latLng_Prev, latLng_Now)
            .width(5)
            .color(Color.RED));
    latLng_Prev = latLng_Now;*/
}
 
Example 3
Source File: AmapFragment.java    From BmapLite with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onMyLocationChange(Location location) {
    if (null != location && null != mMapView) {
        if (null == BApp.MY_LOCATION) {
            BApp.MY_LOCATION = new MyPoiModel(BApp.TYPE_MAP);
        }
        BApp.MY_LOCATION.setLongitude(location.getLongitude());
        BApp.MY_LOCATION.setLatitude(location.getLatitude());
        BApp.MY_LOCATION.setName("我的位置");
        BApp.MY_LOCATION.setAltitude(location.getAltitude());
        BApp.MY_LOCATION.setAccuracy(location.getAccuracy());

        if (isFirstLoc || isRequest) {

            if (location.getLatitude() == 0 || location.getLongitude() == 0
                    || location.getLatitude() == 4.9E-324 || location.getLongitude() == 4.9E-324) {
                onMessage("无法获取到位置信息,请连接网络后再试");
                return;
            }

            mAmap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(BApp.MY_LOCATION.getLatitude(), BApp.MY_LOCATION.getLongitude())));
            mSearchInteracter.searchLatLng(BApp.MY_LOCATION.getLatitude(), BApp.MY_LOCATION.getLongitude(), 1, this);

            CacheInteracter cacheInteracter = new CacheInteracter(getActivity());
            cacheInteracter.setLatitude(location.getLatitude());
            cacheInteracter.setLongitude(location.getLongitude());

            if (isFirstLoc) {
                ((MainActivity) getActivity()).firstLocationComplete();
                isFirstLoc = false;
            }

            isRequest = false;
        }

    }

}
 
Example 4
Source File: MainActivity.java    From ExamplesAndroid with Apache License 2.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    if (mCurrLocationMarker != null) {
        mCurrLocationMarker.remove();
    }


    //MyItem current location marker
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    latitud = location.getLatitude();
    longitud = location.getLongitude();


    CameraPosition PosicionCamara = CameraPosition.builder()
            .target(latLng)//Direccion de la camara
            .zoom(20)//Zoom al mapa
            .bearing(90)//Dirección que la cámara está apuntando en, en grados en sentido horario desde el norte.
            .build();


    mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(PosicionCamara),
            6000, null);
    //move map camera
    // mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(15));


    if (mGoogleApiClient != null) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }


}
 
Example 5
Source File: AmapRouteFragment.java    From BmapLite with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onMyLocationChange(Location location) {
    if (null != location && null != mMapView) {
        if (null == BApp.MY_LOCATION) {
            BApp.MY_LOCATION = new MyPoiModel(BApp.TYPE_MAP);
        }
        BApp.MY_LOCATION.setLongitude(location.getLongitude());
        BApp.MY_LOCATION.setLatitude(location.getLatitude());
        BApp.MY_LOCATION.setName("我的位置");

        if (isFirstLoc || isRequest) {

            if (location.getLatitude() == 0 || location.getLongitude() == 0
                    || location.getLatitude() == 4.9E-324 || location.getLongitude() == 4.9E-324) {
                onMessage("无法获取到位置信息,请连接网络后再试");
                return;
            }

            mAmap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(BApp.MY_LOCATION.getLatitude(), BApp.MY_LOCATION.getLongitude())));
            mSearchInteracter.searchLatLng(BApp.MY_LOCATION.getLatitude(), BApp.MY_LOCATION.getLongitude(), 1, this);

            CacheInteracter cacheInteracter = new CacheInteracter(getActivity());
            cacheInteracter.setLatitude(location.getLatitude());
            cacheInteracter.setLongitude(location.getLongitude());

            isRequest = false;
            isFirstLoc = false;
        }

    }
}
 
Example 6
Source File: FragmentiGapMap.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * ****************************** methods ******************************
 */

private void currentLocation(Location location, boolean setDefaultZoom) {
    GeoPoint startPoint = new GeoPoint(location.getLatitude(), location.getLongitude());
    if (setDefaultZoom) {
        map.getController().setZoom(16);
    }
    map.getController().animateTo(startPoint);
    G.handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            initMapListener();
        }
    }, 2000);
}
 
Example 7
Source File: NavigationOverlay.java    From WhereYouGo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public synchronized void draw(BoundingBox boundingBox, byte zoomLevel, Canvas canvas) {
    // TODO Auto-generated method stub
    if (target == null || !myLocationOverlay.isMyLocationEnabled()
            || myLocationOverlay.getLastLocation() == null)
        return;
    double canvasPixelLeft =
            MercatorProjection.longitudeToPixelX(boundingBox.minLongitude, zoomLevel);
    double canvasPixelTop = MercatorProjection.latitudeToPixelY(boundingBox.maxLatitude, zoomLevel);
    Point canvasPosition = new Point(canvasPixelLeft, canvasPixelTop);

    Location startLocation = myLocationOverlay.getLastLocation();
    GeoPoint start = new GeoPoint(startLocation.getLatitude(), startLocation.getLongitude());

    List<GeoPoint> geoPoints = new ArrayList<GeoPoint>();
    geoPoints.add(start);
    geoPoints.add(target);
    line.setPolygonalChain(new PolygonalChain(geoPoints));
    line.draw(boundingBox, zoomLevel, canvas, canvasPosition);

/*
 * double canvasPixelLeft = MercatorProjection.longitudeToPixelX( boundingBox.minLongitude,
 * zoomLevel); double canvasPixelTop = MercatorProjection.latitudeToPixelY(
 * boundingBox.maxLatitude, zoomLevel); Point canvasPosition = new Point(canvasPixelLeft,
 * canvasPixelTop); Point a = getPoint(start, canvasPosition, zoomLevel); Point b =
 * getPoint(target, canvasPosition, zoomLevel); canvas.drawLine(a.x, a.y, b.x, b.y, paint);
 */
}
 
Example 8
Source File: Pathfinder.java    From codeexamples-android with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void onLocationChanged(Location location) {
	System.out.println("Called");
	int lat = (int) (location.getLatitude() * 1E6);
	int lng = (int) (location.getLongitude() * 1E6);
	edit1.setText(lat);
	edit2.setText(lng);
}
 
Example 9
Source File: Util.java    From BackPackTrackII with GNU General Public License v3.0 5 votes vote down vote up
public static void geoShare(Location location, String name, Context context) {
    try {
        // https://developer.android.com/guide/components/intents-common.html#Maps
        // https://developers.google.com/maps/documentation/android/intents
        String uri = "geo:" + location.getLatitude() + "," + location.getLongitude() +
                "?q=" + location.getLatitude() + "," + location.getLongitude() +
                (name == null ? "" : "(" + Uri.encode(name) + ")");
        context.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(uri)));
    } catch (Throwable ex) {
        Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
        Toast.makeText(context, ex.toString(), Toast.LENGTH_SHORT).show();
    }
}
 
Example 10
Source File: OverlayManagerTest.java    From android with Apache License 2.0 5 votes vote down vote up
@Test public void setMyLocationEnabled_shouldUpdateMapStateManager() {
  overlayManager.setMyLocationEnabled(true);
  findMeButton.performClick();
  verify(mapStateManager).setZoom(16f);
  Location loc = LocationServices.FusedLocationApi.getLastLocation(lostApiClient);
  LngLat lngLat = new LngLat(loc.getLongitude(), loc.getLatitude());
  verify(mapStateManager).setPosition(lngLat);
}
 
Example 11
Source File: AttractionListFragment.java    From wear-os-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Location location =
            intent.getParcelableExtra(FusedLocationProviderApi.KEY_LOCATION_CHANGED);
    if (location != null) {
        mLatestLocation = new LatLng(location.getLatitude(), location.getLongitude());
        mAdapter.mAttractionList = loadAttractionsFromLocation(mLatestLocation);
        mAdapter.notifyDataSetChanged();
    }
}
 
Example 12
Source File: AttachFile.java    From iGap-Android with GNU Affero General Public License v3.0 5 votes vote down vote up
private void getPosition(Fragment fragment) {

        try {
            if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                showSettingsAlert(fragment);
            } else {
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location == null) {
                    location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
                if (location != null) {
                    location.getLatitude();
                    location.getLongitude();

                    String position = String.valueOf(location.getLatitude()) + "," + String.valueOf(location.getLongitude());

                    if (complete != null) complete.complete(true, position, "");
                } else {
                    sendPosition = true;
                    pd = new ProgressDialog(context);
                    pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                    pd.setMessage(context.getString(R.string.just_wait_en));
                    pd.setIndeterminate(false);
                    pd.setCancelable(true);
                    pd.show();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
Example 13
Source File: RecommendedRouteFragment.java    From rox-android with Apache License 2.0 5 votes vote down vote up
private void showCurrentLocationInMap() {
    Location currentLocation = getCurrentLocationArg();
    LatLng latLng = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude());
    googleMap.addMarker(new MarkerOptions()
            .position(latLng)
            .title(getString(R.string.current_location))
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_map_location)));
    googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 13f));
}
 
Example 14
Source File: GglMapLocationManager.java    From FimiX8-RE with MIT License 5 votes vote down vote up
private void startMoveLocationAndMap(Location location) {
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    Log.i("位置", "latLng" + latLng.toString());
    if (this.locationMarker != null) {
        this.locationMarker.setPosition(latLng);
    }
}
 
Example 15
Source File: YahooPlacesAPIClient.java    From BetterWeather with Apache License 2.0 4 votes vote down vote up
public static String buildPlaceSearchUrl(Location l) throws MalformedURLException {
    // GeoPlanet API
    return "http://where.yahooapis.com/v1/places.q('"
            + l.getLatitude() + "," + l.getLongitude() + "')"
            + "?lang=" + sLang + "&appid=" + API_KEY;
}
 
Example 16
Source File: LocationService.java    From nearby-android with Apache License 2.0 4 votes vote down vote up
public void setCurrentLocation(final Location currentLocation) {
  mCurrentLocation =  new Point(currentLocation.getLongitude(), currentLocation.getLatitude());
}
 
Example 17
Source File: n.java    From MiBandDecompiled with Apache License 2.0 4 votes vote down vote up
static void a(n n1, Location location)
{
    if (location == null || location.getLatitude() > 359D || location.getLongitude() > 359D)
    {
        if (n1.w != null && n1.w.a())
        {
            n1.b(true);
        } else
        {
            n1.e();
        }
    }
    n1.z = new d();
    n1.z.z = 0;
    n1.z.y = 0;
    n1.z.b = com.tencent.b.b.s.a(location.getLatitude(), 6);
    n1.z.c = com.tencent.b.b.s.a(location.getLongitude(), 6);
    if (n1.w != null && n1.w.a())
    {
        n1.z.e = com.tencent.b.b.s.a(n1.w.b().getAccuracy(), 1);
        n1.z.d = com.tencent.b.b.s.a(n1.w.b().getAltitude(), 1);
        n1.z.f = com.tencent.b.b.s.a(n1.w.b().getSpeed(), 1);
        n1.z.g = com.tencent.b.b.s.a(n1.w.b().getBearing(), 1);
        n1.z.a = 0;
    }
    n1.z.x = true;
    if (n1.l != 0 && n1.A != null && n1.B == 0)
    {
        if ((n1.l == 3 || n1.l == 4) && n1.l == n1.A.z)
        {
            n1.z.i = n1.A.i;
            n1.z.j = n1.A.j;
            n1.z.k = n1.A.k;
            n1.z.l = n1.A.l;
            n1.z.m = n1.A.m;
            n1.z.n = n1.A.n;
            n1.z.o = n1.A.o;
            n1.z.p = n1.A.p;
            n1.z.z = 3;
        }
        if (n1.l == 4 && n1.l == n1.A.z && n1.A.w != null)
        {
            n1.z.w = new ArrayList();
            c c1;
            for (Iterator iterator = n1.A.w.iterator(); iterator.hasNext(); n1.z.w.add(new c(c1)))
            {
                c1 = (c)iterator.next();
            }

            n1.z.z = 4;
        }
        if (n1.l == 7 && n1.l == n1.A.z)
        {
            n1.z.z = 7;
            n1.z.h = n1.A.h;
            n1.z.i = n1.A.i;
            if (n1.A.h == 0)
            {
                n1.z.j = n1.A.j;
                n1.z.k = n1.A.k;
                n1.z.l = n1.A.l;
                n1.z.m = n1.A.m;
                n1.z.n = n1.A.n;
                n1.z.o = n1.A.o;
                n1.z.p = n1.A.p;
            } else
            {
                n1.z.q = n1.A.q;
                n1.z.r = n1.A.r;
                n1.z.s = n1.A.s;
                n1.z.t = n1.A.t;
                n1.z.u = n1.A.u;
                n1.z.v = n1.A.v;
            }
        }
    }
    if (n1.B != 0 || n1.A != null)
    {
        if (n1.B != 0)
        {
            n1.z.y = n1.B;
        }
        if (System.currentTimeMillis() - n1.v >= n1.a && n1.j != null && n1.k == 1)
        {
            n1.j.onLocationUpdate(n1.z);
            n1.v = System.currentTimeMillis();
        }
    }
}
 
Example 18
Source File: BackgroundService.java    From BackPackTrackII with GNU General Public License v3.0 4 votes vote down vote up
private void handlePassiveLocationUpdate(Intent intent) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

    // Process passive location update
    Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
    Log.i(TAG, "Update passive location=" + location);
    if (location == null || (location.getLatitude() == 0.0 && location.getLongitude() == 0.0))
        return;

    // Filter inaccurate passive locations
    int pref_inaccurate = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_INACCURATE, SettingsFragment.DEFAULT_PASSIVE_INACCURATE));
    if (!location.hasAccuracy() || location.getAccuracy() > pref_inaccurate) {
        Log.i(TAG, "Filtering inaccurate passive location=" + location);
        return;
    }

    // Get last location
    Location lastLocation = LocationDeserializer.deserialize(prefs.getString(SettingsFragment.PREF_LAST_LOCATION, null));
    if (lastLocation == null) {
        Log.i(TAG, "Passive location without last location, location=" + location);
        return;
    }

    // Filter old locations
    if (location.getTime() <= lastLocation.getTime()) {
        Log.i(TAG, "Passive location is older than last location, location=" + location);
        return;
    }

    // Correct altitude
    correctAltitude(location, this);

    // Filter nearby passive locations
    int pref_nearby = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_NEARBY, SettingsFragment.DEFAULT_PASSIVE_NEARBY));
    if (Util.distance(lastLocation, location) < pref_nearby &&
            (lastLocation.hasAccuracy() ? lastLocation.getAccuracy() : Float.MAX_VALUE) <=
                    (location.hasAccuracy() ? location.getAccuracy() : Float.MAX_VALUE)) {
        Log.i(TAG, "Filtering nearby passive location=" + location);
        return;
    }

    float bchange = 0;
    double achange = 0;
    boolean update = false;

    // Handle bearing change
    if (location.hasBearing()) {
        int pref_bearing_change = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_BEARING, SettingsFragment.DEFAULT_PASSIVE_BEARING));
        bchange = Math.abs(lastLocation.getBearing() - location.getBearing());
        if (bchange > 180)
            bchange = 360 - bchange;
        if (!lastLocation.hasBearing() || bchange > pref_bearing_change) {
            Log.i(TAG, "Bearing changed to " + location.getBearing());
            update = true;
        }
    }

    // Handle altitude change
    if (location.hasAltitude()) {
        int pref_altitude_change = Integer.parseInt(prefs.getString(SettingsFragment.PREF_PASSIVE_ALTITUDE, SettingsFragment.DEFAULT_PASSIVE_ALTITUDE));
        achange = Math.abs(lastLocation.getAltitude() - location.getAltitude());
        if (!lastLocation.hasAltitude() || achange > pref_altitude_change) {
            Log.i(TAG, "Altitude changed to " + location.getAltitude());
            update = true;
        }
    }

    if (update) {
        // Persist new location
        prefs.edit().putString(SettingsFragment.PREF_LAST_LOCATION, LocationSerializer.serialize(location)).apply();
        DatabaseHelper dh = null;
        try {
            dh = new DatabaseHelper(this);
            int altitude_type = (location.hasAltitude() ? ALTITUDE_GPS : ALTITUDE_NONE);
            dh.insertLocation(location, altitude_type, null).close();
        } finally {
            if (dh != null)
                dh.close();
        }

        // Feedback
        showStateNotification(this);
        if (Util.debugMode(this))
            Util.toast(getString(R.string.title_trackpoint) +
                    " " + getProviderName(location, this) +
                    " " + Math.round(bchange) +
                    "° / " + Math.round(achange) + "m", Toast.LENGTH_SHORT, this);
    }
}
 
Example 19
Source File: MapFragment.java    From open with GNU General Public License v3.0 4 votes vote down vote up
public GeoPoint getUserLocationPoint() {
    Location userLocation = mapController.getLocation();
    return new GeoPoint(userLocation.getLatitude(), userLocation.getLongitude());
}
 
Example 20
Source File: MobileDataLayerListenerService.java    From climb-tracker with Apache License 2.0 4 votes vote down vote up
@Override
public void onDataChanged(DataEventBuffer dataEvents) {
    Log.d(TAG, "onDataChanged: " + dataEvents);
    final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents);
    dataEvents.close();

    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    String gradeSystemType = sharedPref.getString(Path.PREF_GRAD_SYSTEM_TYPE, GradeList.SYSTEM_DEFAULT);

    Location lastLocation = null;

    if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        lastLocation  = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    }

    for (DataEvent event : events) {
        Log.d(TAG, "Event: " + event.getDataItem().toString());
        Uri uri = event.getDataItem().getUri();
        String path = uri.getPath();

        if (path.startsWith(Path.CLIMB)) {
            DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem());
            String routeGradeLabel = dataMapItem.getDataMap().getString(Path.ROUTE_GRADE_LABEL_KEY);
            Date climbDate = new Date(dataMapItem.getDataMap().getLong(Path.CLIMB_DATE_KEY));

            // check that climb date and location date are not too far, do not save location if so.
            double latitude = 0;
            double longitude = 0;
            if(lastLocation != null && Math.abs(lastLocation.getTime() - climbDate.getTime()) < MAX_TIME_FOR_LOCATION) {
                latitude = lastLocation.getLatitude();
                longitude = lastLocation.getLongitude();
            }

            if (routeGradeLabel != null) {
                Log.d(TAG, "New Climb, grade : " + routeGradeLabel + " " + climbDate.toString());

                AuthData authData = mFirebaseRef.getAuth();
                if (authData != null) {
                    Climb newClimb = new Climb(climbDate, routeGradeLabel, gradeSystemType, latitude, longitude);
                    mFirebaseRef.child("users")
                            .child(authData.getUid())
                            .child("climbs")
                            .push().setValue(newClimb);
                }
            }
        }
    }
}