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

The following examples show how to use android.location.Location#convert() . 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: SingleAddressBottomSheet.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
public void showResult(double latitude, double longitude, String addressToShortString, String addressToString) {
  bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
  placeProgressBar.setVisibility(View.GONE);

  if (TextUtils.isEmpty(addressToString)) {
    String longString = Location.convert(longitude, Location.FORMAT_DEGREES);
    String latString  = Location.convert(latitude,  Location.FORMAT_DEGREES);

    placeNameTextView.setText(String.format(Locale.getDefault(), "%s %s", latString, longString));
  } else {
    placeNameTextView.setText(addressToShortString);
    placeAddressTextView.setText(addressToString);
  }
}
 
Example 2
Source File: AppUtils.java    From Beauty-Compass with Apache License 2.0 5 votes vote down vote up
public static String convert(double latitude, double longitude) {
    StringBuilder builder = new StringBuilder();

    builder.append("Lat.  ");
    if (latitude < 0) {
        builder.append("S ");
    } else {
        builder.append("N ");
    }

    String latitudeDegrees = Location.convert(Math.abs(latitude), Location.FORMAT_SECONDS);
    String[] latitudeSplit = latitudeDegrees.split(":");
    builder.append(latitudeSplit[0]);
    builder.append("°");
    builder.append(latitudeSplit[1]);
    builder.append("'");
    builder.append(latitudeSplit[2]);
    builder.append("\"");

    builder.append("\n");

    builder.append("Lng. ");
    if (longitude < 0) {
        builder.append("W ");
    } else {
        builder.append("E ");
    }

    String longitudeDegrees = Location.convert(Math.abs(longitude), Location.FORMAT_SECONDS);
    String[] longitudeSplit = longitudeDegrees.split(":");
    builder.append(longitudeSplit[0]);
    builder.append("°");
    builder.append(longitudeSplit[1]);
    builder.append("'");
    builder.append(longitudeSplit[2]);
    builder.append("\"");

    return builder.toString();
}
 
Example 3
Source File: RxExifTool.java    From RxTools-master with Apache License 2.0 5 votes vote down vote up
private static String gpsInfoConvert(double gpsInfo){
    gpsInfo = Math.abs(gpsInfo);
    String dms = Location.convert(gpsInfo, Location.FORMAT_SECONDS);
    String[] splits = dms.split(":");
    String[] secnds = (splits[2]).split("\\.");
    String seconds;
    if (secnds.length == 0) {
        seconds = splits[2];
    } else {
        seconds = secnds[0];
    }
    return  splits[0] + "/1," + splits[1] + "/1," + seconds + "/1";
}
 
Example 4
Source File: HUDFragmentTest.java    From RobotCA with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Tests updating UI elements.
 * @throws Exception
 */
@Test
public void testUpdateUI() throws Exception {

    Log.d(TAG, "testUpdateUI()");

    // Create a random Location to test the GPS display
    Location loc = new Location("TestProvider");
    loc.setLatitude(360.0 * Math.random() - 180.0);
    loc.setLongitude(360.0 * Math.random() - 180.0);

    String strLongitude = Location.convert(loc.getLongitude(), Location.FORMAT_SECONDS);
    String strLatitude = Location.convert(loc.getLatitude(), Location.FORMAT_SECONDS);

    strLongitude = HUDFragment.getLatLongString(strLongitude, false);
    strLatitude = HUDFragment.getLatLongString(strLatitude, true);

    hudFragment.updateUI(100.0, 360.0);

    // Wait for changes to happen
    Thread.sleep(500L);

    // Test the text
    Log.d(TAG, " testing speed text...");
    onView(withId(R.id.hud_speed)).check(matches(withText(
            String.format(controlAppRule.getActivity().getString(R.string.speed_string), TEST_SPEED))));
}
 
Example 5
Source File: PhysicalDataFormatter.java    From GPSLogger with GNU General Public License v3.0 5 votes vote down vote up
public PhysicalData format(double Number, byte Format) {
    PhysicalData _PhysicalData = new PhysicalData();
    _PhysicalData.Value = "";
    _PhysicalData.UM = "";
    
    if (Number == NOT_AVAILABLE) return(_PhysicalData);     // Returns empty fields if the data is not available
    
    switch (Format) {
        case FORMAT_LATITUDE:   // Latitude
            _PhysicalData.Value = gpsApplication.getPrefShowDecimalCoordinates() ? 
                String.format("%.9f", Math.abs(Number)) : Location.convert(Math.abs(Number), Location.FORMAT_SECONDS);
            _PhysicalData.UM = Number >= 0 ? gpsApplication.getString(R.string.north) : gpsApplication.getString(R.string.south);
            return(_PhysicalData);
            
        case FORMAT_LONGITUDE:  // Longitude
            _PhysicalData.Value = gpsApplication.getPrefShowDecimalCoordinates() ?
                String.format("%.9f", Math.abs(Number)) : Location.convert(Math.abs(Number), Location.FORMAT_SECONDS);
            _PhysicalData.UM = Number >= 0 ?
                gpsApplication.getString(R.string.east) : gpsApplication.getString(R.string.west);
            return(_PhysicalData);
            
        case FORMAT_ALTITUDE:   // Altitude
            switch (gpsApplication.getPrefUM()) {
                case UM_METRIC_KMH:
                case UM_METRIC_MS:
                    _PhysicalData.Value = String.valueOf(Math.round(Number));
                    _PhysicalData.UM = gpsApplication.getString(R.string.UM_m);
                    return(_PhysicalData);
                case UM_IMPERIAL_MPH:
                case UM_IMPERIAL_FPS:
                case UM_NAUTICAL_KN:
                case UM_NAUTICAL_MPH:
                    _PhysicalData.Value = String.valueOf(Math.round(Number * M_TO_FT));
                    _PhysicalData.UM = gpsApplication.getString(R.string.UM_ft);
                    return(_PhysicalData);
            }
        }
    return(_PhysicalData);
}
 
Example 6
Source File: LocAlarmService.java    From ownmdm with GNU General Public License v2.0 5 votes vote down vote up
/**
 * getGoogleLocation
 */
private String getGoogleLocation() {
	Util.location = "Error";
	try {
		
		getNewLocation();

		Thread.sleep(12000); // esperar

        Double d1 = Util.locationReal.getLatitude();
        Double d2 = Util.locationReal.getLongitude();
        
        String latitude = Location.convert(d1,Location.FORMAT_DEGREES);	
        String longitude = Location.convert(d2,Location.FORMAT_DEGREES);
        latitude = latitude.replace(",", ".");
        longitude = longitude.replace(",", ".");
        Util.location = "http://maps.google.com/maps?q=" + latitude + "," + longitude;
        Util.logDebug("location: " + Util.location);
		
        Time t = new Time();
        t.setToNow();
        Util.lastLocation = t.toMillis(false);
        		
        
	} catch(Exception e) {
		Util.logDebug("Exception (getLocation): " + e.getMessage());
	}
       return Util.location;
}
 
Example 7
Source File: LocAlarmService.java    From ownmdm with GNU General Public License v2.0 5 votes vote down vote up
/**
 * llamada desde BootReceiver
 */
public void location_exit_boot() {
	Util.logDebug("location_exit method");
	Util.locationReal = null;
	
	try {
		    LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
		    Util.locationReal = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); // lo inicializo
			Util.locationReal.setLatitude(Double.parseDouble(Util.location_exit_latitude));
			Util.locationReal.setLongitude(Double.parseDouble(Util.location_exit_longitude));
			
      Double d1 = Util.locationReal.getLatitude();
      Double d2 = Util.locationReal.getLongitude();
      String latitude = Location.convert(d1,Location.FORMAT_DEGREES);	
      String longitude = Location.convert(d2,Location.FORMAT_DEGREES);
      latitude = latitude.replace(",", ".");
      longitude = longitude.replace(",", ".");
			
			Util.logDebug("setting location_exit at: " + Util.location_exit_param + " from: maps.google.com/maps?q=" + latitude + "," + longitude);
			log(getApplicationContext(), "setting location_exit at: " + Util.location_exit_param + " from: maps.google.com/maps?q=" + latitude + "," + longitude);

	        float radious = Float.parseFloat(Util.location_exit_param);

	        Intent i = new Intent(getApplicationContext(), LocAlarmService.class);
	        i.setAction(Util.INTENT_ACTION_LOCATION_EXIT);
	        
	        PendingIntent pi = PendingIntent.getService(getApplicationContext(), 5021, i, PendingIntent.FLAG_UPDATE_CURRENT);
	        lm.addProximityAlert(Util.locationReal.getLatitude(), Util.locationReal.getLongitude(), radious, -1, pi);
	        Util.logDebug("location exit set");
	} catch (Exception e) {
		Util.logDebug("Exception location_exit: " + e.getMessage());
	}
	
}
 
Example 8
Source File: Helperfunctions.java    From open-rmbt with Apache License 2.0 5 votes vote down vote up
public static String convertLocation(final Resources res, final double coordinate, final boolean latitude)
{
    final String rawStr = Location.convert(coordinate, Location.FORMAT_MINUTES);
    //[+-]DDD:MM.MMMMM - FORMAT_MINUTES
    final String[] split = rawStr.split(":");
    final String direction;
    float min = 0f;
   
    
    try
    {
        split[1] = split[1].replace(",",".");
        min = Float.parseFloat(split[1]);
    }
    catch (NumberFormatException e)
    {
    }
    
    if (latitude)
    {
        if (coordinate >= 0)
            direction = res.getString(R.string.test_location_dir_n);
        else
            direction = res.getString(R.string.test_location_dir_s);
    }
    else if (coordinate >= 0)
        direction = res.getString(R.string.test_location_dir_e);
    else
        direction = res.getString(R.string.test_location_dir_w);
    return String.format("%s %s°%.3f'", direction, split[0].replace("-", ""), min);
}
 
Example 9
Source File: LocationUtil.java    From android_maplib with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static void writeLocationToExif(
        File imgFile,
        Location location)
        throws IOException
{
    if (location == null) {
        return;
    }

    ExifInterface exif = new ExifInterface(imgFile.getCanonicalPath());

    double lat = location.getLatitude();
    double absLat = Math.abs(lat);
    String dms = Location.convert(absLat, Location.FORMAT_SECONDS);
    String[] splits = dms.split(":");
    String[] secondsArr = (splits[2]).split("\\.");
    String seconds;

    if (secondsArr.length == 0) {
        seconds = splits[2];
    } else {
        seconds = secondsArr[0];
    }

    String latitudeStr = splits[0] + "/1," + splits[1] + "/1," + seconds + "/1";
    exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, latitudeStr);
    exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, lat > 0 ? "N" : "S");

    double lon = location.getLongitude();
    double absLon = Math.abs(lon);
    dms = Location.convert(absLon, Location.FORMAT_SECONDS);
    splits = dms.split(":");
    secondsArr = (splits[2]).split("\\.");

    if (secondsArr.length == 0) {
        seconds = splits[2];
    } else {
        seconds = secondsArr[0];
    }

    String longitudeStr = splits[0] + "/1," + splits[1] + "/1," + seconds + "/1";
    exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, longitudeStr);
    exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, lon > 0 ? "E" : "W");

    exif.saveAttributes();
}
 
Example 10
Source File: GPSTesterActivityController.java    From android-gps-test-tool with Apache License 2.0 4 votes vote down vote up
private static void writeResultToTable(
			Location location,
			LocationManager locationManager,
			String elapsedTimeGPSProvider,
			Boolean isNetworkAvailable){
		
    	_gpsLatitude = location.getLatitude();
    	_gpsLongitude = location.getLongitude();
    	_gpsAccuracy = location.getAccuracy();  
    	final double speed = location.getSpeed();
    	final double altitude = location.getAltitude();

    	String bestAvailableText = "";
    	
		boolean networkProviderEnabled = false; 	
		boolean gpsProviderEnabled = false;
		
		try{
			networkProviderEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
			gpsProviderEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
		}
		catch(Exception exc){
			Log.d("GPSTester","WriteResultToTable(): " + exc.getMessage());
		}

    	if(_networkAccuracy > _gpsAccuracy && _gpsAccuracy > 0.0 && gpsProviderEnabled == true){
    		_bestAvailableType = BestAvailableType.GPS;
    		bestAvailableText = "<b><font color='yellow'>Best Accuracy</font> = <font color='red'>GPS</b></font>" +
    				"<br><b>GPS Accuracy:</b> " + DECIMAL_FORMAT_4.format(_gpsAccuracy) + " meters" +
    				"<br><b>GPS Lat/Lon:</b> " + _gpsLatitude + ", " + _gpsLongitude;
    	}  	
    	else if(_gpsAccuracy > _networkAccuracy && _networkAccuracy > 0.0 && networkProviderEnabled == true){
    		_bestAvailableType = BestAvailableType.NETWORK;	    		
    		bestAvailableText = "<b><font color='yellow'><b><font color='yellow'>Best Accuracy</font> = <font color='red'>Network</b></font></b></font>" +
    				"<br><b>Network Accuracy:<b/> " + DECIMAL_FORMAT_4.format(_networkAccuracy) + " meters" +
    				"<br><b>Network Lat/Lon:<b/> " + _networkLatitude + ", " + _networkLongitude;
    	}
    	else if(_gpsAccuracy == 0.0 && _networkAccuracy > 0.0 && networkProviderEnabled == true){
    		_bestAvailableType = BestAvailableType.NETWORK;	    		
    		bestAvailableText = "<b><font color='yellow'><b><font color='yellow'>Best Accuracy</font> = <font color='red'>Network</b></font></b></font>" +
    				"<br><b>Network Accuracy:<b/> " + DECIMAL_FORMAT_4.format(_networkAccuracy) + " meters" +
    				"<br><b>Network Lat/Lon:<b/> " + _networkLatitude + ", " + _networkLongitude;    		
    	}
    	else if(_networkAccuracy == 0.0 && _gpsAccuracy > 0.0 && gpsProviderEnabled == true){
    		_bestAvailableType = BestAvailableType.GPS;
    		bestAvailableText = "<b><font color='yellow'>Best Accuracy</font> = <font color='red'>GPS</b></font>" +
    				"<br><b>GPS Accuracy:</b> " + DECIMAL_FORMAT_4.format(_gpsAccuracy) + " meters" +
    				"<br><b>GPS Lat/Lon:</b> " + _gpsLatitude + ", " + _gpsLongitude;    		
    	}
    	else{
    		_bestAvailableType = BestAvailableType.NULL;
    		bestAvailableText = "<b><font color='yellow'>Best Accuracy = N/A</b></font>" + 
    				"<br><b>Lat/Lon:</b> N/A" +  
    				"<br><b>Accuracy:</b> N/A";	    		
    	}
    	
	  	setBestAvailableImageView(_bestAvailableType);
		
		String elapsedTimeSinceLastGPS = _elapsedTimer.calculateTimeDifference(_initialGPSTime, _elapsedTimer.getElapsedtime());			  	
    	_initialGPSTime = _elapsedTimer.getElapsedtime();		
    	
	  	final String gpsLocationText = "<b><font color='yellow'>GPS Provider</b></font>" +
    		  	"<br><b>Timestamp:</b> " + _elapsedTimer.convertMillisToMDYHMSS(location.getTime()) +
				"<br><b>1st update elapsed time:</b> " + elapsedTimeGPSProvider +
			  	"<br><b>Since last update:</b> " + elapsedTimeSinceLastGPS +
		  		"<br><b>Lat/Lon:</b> " + _gpsLatitude + ", " + _gpsLongitude +
		  		"<br><b>DMSS:</b> " + 
		  			Location.convert(_gpsLatitude, Location.FORMAT_SECONDS) + ", " +					  			
		  			Location.convert(_gpsLongitude, Location.FORMAT_SECONDS) +
		  		"<br><b>Accuracy:</b> " + DECIMAL_FORMAT_4.format(_gpsAccuracy) + " meters" +
		  		"<br><b>Speed:</b> " + DECIMAL_FORMAT.format((speed * 2.2369)) + " mph" + ", " +
		  		DECIMAL_FORMAT.format(((speed * 3600)/1000)) + " km/h" +
		  		"<br><b>Altitude:</b> " + DECIMAL_FORMAT.format(altitude) + " m, " +
		  		DECIMAL_FORMAT.format(altitude * 3.2808) + " ft" +
		  		"<br><b>Bearing:</b> " + location.getBearing() + " deg";				  	
			  	
    	
	  	_gpsLocationTextView.setText(Html.fromHtml(gpsLocationText));	  	
    	_bestAvailableInfoTextView.setText(Html.fromHtml(bestAvailableText));
    	    	
    	//If true then we can draw on the map. Offline maps not available in this version
    	if(isNetworkAvailable == true){
			final int redMapGraphicSize = Integer.valueOf(_preferences.getString("pref_key_gpsGraphicSize", "10"));    	
	    	
	    	// Called when a new location is found by the network location provider.
	    	if(_preferences.getBoolean("pref_key_centerOnGPSCoords", true) == true){
	    		_map.centerAt(_gpsLatitude, _gpsLongitude, true);
	    	}
	    	if(_preferences.getBoolean("pref_key_accumulateMapPoints", true) == false){
//	    		_map.clearPointsGraphicLayer();
	    		_graphicsLayer.removeAll();
	    	}
	    	
	    	addGraphicLatLon(_gpsLatitude, _gpsLongitude, null, SimpleMarkerSymbol.STYLE.CIRCLE,Color.RED,redMapGraphicSize,_graphicsLayer,_map);
    	}
	}
 
Example 11
Source File: StringUtils.java    From mytracks with Apache License 2.0 2 votes vote down vote up
/**
 * Formats a coordinate
 * 
 * @param coordinate the coordinate
 */
public static String formatCoordinate(double coordinate) {
  return Location.convert(coordinate, Location.FORMAT_DEGREES) + COORDINATE_DEGREE;
}