I'm trying to create a method that given a latitude and longitude and range (in miles or km) returns the NE and SW corners of a bounding box?
I had a function that I found somewhere but after some testing it doesn't seem to work( see below):
double latrange=range/69.172;
double longrange=Math.abs(range/(Math.cos(inLat) *69.172));
double minlat=inLat-latrange;
double maxlat=inLat+latrange;
double minlon=inLong-longrange;
double maxlon=inLong+longrange;
MapCoord min = new MapCoord(minlat,minlon);
MapCoord max = new MapCoord(maxlat,maxlon);
MapCoord [] rs = new MapCoord[2];
rs[0] = min;
rs[1] = max;
return rs;
Not clear what you mean by "doesn't work" but from what I can see the code does result in two points SW and NE of the input. It will however break close to the poles and the international dateline.
Simple test program that produces reasonable looking output:
public class LatLonBoundBox {
public static class MapCoord {
final double lat;
final double lon;
public MapCoord(double lat, double lon) {
this.lat=lat;
this.lon=lon;
}
#Override
public String toString() {
return "MapCoord [lat=" + lat + ", lon=" + lon + "]";
}
}
/**
* #param args
*/
public static void main(String[] args) {
double range = 1.0;
double inLat = 51.350801;
double inLong = -0.251850;
double latrange=range/69.172;
double longrange=Math.abs(range/(Math.cos(inLat) *69.172));
double minlat=inLat-latrange;
double maxlat=inLat+latrange;
double minlon=inLong-longrange;
double maxlon=inLong+longrange;
MapCoord min = new MapCoord(minlat,minlon);
MapCoord max = new MapCoord(maxlat,maxlon);
System.out.println(min);
System.out.println(max);
}
}
Related
Is there anyway to round up a double value?
I want result always rounded up.
int offSet = (totalRecords / 10).round();
It's ceil:
Returns the least integer no smaller than this.
int offSet = (totalRecords / 10).ceil();
Here I'm rounding it to the next double or to next 0.5;
Sample: If its 6.6 then rount to 7.0. If its 6.2, then round to 6.5. See code bellow:
String arredonde(String n) {
final List x = n.split('.'); //break in to a list
if (x.length > 1) { //if its 0, then its already a rounded number or integer
int fstNmbr = int.parse(x[0]);
final int lstNmbrs = int.parse(x[1]);
if (lstNmbrs > 5) {
fstNmbr = fstNmbr + 1;
final String finalNumber = fstNmbr.toStringAsFixed(1);
return finalNumber;
} else {
if (lstNmbrs != 0) {
final double finalNumber = fstNmbr + 0.5;
return finalNumber.toStringAsFixed(1);
} else {
return n;
}
}
} else {
return n;
}
}
try with
num.parse((totalRecords / 10).toStringAsFixed(3))
if you want 3 decimal
Now you have something like you want. I choose sup to 5 to round up, you can change if you want
num offSet = (totalRecords / 10);
var eval = offSet.toStringAsFixed(1).split('.');
var res =
int.parse(eval[1]) > 5 ? int.parse(eval[0]) + 1 : int.parse(eval[0]);
print(res);
I have a string hiWorld and
i want to split this string in two parts hi and World by length of first word hi which is of length 2.
This is what i want to do
List<String> list = ("hiWorld").splitFromLength(2);
I'd use the solution you published shortening up the definition:
List<String> splitStringByLength(String str, int length) =>
[str.substring(0, length), str.substring(length)];
or using an extension method to call the function:
extension on String {
List<String> splitByLength(int length) =>
[substring(0, length), substring(length)];
}
'helloWorld'.splitByLength(5); // Returns [hello, World].
My current solution
List<String> splitStringByLength( String str, int length)
{
List<String> data = [];
data.add( str.substring(0, length) );
data.add( str.substring( length) );
return data;
}
This is my solution which is more generic:
List<String> splitByLength(String value, int length) {
List<String> pieces = [];
for (int i = 0; i < value.length; i += length) {
int offset = i + length;
pieces.add(value.substring(i, offset >= value.length ? value.length : offset));
}
return pieces;
}
And the extension method:
extension on String {
List<String> splitByLength(int length, {bool ignoreEmpty = false}) {
List<String> pieces = [];
for (int i = 0; i < this.length; i += length) {
int offset = i + length;
String piece = this.substring(i, offset >= this.length ? this.length : offset);
if (ignoreEmpty) {
piece = piece.replaceAll(RegExp(r'\s+'), '');
}
pieces.add(piece);
}
return pieces;
}
}
You can use it like:
'HELLO WORLD'.splitByLength(5, ignoreEmpty: true)
var num1 = 10.12345678
What should i do with num1 to delete digits after two decimal point without rounding its value.
I need output as 10.12
import 'package:flutter/material.dart';
void main() => runApp(MaterialApp(
title: ' Delete digits after two decimal point ',
theme: ThemeData(primarySwatch: Colors.blue),
home: MyHome(),
));
class MyHome extends StatefulWidget {
#override
_MyHomeState createState() => _MyHomeState();
}
class _MyHomeState extends State<MyHome> {
#override
Widget build(BuildContext context) {
var num1 = 10.12345678;
print(num1); // I need output as 10.12
return Container();
}
}
If you want to round the number:
var num1 = 10.12345678;
var num2 = double.parse(num1.toStringAsFixed(2)); // num2 = 10.12
If you do NOT want to round the number:
Create this method:
double getNumber(double input, {int precision = 2}) =>
double.parse('$input'.substring(0, '$input'.indexOf('.') + precision + 1));
Usage:
var input = 113.39999999999999;
var output = getNumber(input, precision: 1); // 113.9
var output = getNumber(input, precision: 2); // 113.99
var output = getNumber(input, precision: 3); // 113.999
You can use intl package (https://pub.dartlang.org/packages/intl#-installing-tab-)
var num1 = 10.12345678;
var f = new NumberFormat("###.0#", "en_US");
print(f.format(num1));
Some answers here did not work (top answer is round, not truncate).
here is a way:
(n * 100).truncateToDouble()/100
if you want round the number use this.
double mod = pow(10.0, places);
return ((val * mod).round().toDouble() / mod);
if you just want to truncate use this.
return val - val % 0.01;
String toFixed2DecimalPlaces(double data, {int decimalPlaces = 2}) {
List<String> values = data.toString().split('.');
if (values.length == 2 && values[0] != '0' && values[1].length >= decimalPlaces && decimalPlaces > 0)
return values[0] + '.' + values[1].substring(0, decimalPlaces);
else
return data.toString();
}
You can also try this ----> (0.2055).toStringAsFixed(2)
var per = 0.2055;
Text( "result view -> ${double.parse((per * 100).toStringAsFixed(2))}%",
style: TextStyle(color: Colors.white, fontSize: 10)),
result value ->
input -> 0.2055
output -> result view ->20.00
There is a simple solution to this problem.
double value = 17.56565656;
//as string
String formatted = value.toStringAsFixed(2); // 17.56
//as double
double formattedDouble = double.parse(formatted); //17.56
extension NoRoundingDecimal on double {
String toDecimalAsFixed(int toDecimal) {
var right;
try {
right = this.toString().split(".")[1].padRight(toDecimal, "0").substring(0, toDecimal);
} catch (e) {
right = "00";
}
var left = this.toString().split(".")[0];
double number = double.parse(left + "." + right);
return number.toStringAsFixed(toDecimal);
}
}
Example1:
double price = 71.999999999;
print("number: ${price.toDecimalAsFixed(3)}");
Result: number: 71.999
Example2:
double price = 71;
print("number: ${price.toDecimalAsFixed(3)}");
Result: number: 71.000
how can i use delimiter " : " to receive a string from (system.in ) E.g Ben : 50. Jessica : 30 and so on , and then print as Ben, 50 using my own System.out.print (name + "," + score); I was able to print out the string as string but its not printing out the integer as integer. I need to calculate the average of all the score and that is why i need integer to remain integer so the average method can work Here is my code . Here is my code so far. Please help !!!
-------------------------------------------------------------------------
import java.util.Scanner;
public class StudentScore{
public static void main(String [] args){
Scanner input = new Scanner(System.in);
input.useDelimiter(":");
System.out.print("Please enter your name and score in format: Ben : 50" );
String name = input.next();
int score = input.nextInt();
while(input.hasNext() || input.hasNextInt());{
System.out.println(name + ", " + score);
}
input.close();
}
}
this keeps creeating a new scanner and no print out.
After researching and asking several people , i found out the String class actually has a function that takes in string and then splits it into several primitive values" long", " int" and so on. You need to convert your input into an array, make sure it is spitted by a delimiter of choice .e.g "," or ":" in my own case. Then the array will be your parameter for the .split method from the String class. I posted my complete program below. The programs takes in three names and score and outputs the grade letter and then tells the best score among the three students.
import java.util.Scanner;
public class ThreeNamesAndScore {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Please enter your name and score in this format, Name : Score");
String input1 = input.nextLine();
String[] userData1 = input1.split(":");
String firstStudentName = userData1[0];
String firstStudentStrScore = userData1[1];
int firstStudentScore = Integer.parseInt(firstStudentStrScore);
System.out.print("Please enter your name and score in this format, Name : Score");
String input2 = input.nextLine();
String[] userData2 = input2.split(":");
String secondStudentName = userData2[0];
String secondStudentStrScore = userData2[1];
int secondStudentScore = Integer.parseInt(secondStudentStrScore);
System.out.print("Please enter your name and score in this format, Name : Score");
String input3 = input.nextLine();
String[] userData3 = input3.split(":");
String thirdStudentName = userData3[0];
String thirdStudentStrScore = userData3[1];
int thirdStudentScore = Integer.parseInt(thirdStudentStrScore);
System.out.println("The following is the fianl result ");
System.out.println(firstStudentName + ", " + getGradeLetter(firstStudentScore));
System.out.println(secondStudentName + ", " + getGradeLetter(secondStudentScore));
System.out.println(thirdStudentName + ", " + getGradeLetter(thirdStudentScore));
System.out.println("The best score is from " + bestScore(input1, input2, input3));
input.close();
}
public static String getGradeLetter(int score) {
if (score >= 90) {
return "A";
} else if (score >= 80) {
return "B";
} else if (score >= 70) {
return "C";
} else if (score >= 60) {
return "D";
} else
return "F";
}
public static String bestScore(String a, String b, String c) {
String bestStudent;
String[] userInputs = { a, b, c };
String[] user1 = a.split(":");
String aStrScore = user1[1];
int aScore = Integer.parseInt(aStrScore);
String[] user2 = b.split(":");
String bStrScore = user2[1];
int bScore = Integer.parseInt(bStrScore);
String[] user3 = c.split(":");
String cStrScore = user3[1];
int cScore = Integer.parseInt(cStrScore);
if ((aScore > bScore) && (aScore > cScore))
bestStudent = a;
else if ((bScore > aScore) && (bScore > cScore))
bestStudent = b;
else
bestStudent = c;
return bestStudent;
}
}
I have a NSManagedObject derived class (entity) whose instances are persisted in a local SQL-lite storage. The class has also longitude and latitude properties and I need to fetch the entities based on the distance from specific coordinates. I tried to used NSPredicate with custom functions, but I couldn't find documentation on how to implement the function (... if it does support that). Has anyone an idea on how to perform that kind of dynamic filtering on Core Data entities ? I tried with NSPredicate withBlock, but it doesn't work on objects persisted on SQL-Lite databases. Please help.
You can't do that with Core Data. You could use a Transient property to model the distance from your dynamic location, after the entities have been fetched, and even order the items based on that Transient property. But you can only fetch properties from the persistent store if they are persistent properties.
In practice, I've found it's very fast to query points in a rectangular window, if the coordinates are indexed. Build the window by taking the dynamic position's latitude/longitude, plus/minus the search radius, throwing in a cosine(latitude) adjustment for the longitude window if it's unprojected data (pure lat/lon, not UTM or similar grid).
If that's really not fast enough, you could store a geohash on your entities, which gives you a string you can do a prefix search on. See https://en.wikipedia.org/wiki/Geohash for a discussion. Or you could implement a true spatial index. But I've never had a Core Data performance problem that made it worth implementing either of those approaches.
I store my locations in the data model as latitude/longitude coordinates. Then I wrote some helper extensions to find a semirectangular region of lat/lon coordinates and query by that. This greatly limits the result set, so if you need to sort by location you can sort the resulting objects using the CLLocation distance calculator.
I create a CLCircularRegion and you can see my buildPredicate() function that creates the query.
Here's the code I'm using:
Swift 3
extension CLLocationDegrees {
static var north: CLLocationDegrees {
return 90.0
}
static var south: CLLocationDegrees {
return -90.0
}
static var east: CLLocationDegrees {
return 180.0
}
static var west: CLLocationDegrees {
return -180.0
}
var radians: Double {
return Double.pi * self / 180.0
}
}
extension CLLocationCoordinate2D {
var metersPerDegreeLatitude: CLLocationDistance {
return 111319.4907932736
}
var metersPerDegreeLongitude: CLLocationDistance {
return max(0.0, cos(self.latitude.radians) * self.metersPerDegreeLatitude)
}
}
extension CLCircularRegion {
var northernmostLatitude: CLLocationDegrees {
let longitude = self.center.latitude + self.radius / self.center.metersPerDegreeLatitude
return min(longitude, .north)
}
var southernmostLatitude: CLLocationDegrees {
let longitude = self.center.latitude - self.radius / self.center.metersPerDegreeLatitude
return max(longitude, .south)
}
var easternmostLongitude: CLLocationDegrees {
guard self.northernmostLatitude <= .north else {
return .east
}
guard self.southernmostLatitude >= .south else {
return .east
}
return min(.east, self.center.longitude + self.radius / (self.center.metersPerDegreeLongitude + 0.0001))
}
var westernmostLongitude: CLLocationDegrees {
guard self.northernmostLatitude <= .north else {
return .west
}
guard self.southernmostLatitude >= .south else {
return .west
}
return max(.west, self.center.longitude - self.radius / (self.center.metersPerDegreeLongitude + 0.0001))
}
func buildPredicate(latitudeName: String = "latitude", longitudeName: String = "longitude") -> NSPredicate {
let args = [self.southernmostLatitude, self.northernmostLatitude, self.westernmostLongitude, self.easternmostLongitude]
return NSPredicate(format: "\(latitudeName) >= %# && \(latitudeName) <= %# && \(longitudeName) >= %# && \(longitudeName) <= %#", argumentArray: args)
}
}
Here is the answer https://www.objc.io/issues/4-core-data/core-data-fetch-requests/
static double const D = 80. * 1.1;
double const R = 6371009.; // Earth readius in meters
double meanLatitidue = pointOfInterest.latitude * M_PI / 180.;
double deltaLatitude = D / R * 180. / M_PI;
double deltaLongitude = D / (R * cos(meanLatitidue)) * 180. / M_PI;
double minLatitude = pointOfInterest.latitude - deltaLatitude;
double maxLatitude = pointOfInterest.latitude + deltaLatitude;
double minLongitude = pointOfInterest.longitude - deltaLongitude;
double maxLongitude = pointOfInterest.longitude + deltaLongitude;
request.result = [NSPredicate predicateWithFormat:
#"(%# <= longitude) AND (longitude <= %#)"
#"AND (%# <= latitude) AND (latitude <= %#)",
#(minLongitude), #(maxLongitude), #(minLatitude), #(maxLatitude)];
Here's the Swift version of above answer
let D: Double = 80 * 1.1
let R: Double = 6371009
let meanLatitidue = pointOfInterest.coordinate.latitude * .pi / 180
let deltaLatitude = D / R * 180 / .pi
let deltaLongitude = D / (R * cos(meanLatitidue)) * 180 / .pi
let minLatitude: Double = pointOfInterest.coordinate.latitude - deltaLatitude
let maxLatitude: Double = pointOfInterest.coordinate.latitude + deltaLatitude
let minLongitude: Double = pointOfInterest.coordinate.longitude - deltaLongitude
let maxLongitude: Double = pointOfInterest.coordinate.longitude + deltaLongitude
let predicate = NSPredicate(format: "(%lf <= longitude) AND (longitude <= %lf) AND (%lf <= latitude) AND (latitude <= %lf)", minLongitude, maxLongitude,minLatitude, maxLatitude)