I need some help :) I am assign with a project to come out with the distance / speed and time. I have already come out with the Timer. However, the distance is giving me some problem. The distance does not changed at all from I travel from one place to another.
//GPS
private static Double EARTH_RADIUS = 6371.00; // Radius in Kilometers default
private static final String DEBUG_TAG = "GPS";
private String[] location;
private double[] coordinates;
private double[] gpsOrg;
private double[] gpsEnd;
private LocationManager lm;
private LocationListener locationListener;
private double totalDistanceTravel;
private boolean mPreviewRunning;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.waterspill);
/*getWindow().setFormat(PixelFormat.TRANSLUCENT);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);*/
mSurfaceView = (SurfaceView) findViewById(R.id.surface_camera);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
distanceCal=new LocationUtil(EARTH_RADIUS);
totalDistanceTravel=0;
// ---Additional---
//mapView = (MapView) findViewById(R.id.mapview1);
//mc = mapView.getController();
// ----------------
txtTimer = (TextView) findViewById(R.id.Timer);
gpsOnOff = (TextView) findViewById(R.id.gpsOnOff);
disTrav = (TextView) findViewById(R.id.disTrav);
startButton = (Button) findViewById(R.id.startButton);
startButton.setOnClickListener(startButtonClickListener);
stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(stopButtonClickListener);
testButton = (Button) findViewById(R.id.testButton);
testButton.setOnClickListener(testButtonClickListener);
startButton.setEnabled(false);
stopButton.setEnabled(false);
getLocation();
}
public void getLocation()
{
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0,locationListener);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,locationListener);
}
private OnClickListener startButtonClickListener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
gpsOrg=coordinates;
totalDistanceTravel=0;
Toast.makeText(getBaseContext(),
"Start Location locked : Lat: " + gpsOrg[0] +
" Lng: " + gpsOrg[1],
Toast.LENGTH_SHORT).show();
if (!isTimerStarted)
{
startTimer();
isTimerStarted = true;
}
stopButton.setEnabled(true);
}
};
private OnClickListener stopButtonClickListener = new OnClickListener()
{
public void onClick(View v) {
// TODO Auto-generated method stub
gpsEnd=coordinates;
//gpsEnd = new double[2];
//gpsEnd[0]=1.457899;
//gpsEnd[1]=103.828659;
Toast.makeText(getBaseContext(),
"End Location locked : Lat: " + gpsEnd[0] +
" Lng: " + gpsEnd[1],
Toast.LENGTH_SHORT).show();
double d = distFrom(gpsOrg[0],gpsOrg[1],gpsEnd[0],gpsEnd[1]);
totalDistanceTravel+=d;
disTrav.setText(Double.toString(d));
}
};
public static double distFrom(double lat1, double lng1, double lat2, double lng2) {
double earthRadius = EARTH_RADIUS;
double dLat = Math.toRadians(lat2-lat1);
double dLng = Math.toRadians(lng2-lng1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLng/2) * Math.sin(dLng/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = earthRadius * c;
return new Float(dist).floatValue();
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc) {
if(coordinates!=null)
{
double[] coordinatesPrev=coordinates;
double d = distFrom(coordinatesPrev[0],coordinatesPrev[1],coordinates[0],coordinates[1]);
totalDistanceTravel+=d;
}
else
{
coordinates = getGPS();
}
startButton.setEnabled(true);
}
private double[] getGPS() {
List<String> providers = lm.getProviders(true);
double[] gps = new double[2];
//Loop over the array backwards, and if you get an accurate location, then break out the loop
Location l = null;
for (int i=providers.size()-1; i>=0; i--) {
String s = providers.get(i);
Log.d("LocServ",String.format("provider (%d) is %s",i,s));
l = lm.getLastKnownLocation(providers.get(i));
if (l != null) {
gps[0] = l.getLatitude();
gps[1] = l.getLongitude();
Log.d("LocServ",String.format("Lat %f, Long %f accuracy=%f",gps[0],gps[1],l.getAccuracy()));
gpsOnOff.setText("On");
}
}
return gps;
}
Is there anything wrong with my codes. Please advice and Thanks a lot for your help :)
Test your formula with this: The distance between {-73.995008, 40.752842}, and {-73.994905, 40.752798} should be 0.011532248670891638 km.
Related
I am working on an app that collects Accelerometer, magnetometer data every 20 milliseconds and it saves the data to a csv file.
What I want to do is collect precise latitude and longitude too at the time of data collection so that I can create a heat map (eg. of house).
I am not an android expert. So, I don't know much on how to implement this feature. Is it possible to get coordinate data every 20 milliseconds during indoor data collection?
Below is my current work. Please help me with how can I get real time lat, long and save it to my csv file and what changes I should make?
public class MainActivity extends AppCompatActivity implements SensorEventListener
{
private SensorManager sensorManager;
private Sensor magnetic;
private int counter = 1;
private boolean recording = false;
private boolean counterOn = false;
private float magValues[] = new float[3];
private Context context;
private static final int REQUESTCODE_STORAGE_PERMISSION = 1;
Collection<String[]> magneticData = new ArrayList<>();
private CsvWriter csvWriter = null;
public static DecimalFormat DECIMAL_FORMATTER;
TextView stateText;
EditText fileIDEdit;
TextView magText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(listenerStartButton);
findViewById(R.id.button2).setOnClickListener(listenerStopButton);
fileIDEdit = (EditText)findViewById(R.id.editText);
magText = (TextView) findViewById(R.id.textView3);
stateText = (TextView) findViewById(R.id.textView);
stateText.setText("Stand by");
context = this;
// Sensor
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
magnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
symbols.setDecimalSeparator('.');
DECIMAL_FORMATTER = new DecimalFormat("#.000", symbols);
}
private View.OnClickListener listenerStartButton = new View.OnClickListener() {
#Override
public void onClick(View v) {
recording = true;
stateText.setText("Recording started");
stateText.setTextColor(Color.parseColor("#FF0000"));
}
};
private int REQUEST_CODE = 1;
private View.OnClickListener listenerStopButton = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(recording == true)
{
recording = false;
counter = 0;
String value = fileIDEdit.getText().toString();
stateText.setText("Recording Stopped");
stateText.setTextColor(Color.parseColor("#0000FF"));
if (storagePermitted((Activity) context)){
csvWriter = new CsvWriter();
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "magnetic" + value + ".csv");
//File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "magnetic" + value + ".csv");
try {
csvWriter.write(file, StandardCharsets.UTF_8, magneticData);
Toast.makeText(MainActivity.this, "File is recorded in memory.", Toast.LENGTH_LONG).show();
} catch (IOException io) {
Log.d("Error", io.getLocalizedMessage());
}
}
}
else{
Toast.makeText(MainActivity.this, "Nothing to save. Recording was not started.", Toast.LENGTH_LONG).show();
}
}
};
#Override
protected void onResume(){
super.onResume();
sensorManager.registerListener(this, magnetic, SensorManager.SENSOR_DELAY_GAME);
}
#Override
public void onSensorChanged(SensorEvent event) {
long timeInMillisec = (new Date()).getTime() + (event.timestamp - System.nanoTime()) / 1000000L;
if(recording) {
float x = 0;
float y = 0;
float z = 0;
double magnitude = 0;
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
// New Code:
x = event.values[0];
y = event.values[1];
z = event.values[2];
magnitude = Math.sqrt((x * x) + (y + y)
+ (z * z));
//magText.setText("Magnetometer: " + timeInMillisec+" X= " + roundThis(event.values[0]) + " Y= " + roundThis(event.values[1]) + " Z= " + roundThis(event.values[2]));
magText.setText("Magnetometer: X= " + x + " Y= " + y + " Z= " + z + " Magnitude: " + DECIMAL_FORMATTER.format(magnitude) + "\u00b5Tesla");
Log.d("Record", "Magnetometer" + String.valueOf(counter));
magValues = event.values;
}
//magneticData.add(new String[]{String.valueOf(timeInMillisec), String.valueOf(magValues[0]), String.valueOf(magValues[1]), String.valueOf(magValues[2])});
#SuppressLint("SimpleDateFormat") SimpleDateFormat logLineStamp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS", Locale.getDefault());
//logLineStamp.setTimeZone(TimeZone.getTimeZone("UTC"));
magneticData.add(new String[]{logLineStamp.format(new Date(timeInMillisec)), String.valueOf(x), String.valueOf(y), String.valueOf(z), String.valueOf(magnitude)});
counter++;
}
}
// Checks if the the storage permissions are given or not by the user
// It will request the use if not
private static boolean storagePermitted(Activity activity){
// Check read write permission
Boolean readPermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
Boolean writePermission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (readPermission && writePermission){
return true;
}
ActivityCompat.requestPermissions(activity, new String[]{ Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUESTCODE_STORAGE_PERMISSION);
return false;
}
public static float roundThis(float value){
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(4, RoundingMode.HALF_UP);
return bd.floatValue();
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
In sqlite the same method work, but I changed the database to Mysql, this method does not work!
i send arraylist(names) from AsyncTask to show method in MapsActivity
and probleme in ligne
myLocation = mMap.getMyLocation();
and
mMap.addMarker(new MarkerOptions().position(dz).title("welcome to")).showInfoWindow();
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
public void mark(Double latitude, Double longitude) {
LatLng dz = new LatLng(latitude, longitude);
mMap.addMarker(new MarkerOptions().position(dz).title("welcome to")).showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(dz, 16));
}
public float distanceBetween(Double latitude, Double longitude) {
float result[] = new float[10];
Location myLocation = mMap.getMyLocation();
Double mylatitude = myLocation.getLatitude();
Double mylongitude = myLocation.getLongitude();
myLocation.distanceBetween(mylatitude, mylongitude, latitude, longitude, result);
return result[0];
}
public void show ( ArrayList names) {
ArrayList<String> arrList = new ArrayList<>();
arrList = names;
int c = arrList.size();
Float t[] = new Float[10];
Double company[] = new Double[3];
if (c > 0) {
int n = 0;
int i = 0;
while (c > 0) {
Double latitude = Double.valueOf(arrList.get(n));
Double longitude = Double.valueOf(arrList.get(n + 1));
Double price = Double.valueOf(arrList.get(n + 2));
t[i] = distanceBetween(latitude, longitude);
if (n == 0) {
company[0] = latitude;
company[1] = longitude;
company[2] = price;
}
if ((i > 0) && (t[i] < t[i - 1])) {
t[i] = t[i - 1];
company[0] = latitude;
company[1] = longitude;
company[2] = price;
}
i = i + 1;
n = n + 3;
c = c - 3;
}
mark(company[0], company[1]);
} else {
Toast T = Toast.makeText(this, "product is not available ", Toast.LENGTH_SHORT);
T.show();
}
Toast.makeText(this, "price of product = " + company[2], Toast.LENGTH_LONG).show();
}
}
public class Parser2 extends AsyncTask<Void,Void,Integer> {
Context c;
String data;
ArrayList<String> names=new ArrayList<>();
public Parser2(Context c, String data) {
this.c = c;
this.data = data;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Integer doInBackground(Void... params) {
return this.parse();
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
if(integer==1)
{
MapsActivity m =new MapsActivity();
m.show(names);
}else {
Toast.makeText(c,"Unable to Parse2",Toast.LENGTH_SHORT).show();
}
}
private int parse()
{
try
{
JSONArray ja=new JSONArray(data);
JSONObject jo=null;
names.clear();
int i;
for( i=0;i<ja.length();i++)
{
jo=ja.getJSONObject(i);
String latitude=jo.getString("latitude");
String longitude=jo.getString("longitude");
String price=jo.getString("price");
names.add(latitude);
names.add(longitude);
names.add(price);}
return 1;
} catch (JSONException e) {
e.printStackTrace();
}
return 0;
}
}
It seems the reason of the problem is because getMyLocation() is null and the algorithm is expecting it not to be null. Please make sure that this object contains value. You can use this code to check the last location of the user:
LocationManager service = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = service.getBestProvider(criteria, false);
Location location = service.getLastKnownLocation(provider);
LatLng userLocation = new LatLng(location.getLatitude(),location.getLongitude());
Hope this information find you helpful and good luck on your project!
This question already has answers here:
The application may be doing too much work on its main thread
(21 answers)
Closed 1 year ago.
As I am new to android I couldn't fix this skipped 1000+ frames issue.Help me to sort out this and help me to add loading progress bar while this skipping frames action takes place before opening map. This is my map code.
RouteMap.java
public class RouteMap extends android.support.v4.app.FragmentActivity
implements OnClickListener, OnInfoWindowClickListener,
DirecitonReceivedListener, OnMapReadyCallback {
public List<String> destinations;
ImageView img_home, img_menu;
private GoogleMap mMap;
ProgressDialog prgDialog;
model modelData;
private Button btnDirection;
double latitude, longitude;
LinearLayout linear_back;
LatLng startPosition, start;
String startPositionTitle;
Vibrator vibrator;
String startPositionSnippet;
Double desc1_long, desc1_lat;
LatLng destinationPosition1;
String destinationPositionTitle;
String destinationPositionSnippet;
MarkerOptions mDestination1, mStart;
ToggleButton tbMode;
GPSTracker gps;
Geocoder gCoder;
ArrayList<Address> addresses = null;
ArrayList<Address> adres2 = null;
SupportMapFragment mapFragment;
public final static double AVERAGE_RADIUS_OF_EARTH = 6371;
TextView back_txt;
openMap openMap;
String mapStatus = "start";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_route_map);
back_txt = (TextView) findViewById(R.id.txt_back);
try {
back_txt = (TextView) findViewById(R.id.txt_back);
modelData = model.getInstance();
vibrator = (Vibrator) getApplicationContext().getSystemService(Context.VIBRATOR_SERVICE);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
gCoder = new Geocoder(RouteMap.this);
addresses = (ArrayList<Address>) gCoder.getFromLocation(latitude, longitude, 1);
tbMode = (ToggleButton) findViewById(R.id.tbMode);
mapFragment = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map));
mapFragment.getMapAsync(this);
btnDirection = (Button) findViewById(R.id.btnDirection);
btnDirection.setOnClickListener(this);
tbMode.setChecked(true);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}
public int calculateDistance(double userLat, double userLng, double venueLat, double venueLng) {
final int R = 6371;
try {
Double latDistance = deg2rad(venueLat - userLat);
Double lonDistance = deg2rad(venueLng - userLng);
Double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2)
+ Math.cos(deg2rad(userLat)) * Math.cos(deg2rad(venueLat))
* Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);
Double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double distance = R * c * 1000; // convert to meters
double height = 0 - 0;
distance = Math.pow(distance, 2) + Math.pow(height, 2);
return (int) Math.sqrt(distance);
} catch (Exception ex) {
Toast.makeText(getApplicationContext(), "Please Check your Destination's GeoCode ", Toast.LENGTH_LONG).show();
}
return 0;
}
private double deg2rad(double deg) {return (deg * Math.PI / 180.0);}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap=googleMap;
//setUpMap();
try {
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mMap.setMyLocationEnabled(true);
mMap.setIndoorEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.getUiSettings().setCompassEnabled(true);
mMap.getUiSettings().setAllGesturesEnabled(true);
String[] arr = new String[modelData.outletList.size()];
for(int i=0;i<modelData.outletList.size();i++)
{
String str1 = modelData.outletList.get(i)[2];
String str2 = modelData.outletList.get(i)[3];
String newString = str1+","+str2;
arr[i] = newString;
}
String[] latTempArr = arr;
String strKey = "";
double curLatitude = latitude;
double curLongtitude = longitude;
double desLat;
double desLng;
Map<String, Integer> final_arr = new HashMap<String, Integer>();
Map<String, Integer> final_arr2 = new HashMap<String, Integer>();
List<Integer> intTempArr = new ArrayList<Integer>();
List<Integer> intTempArr2 = new ArrayList<Integer>();
for(int j=0;j<arr.length;j++)
{
intTempArr = new ArrayList<Integer>();
for (int k=0;k<latTempArr.length;k++)
{
String[] arr_temp = latTempArr[k].split(",");
//System.out.println(arr_temp[0]);
desLat = Double.parseDouble(arr_temp[0]);
desLng = Double.parseDouble(arr_temp[1]);
int temp = calculateDistance(curLatitude,curLongtitude,desLat,desLng);
intTempArr.add(temp);
final_arr.put(latTempArr[k],temp);
}
Collections.sort(intTempArr);
Integer[] array = new Integer[intTempArr.size()];
intTempArr.toArray(array);
for (Map.Entry<String, Integer> entry : final_arr.entrySet()) {
try{
if (entry.getValue().equals(array[0])) { //get next best path
List<String> list = new ArrayList<String>(Arrays.asList(latTempArr)); // remove the best path to find next one
list.remove(entry.getKey());
latTempArr = list.toArray(new String[0]);
String[] arr_temp2 = entry.getKey().split(",");
//System.out.println(arr_temp[0]);
curLatitude = Double.parseDouble(arr_temp2[0]);
curLongtitude = Double.parseDouble(arr_temp2[1]);
strKey = entry.getKey();
intTempArr2.add(entry.getValue());
final_arr2.put(strKey,entry.getValue());
}
}
catch(Exception e)
{
}
}
//System.out.println(intTempArr);
}
//int i = 0;
destinations = new ArrayList<String>();
for(int i =0;i<intTempArr2.size();i++) {
for(String Key : final_arr2.keySet()) {
//System.out.println();
if(final_arr2.get(Key) == intTempArr2.get(i)) {
destinations.add(Key);
break;
}
}
}
System.out.println(destinations);
for(int i = 0;i < destinations.size();i++) {
//Toast.makeText(getApplicationContext(), " ListItem : " + i, Toast.LENGTH_LONG).show();
String desti1 = destinations.get(i);
String[] des = desti1.split(",");
desc1_lat = Double.parseDouble(des[0]);
desc1_long = Double.parseDouble(des[1]);
startPosition = new LatLng(latitude, longitude);
startPositionTitle = addresses.get(0).getLocality();
startPositionSnippet = addresses.get(0).getAddressLine(1)+"," +" "+ addresses.get(0).getAddressLine(2);
try {
adres2 = (ArrayList<Address>) gCoder.getFromLocation(desc1_lat, desc1_long, 1);
} catch (IOException e) {
e.printStackTrace();
}
destinationPosition1 = new LatLng(desc1_lat, desc1_long);
destinationPositionTitle = adres2.get(0).getLocality();
destinationPositionSnippet =adres2.get(0).getAddressLine(1)+"," +" "+adres2.get(0).getAddressLine(2);
// mMap.setOnInfoWindowClickListener(this);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker marker) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View v = getLayoutInflater().inflate(R.layout.marker, null);
TextView info= (TextView) v.findViewById(R.id.info);
info.setText(marker.getSnippet().toString());
return v;
}
});
mDestination1 = new MarkerOptions()
.position(destinationPosition1)
.title(destinationPositionTitle)
.snippet(destinationPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));
mStart = new MarkerOptions()
.position(startPosition)
.title(startPositionTitle)
.snippet(startPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));
mMap.addMarker(mDestination1);
mMap.addMarker(mStart);
latitude = desc1_lat;
longitude = desc1_long;
LatLng locations = new LatLng(latitude,longitude);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locations, 5.5f));
}
}catch (Exception ex)
{
/*Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();*/
}
}
public void clearMap() {
mMap.clear();
}
#Override
public void onClick(View v) {
try
{
Locale mLocale = new Locale("en");
Log.d("Display language = ", "" + mLocale.getDisplayLanguage());
gCoder = new Geocoder(RouteMap.this,mLocale);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
for(int i = 0;i<destinations.size();i++) {
String desti1 = destinations.get(i);
String[] des = desti1.split(",");
desc1_lat = Double.parseDouble(des[0]);
desc1_long = Double.parseDouble(des[1]);
startPosition = new LatLng(latitude, longitude);
startPositionTitle = addresses.get(0).getLocality();
startPositionSnippet = addresses.get(0).getAddressLine(1)+","+" "+addresses.get(0).getAddressLine(2);
destinationPosition1 = new LatLng(desc1_lat, desc1_long);
destinationPositionTitle = adres2.get(0).getLocality();
destinationPositionSnippet =adres2.get(0).getAddressLine(1)+","+""+ adres2.get(0).getAddressLine(2);
mMap.setOnInfoWindowClickListener(this);
mStart = new MarkerOptions()
.position(startPosition)
.title(startPositionTitle)
.snippet(startPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin1));
mDestination1 = new MarkerOptions()
.position(destinationPosition1)
.title(destinationPositionTitle)
.snippet(destinationPositionSnippet)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin2));
if (v == btnDirection) {
// clearMap();
mMap.addMarker(mDestination1);
mMap.addMarker(mStart);
if (tbMode.isChecked()) {
new GetRotueListTask(RouteMap.this, startPosition,
destinationPosition1, GMapV2Direction.MODE_DRIVING, this)
.execute();
} else {
new GetRotueListTask(RouteMap.this, startPosition,
destinationPosition1, GMapV2Direction.MODE_WALKING, this)
.execute();
}
}
latitude = desc1_lat;
longitude = desc1_long;
}
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}
#Override
public void OnDirectionListReceived(List<LatLng> mPointList) {
try
{
if (mPointList != null) {
PolylineOptions rectLine = new PolylineOptions().width(10).color(
Color.RED);
for (int i = 0; i < mPointList.size(); i++) {
rectLine.add(mPointList.get(i));
}
mMap.addPolyline(rectLine);
gps = new GPSTracker(RouteMap.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
start = new LatLng(latitude, longitude);
CameraPosition mCPFrom = new CameraPosition.Builder()
.target(start).zoom(15.5f).bearing(0).tilt(25)
.build();
final CameraPosition mCPTo = new CameraPosition.Builder()
.target(destinationPosition1).zoom(15.5f).bearing(0)
.tilt(50).build();
changeCamera(CameraUpdateFactory.newCameraPosition(mCPFrom),
new CancelableCallback() {
#Override
public void onFinish() {
changeCamera(CameraUpdateFactory
.newCameraPosition(mCPTo),
new CancelableCallback() {
#Override
public void onFinish() {
LatLngBounds bounds = new LatLngBounds.Builder()
.include(start)
.include(
destinationPosition1)
.build();
changeCamera(
CameraUpdateFactory
.newLatLngBounds(
bounds, 50),
null, false);
}
#Override
public void onCancel() {
}
}, false);
}
#Override
public void onCancel() {
}
}, true);
}
}catch (Exception ex)
{
Toast.makeText(getApplicationContext(), "Please Check your Data Connection", Toast.LENGTH_LONG).show();
}
}
private void changeCamera(CameraUpdate update, CancelableCallback callback,
boolean instant) {
if (instant) {
mMap.animateCamera(update, 1, callback);
} else {
mMap.animateCamera(update, 4000, callback);
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onInfoWindowClick(Marker marker) {
}
private class openMap extends AsyncTask<String, Void, String>
{
ProgressDialog mProgressDialog;
Context ctx;
public openMap(Context ctx)
{
this.ctx=ctx;
mProgressDialog = new ProgressDialog(RouteMap.this);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.setMessage("Loading Map..Please wait....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
// Toast.makeText(getApplicationContext(), "Syncing DB...", Toast.LENGTH_LONG).show();
}
#Override
protected String doInBackground(String... urls)
{
return "Success";
}
#Override
protected void onPostExecute(String result)
{
mProgressDialog.dismiss();
try
{
if(result.equalsIgnoreCase("Success")) {
}
else
{
Toast.makeText(getApplicationContext(), "Please Check your Data connection or Turn on your Location", Toast.LENGTH_LONG).show();
}
}catch (Exception e){}
}
}
}
From this code above what changes should I make to fix the Skipped
1000+ frames issue and also help me add loader before opening the
map...
Geocoder.getFromLocation() is an expensive call that does a network call to Google's servers, so don't make it on the UI thread.
Have a look at Processes and Threads in the android developer docs for various ways of making the request in the background.
The code that you write in OnMapReady function is to much, please remove that code from there I can see there are more then 4 "for" loops in onMapReady, move that part to to some where else like OnCreate() create all maps and lists that you want.
Just ues OnMapReady function for placing markers
I'm trying to calculate distance between two locations on Google map. I'm inputting latitude and longitude from EditText,
but the return value is zero meters. What goes wrong in the code, i.e., how to get the real distance?
Here is a picture of my app:
public class Ma`inActivity extends AppCompatActivity implements OnMapReadyCallback {
private TextView source;
private TextView destination;
private EditText sLatitude1;
private EditText sLongtiude1;
private EditText dLatitude2;
private EditText dLongtiude2;
private Button button;
private GoogleMap mMap;
boolean mapReady = false;
MarkerOptions elsedaway;
MarkerOptions Elrob3;
Location location;
static final CameraPosition elfayoum = CameraPosition.builder()
.target(new LatLng(29.309324, 30.842973))
.zoom(1)
.bearing(6)
.tilt(45)
.build();
double lati1;
double longi1;
double lati2;
double longi2;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// find text that display distance
textView = (TextView) findViewById(R.id.distance);
MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
// find edit text and text view
source = (TextView) findViewById(R.id.sourc);
destination = (TextView) findViewById(R.id.destination);
sLatitude1 = (EditText) findViewById(R.id.lat1);
sLongtiude1 = (EditText) findViewById(R.id.long1);
dLatitude2 = (EditText) findViewById(R.id.lat2);
dLongtiude2 = (EditText) findViewById(R.id.long2);
// find button
button = (Button) findViewById(R.id.getDistance);
// find string from edittext
String lat1 = sLatitude1.getText().toString();
// parse string to double
lati1 = ParseDouble(lat1);
String lon1 = sLongtiude1.getText().toString();
longi1 = ParseDouble(lon1);
String lat2 = dLatitude2.getText().toString();
lati2 = ParseDouble(lat2);
String lon2 = dLongtiude2.getText().toString();
longi2 = ParseDouble(lon2);
Log.i("**lat", lat2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double xy1 = distanceBetween(new LatLng(lati1, longi1), new LatLng(lati1, longi2));
String distanceis = fmt(xy1) + "meter";
textView.setText(distanceis);
}
});
}
// mehtod to parse double from string
double ParseDouble(String strNumber) {
if (strNumber != null && strNumber.length() > 0) {
try {
return Double.parseDouble(strNumber);
} catch (Exception e) {
return -1; // or some value to mark this field is wrong. or make a function validates field first ...
}
} else return 0;
}
// get distance
public static Double distanceBetween(LatLng point1, LatLng point2) {
if (point1 == null || point2 == null) {
return null;
}
double vw = SphericalUtil.computeDistanceBetween(point1, point2);
Log.i("distance isby utillib ", String.valueOf(vw));
return vw;
}
public String fmt(double d) {
return String.format("%s", d);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mapReady = true;
mMap = googleMap;
// if(elsedaway!=null){
// mMap.addMarker(elsedaway);};
// mMap.addMarker(Elrob3);
mMap.addPolyline(new PolylineOptions().geodesic(true)
.add(new LatLng(lati1, longi1))
.add(new LatLng(lati2, lati2))
mMap.addCircle(new CircleOptions()
.center(new LatLng(29.291540, 30.601884))
.radius(500044)
.strokeColor(Color.GREEN)
.fillColor(Color.argb(54, 99, 255, 0)));
flyTo(elfayoum);
}
This link might help you to find the distance between 2 lat long points.
Here is java implementation of haversine formula.
Hope this may help
Move this punch of code into your onCLick, and Correct your values, your code should be like :
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String lat1 = sLatitude1.getText().toString();
// parse string to double
lati1 = ParseDouble(lat1);
String lon1 = sLongtiude1.getText().toString();
longi1 = ParseDouble(lon1);
String lat2 = dLatitude2.getText().toString();
lati2 = ParseDouble(lat2);
String lon2 = dLongtiude2.getText().toString();
longi2 = ParseDouble(lon2);
double xy1 = distanceBetween(new LatLng(lati1, longi1), new LatLng(lati2, longi2));
String distanceis = fmt(xy1) + "meter";
textView.setText(distanceis);
}
});
For starters, there is a mistake here :
double xy1 = distanceBetween(new LatLng(lati1, longi1), new LatLng(lati1, longi2));
You should be using lati2 instead of lati1 in your second argument.
And also, move the getText() inside the onClick(...) block.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
// find string from edittext
String lat1 = sLatitude1.getText().toString();
// parse string to double
lati1 = ParseDouble(lat1);
String lon1 = sLongtiude1.getText().toString();
longi1 = ParseDouble(lon1);
String lat2 = dLatitude2.getText().toString();
lati2 = ParseDouble(lat2);
String lon2 = dLongtiude2.getText().toString();
longi2 = ParseDouble(lon2);
...
}
});
I am trying to build an app for an individual project. I have a database of latitude and longitude coordinates with associated levels of radioactivity. The app checks the users location and checks the distance between them and the points in the database. If this distance is less than say 15 meters, it will trigger a warning light.
I was able to get the app to read in the database and store it in an arraylist of classes. I was also able to get the GPS to update location every 2 meters. I want to add a for loop in the onLocationChange method so that the app checks against the database but I am not sure how to do this... how can I pass the "dataPoints" arraylist to the locationlistener method so that the onLocationChange can access it?? Is this completed incorrect? I have included my code below:
public class MainActivity extends Activity{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 2, mLocationListener);
//read in datapoints from text file in assets folder and store in class "radioactivityData" in arrayList "dataPoints"
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(getAssets().open("combinedorderedData.txt")));
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
//Define and initialize the ArrayList
ArrayList<radioactivityData> dataPoints = new ArrayList<radioactivityData>(); //The ArrayList stores strings
String inLine; //Buffer to store the current line
try {
while ((inLine = reader.readLine()) != null) //Read line-by-line, until end of file
{
String[] parts = inLine.split(" ");
radioactivityData rad = new radioactivityData();
rad.setlatitude(Double.parseDouble(parts[0]));
rad.setlongitude(Double.parseDouble(parts[1]));
rad.setradioactivity(Integer.parseInt(parts[2]));
dataPoints.add(rad);
}
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //We've finished reading the file
}
//I think I just need to pass the dataPoints array to the LocationListener method... how? is this wrong?
LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
//Here I want to calculate the distance between current location and the data in the dataPoints array
for(int i=0; i<dataPoints.size(); i++){
if(getdistance(dataPoints.get(i).getlatitude(), dataPoints.get(i).getlongitude(),
location.getLatitude(), location.getLongitude())<15 && dataPoints.get(i).getradiation()>5000)
{
txtLat.setText("Turn on the green LED!");
break;
}
else
{
txtLat.setText("No radioactive areas nearby!");
}
}
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
private double getDistance(double lat1, double lon1, double lat2, double lon2){
double theta, dist;
theta = lon1 - lon2;
dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = Math.acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
dist = dist * 1.609344 * 1000;
return (dist);
}
private double deg2rad(double deg) {
return (deg * Math.PI / 180);
}
private double rad2deg(double rad) {
return (rad * 180 / Math.PI);
}
};
}
Here is the radioactivityData class in case that would be helpful
public class radioactivityData {
private double latitude;
private double longitude;
private int radioactivity;
public double getlatitude()
{
return latitude;
}
public void setlatitude(double latitude) {
this.latitude = latitude;
}
public double getlongitude()
{
return longitude;
}
public void setlongitude(double longitude) {
this.longitude = longitude;
}
public int getradioactivity()
{
return radioactivity;
}
public void setradioactivity(int radioactivity) {
this.radioactivity = radioactivity;
}
}
from onLocationChanged call a method to which you will pass current location in that method itself get All Location with which you want to compare.