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

The following examples show how to use android.location.Location#getLongitude() . 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: MyLocation.java    From DongWeather with Apache License 2.0 6 votes vote down vote up
private void updateWithNewLocation(Location location){
        if (location != null) {
            latitude = location.getLatitude(); // 经度
            longitude = location.getLongitude(); // 纬度
            //double altitude = location.getAltitude(); // 海拔
            Log.v(TAG, "latitude " + latitude + "  longitude:" + longitude);
            String tempString1 = String.valueOf(latitude);
            String tempString2 = String.valueOf(longitude);
//        returnData = tempString1.substring(0,tempString1.indexOf('.') + 4)
//        + "," + tempString2.substring(0, tempString2.indexOf('.') + 4);
            returnData = tempString2.substring(0,tempString2.indexOf('.') + 4)
                    + "," + tempString1.substring(0, tempString1.indexOf('.') + 4);
            Log.d(TAG, "retrunData :" + returnData);
        }else{
            Log.v(TAG, "don't know location info");
            //Toast.makeText(, "无法获取位置信息", Toast.LENGTH_SHORT).show();
        }

    }
 
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: WhereAmIActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
@Override
public void onLocationResult(LocationResult locationResult) {
  Location location = locationResult.getLastLocation();
  if (location != null) {
    updateTextView(location);
  }

  if (location != null) {
    updateTextView(location);
    if (mMap != null) {
      LatLng latLng = new LatLng(location.getLatitude(),
        location.getLongitude());
      mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
    }
  }
}
 
Example 4
Source File: MapUtils.java    From android with MIT License 5 votes vote down vote up
private static LatLngZoom getInitialCenterCoordinates(MapView mapView, Bundle extras) throws UnsupportedAreaException {
    // First, start by checking bundle coordinates (from Intent or savedInstance)
    if (extras != null) {
        final LatLngZoom latLngZoom = getBundleGeoPoint(extras);
        if (latLngZoom != null) {
            return latLngZoom;
        }
    }

    // Second, does user have an active checkin
    final CheckinData checkin = PrkngPrefs.getInstance(mapView.getContext())
            .getCheckinData();
    if (checkin != null) {
        return new LatLngZoom(checkin.getLatLng(),
                Const.UiConfig.CHECKIN_ZOOM);
    }

    // Third, user's current location
    if (mapView.isMyLocationEnabled()) {
        final Location myLocation = mapView.getMyLocation();
        if (CityBoundsHelper.isValidLocation(mapView.getContext(), myLocation)) {
            return new LatLngZoom(myLocation.getLatitude(),
                    myLocation.getLongitude(),
                    Const.UiConfig.MY_LOCATION_ZOOM);
        } else {
            throw new UnsupportedAreaException();
        }
    }

    // TODO handle selected city

    return null;
}
 
Example 5
Source File: LocationUtils.java    From Forage with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Gets the magnetic declination at the specified location.
 *
 * @param location Current location.
 * @return The declination of the horizontal component of the magnetic
 * field from true north, in degrees (i.e. positive means the
 * magnetic field is rotated east that much from true north).
 */
public static double getMagneticDeclination(@NonNull Location location) {
    GeomagneticField geoField = new GeomagneticField(
            (float) location.getLatitude(),
            (float) location.getLongitude(),
            (float) location.getAltitude(),
            System.currentTimeMillis()
    );

    return geoField.getDeclination();
}
 
Example 6
Source File: MapsActivity.java    From Self-Driving-Car with MIT License 5 votes vote down vote up
@Override
    public void onLocationChanged(Location location) {


        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        Data data = new Data();
        data.setCurrentLocation(latLng);
        Log.e("Location", String.valueOf(location.getAccuracy()));
        data.setAltitude(location.getAltitude());

        //Place current location marker
        if (toSetMarker) {

            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            markerOptions.title("Current Position");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE));
            mCurrLocationMarker = mMap.addMarker(markerOptions);
            markerPoints.add(latLng);


            //move map camera
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(18));
        }
        toSetMarker = false;


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

    }
 
Example 7
Source File: LocationService.java    From FineGeotag with GNU General Public License v3.0 5 votes vote down vote up
private static double getEGM96Offset(Location location, Context context) throws IOException {
    InputStream is = null;
    try {
        double lat = location.getLatitude();
        double lon = location.getLongitude();

        int y = (int) Math.floor((90 - lat) * 4);
        int x = (int) Math.floor((lon >= 0 ? lon : lon + 360) * 4);
        int p = ((y * 1440) + x) * 2;
        int o;

        if (mEGM96Pointer >= 0 && p == mEGM96Pointer)
            o = mEGM96Offset;
        else {
            is = context.getAssets().open("WW15MGH.DAC");
            is.skip(p);

            ByteBuffer bb = ByteBuffer.allocate(2);
            bb.order(ByteOrder.BIG_ENDIAN);
            bb.put((byte) is.read());
            bb.put((byte) is.read());
            o = bb.getShort(0);

            mEGM96Pointer = p;
            mEGM96Offset = o;
        }

        return o / 100d;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ignored) {
            }
        }
    }
}
 
Example 8
Source File: SimpleLocation.java    From Android-SimpleLocation with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the current position as a Point instance
 *
 * @return the current location (if any) or `null`
 */
public Point getPosition() {
	if (mPosition == null) {
		return null;
	}
	else {
		Location position = blurWithRadius(mPosition);
		return new Point(position.getLatitude(), position.getLongitude());
	}
}
 
Example 9
Source File: RouteFragment.java    From open with GNU General Public License v3.0 5 votes vote down vote up
private String formatInstructionForDescription(Instruction instruction) {
    Location loc = instruction.getLocation();
    String locationName = instruction.getSimpleInstruction(getActivity())
            .replace(instruction.getHumanTurnInstruction(getActivity()), "");
    String latLong = " [" + loc.getLatitude() + ", " + loc.getLongitude() + ']';
    String startLocationString = locationName + latLong;
    return startLocationString;
}
 
Example 10
Source File: LocationUtils.java    From mytracks with Apache License 2.0 5 votes vote down vote up
/**
 * Computes the distance on the two sphere between the point c0 and the line
 * segment c1 to c2.
 * 
 * @param c0 the first coordinate
 * @param c1 the beginning of the line segment
 * @param c2 the end of the lone segment
 * @return the distance in m (assuming spherical earth)
 */
private static double distance(final Location c0, final Location c1, final Location c2) {
  if (c1.equals(c2)) {
    return c2.distanceTo(c0);
  }

  final double s0lat = c0.getLatitude() * UnitConversions.DEG_TO_RAD;
  final double s0lng = c0.getLongitude() * UnitConversions.DEG_TO_RAD;
  final double s1lat = c1.getLatitude() * UnitConversions.DEG_TO_RAD;
  final double s1lng = c1.getLongitude() * UnitConversions.DEG_TO_RAD;
  final double s2lat = c2.getLatitude() * UnitConversions.DEG_TO_RAD;
  final double s2lng = c2.getLongitude() * UnitConversions.DEG_TO_RAD;

  double s2s1lat = s2lat - s1lat;
  double s2s1lng = s2lng - s1lng;
  final double u = ((s0lat - s1lat) * s2s1lat + (s0lng - s1lng) * s2s1lng)
      / (s2s1lat * s2s1lat + s2s1lng * s2s1lng);
  if (u <= 0) {
    return c0.distanceTo(c1);
  }
  if (u >= 1) {
    return c0.distanceTo(c2);
  }
  Location sa = new Location("");
  sa.setLatitude(c0.getLatitude() - c1.getLatitude());
  sa.setLongitude(c0.getLongitude() - c1.getLongitude());
  Location sb = new Location("");
  sb.setLatitude(u * (c2.getLatitude() - c1.getLatitude()));
  sb.setLongitude(u * (c2.getLongitude() - c1.getLongitude()));
  return sa.distanceTo(sb);
}
 
Example 11
Source File: MainActivity.java    From solutions-mobile-shopping-assistant-android-client with Apache License 2.0 4 votes vote down vote up
/**
 * Retrieves the list of nearby places through appropriate CloudEndpoint.
 *
 * @param params the current geolocation for which to retrieve the list of nearby places.
 * @return the collection of retrieved nearby places.
 */
@Override
protected PlaceInfoCollection doInBackground(Location... params) {
  Location checkInLocation = params[0];

  float longitude;
  float latitude;

  if (checkInLocation == null) {
    // return null;
    // TODO(user): Remove this temporary code and just return null

    longitude = (float) -122.12151;
    latitude = (float) 47.67399;
  } else {
    latitude = (float) checkInLocation.getLatitude();
    longitude = (float) checkInLocation.getLongitude();
  }

  Builder endpointBuilder = new Shoppingassistant.Builder(
      AndroidHttp.newCompatibleTransport(), new JacksonFactory(),
      CloudEndpointBuilderHelper.getRequestInitializer());

  PlaceEndpoint placeEndpoint =
      CloudEndpointBuilderHelper.updateBuilder(endpointBuilder).build().placeEndpoint();

  PlaceInfoCollection result;

  // Retrieve the list of up to 10 places within 50 kms
  try {
    long distanceInKm = 50;
    int count = 10;

    result = placeEndpoint.list(
        count, distanceInKm, Float.toString(latitude), Float.toString(longitude)).execute();
  } catch (IOException e) {
    if (e != null) {
      String message = e.getMessage();
      if (message == null) {
        message = e.toString();
      }
      log.severe("Exception=" + message);
    }
    result = null;
  }
  return result;
}
 
Example 12
Source File: SplashActivity.java    From Beauty-Compass with Apache License 2.0 4 votes vote down vote up
private void updateDayState(Location location) {

        com.arbelkilani.beautycompass.global.solar.Location location1 =
                new com.arbelkilani.beautycompass.global.solar.Location(location.getLatitude(), location.getLongitude());
        SunriseSunsetCalculator sunriseSunsetCalculator = new SunriseSunsetCalculator(location1, Calendar.getInstance().getTimeZone());

        Date sunrise = sunriseSunsetCalculator.getOfficialSunriseCalendarForDate(Calendar.getInstance()).getTime();
        Date sunset = sunriseSunsetCalculator.getOfficialSunsetCalendarForDate(Calendar.getInstance()).getTime();
        Date current = Calendar.getInstance().getTime();

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 12);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.SECOND, 0);

        Date noon = calendar.getTime();


        Calendar calendar1 = Calendar.getInstance();
        calendar1.set(Calendar.HOUR_OF_DAY, 0);
        calendar1.set(Calendar.MINUTE, 0);
        calendar1.set(Calendar.SECOND, 0);

        Date midNight = calendar1.getTime();

        if (current.after(midNight)) {
            mBackground = R.drawable.bg_night;
            mGreetingMessage = R.string.night_greeting;

            if (current.after(sunrise)) {
                mBackground = R.drawable.bg_morning;
                mGreetingMessage = R.string.morning_greeting;


                if (current.after(noon)) {
                    mBackground = R.drawable.bg_evening;
                    mGreetingMessage = R.string.afternoon_greeting;

                    if (current.after(sunset)) {
                        mBackground = R.drawable.bg_night;
                        mGreetingMessage = R.string.night_greeting;

                    }
                }
            }
        }

        navigate();
    }
 
Example 13
Source File: EarthquakeTypeConverters.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
@TypeConverter
public static String locationToString(Location location) {
  return location == null ?
           null : location.getLatitude() + "," + location.getLongitude();
}
 
Example 14
Source File: LocationReceiver.java    From prayer-times-android with Apache License 2.0 4 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    Location location = intent.getParcelableExtra(KEY_LOCATION_CHANGED);
    if (location == null) {
        triggerUpdate(context);
        return;
    }


    sLastLocationUpdate = System.currentTimeMillis();
    final double lat = location.getLatitude();
    final double lng = location.getLongitude();
    final double elv = location.getAltitude();

    Cities.get().search(lat, lng, new Cities.Callback<List<Entry>>() {
        @Override
        public void onResult(List<Entry> result) {
            List<Times> times = Times.getTimes();
            boolean updated = false;
            for (Times t : times) {
                if (t.isAutoLocation()) {
                    for (Entry e : result) {
                        if (t.getSource() == e.getSource()) {
                            if (e.getSource() == Source.Calc) {


                                LocalDate today = LocalDate.now();
                                LocalDateTime[] oldtimes =
                                        {t.getTime(today, Vakit.FAJR.ordinal()),
                                                t.getTime(today, Vakit.SUN.ordinal()),
                                                t.getTime(today, Vakit.DHUHR.ordinal()),
                                                t.getTime(today, Vakit.ASR.ordinal()),
                                                t.getTime(today, Vakit.MAGHRIB.ordinal()),
                                                t.getTime(today, Vakit.ISHAA.ordinal())};
                                ((CalcTimes) t).getPrayTimes().setCoordinates(lat, lng, elv);
                                t.setName(e.getName());
                                for (Vakit v : Vakit.values()) {
                                    if (oldtimes[v.ordinal()].equals(t.getTime(today, v.ordinal()))) {
                                        updated = true;
                                        break;
                                    }
                                }


                            } else {
                                t.setName(e.getName());
                                if (!((WebTimes) t).getId().equals(e.getKey())) {
                                    ((WebTimes) t).setId(e.getKey());
                                    updated = true;
                                    ((WebTimes) t).syncAsync();
                                }
                            }
                        }
                    }
                }
            }
            if (updated) {
                Times.setAlarms();
                InternalBroadcastReceiver.sender(App.get()).sendTimeTick();
            } else {
                LocationManager lm = (LocationManager) App.get().getSystemService(Context.LOCATION_SERVICE);
                lm.removeUpdates(getPendingIntent(App.get()));
            }
        }
    });
}
 
Example 15
Source File: WeatherUpdateWorker.java    From PixelWatchFace with GNU General Public License v3.0 4 votes vote down vote up
private boolean isLocationValid(Location location) {
  return !location.getProvider().isEmpty() && location.getLongitude() != Double.MIN_VALUE
      && location.getLatitude() != Double.MIN_VALUE;
}
 
Example 16
Source File: PeriodicPositionUploaderTask.java    From secureit with MIT License 4 votes vote down vote up
public void onLocationChanged(Location location) {
	lat = location.getLatitude();
	lng = location.getLongitude();
}
 
Example 17
Source File: Position.java    From OpenMapKitAndroid with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public Position(Location location) {
    this.mStorage[LAT_IDX] = location.getLatitude();
    this.mStorage[LON_IDX] = location.getLongitude();
    this.mStorage[ALT_IDX] = location.getAltitude();
}
 
Example 18
Source File: LocationService.java    From odm with GNU General Public License v3.0 4 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
	context = getApplicationContext();
	Logd(TAG, "Location service started.");
	loadVARs(context);
	String message = "";
	if (intent.getStringExtra("message") != null) {
		message = intent.getStringExtra("message");
		Logd(TAG, "Message: " + message);
		if (message.equals("Command:GetLocationGPS"))
			locationType = "gpsonly";
		if (message.equals("Command:GetLocationNetwork"))
			locationType = "networkonly";
	}
	if (intent.getStringExtra("alarm") != null) {
		// To overcome a context reference bug, we need to recheck if it's an alarm.
		if (getVAR("NETWORK_ONLY").equals("true")) {
			locationType = "networkonly";
		} else {
			locationType = "";
		}
	}
	LocationResult locationResult = new LocationResult() {
		@Override
		public void gotLocation(Location location) {
			//Got the location! Send to server
			if (location != null) {
				String notification = "Location: " + location.getLatitude() + " " + location.getLongitude();
				AsyncTask<String, Void, Void> postTask;
				postTask = new AsyncTask<String, Void, Void>() {
					@Override
					protected Void doInBackground(String... params) {
						String notification = params[0];
						Map<String, String> postparams = new HashMap<String, String>();
						loadVARs(getApplicationContext());
						postparams.put("regId", getVAR("REG_ID"));
						postparams.put("username", getVAR("USERNAME"));
						postparams.put("password", getVAR("ENC_KEY"));

						postparams.put("message", notification);
						CommonUtilities.post(getVAR("SERVER_URL") + "message.php", postparams);
						return null;
					}
				};
				postTask.execute(notification, null, null);
			} else {
				Logd(TAG, "No location provided by device.");
			}
			stopLocation();
		}
	};
	GetLocation myLocation = new GetLocation();
	Logd(TAG, "Location type: " + locationType);
	myLocation.getLocation(context, locationResult, locationType);
	return START_STICKY;
}
 
Example 19
Source File: EarthquakeTypeConverters.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 4 votes vote down vote up
@TypeConverter
public static String locationToString(Location location) {
  return location == null ?
           null : location.getLatitude() + "," + location.getLongitude();
}
 
Example 20
Source File: NearbySearchQuery.java    From android-google-places with MIT License 2 votes vote down vote up
/**
 * @param apiKey
 * @param location
 */
public NearbySearchQuery(String apiKey, Location location) {
	this(apiKey, location.getLatitude(), location.getLongitude());
}