@Override
  public synchronized void onLocationChanged(Location location) {
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    altitude = location.getAltitude();
    distance = Float.MAX_VALUE;

    // hay un punto siendo visitado y en el radio
    if (MapState.getInstance().getGPS().isDialogDisplayed()) {
      PointInfoState state = (PointInfoState) FRAGUEL.getInstance().getCurrentState();
      Location.distanceBetween(
          latitude, longitude, state.getPointOI().coords[0], state.getPointOI().coords[1], results);
      // si está fuera de rango cargamos el mapa
      float offset = Math.abs(lastFix - results[0]);
      if (offset <= 10.0f) {
        lastFix = results[0];
        hasBeenVisited = true;
      } else hasBeenVisited = false;
      if ((results[0] > proximityAlertDistance + proximityAlertError) && hasBeenVisited) {
        FRAGUEL.getInstance().changeState(MapState.STATE_ID);
        MapState.getInstance().loadData(currentRoute, currentPoint);
        MapState.getInstance().getGPS().setDialogDisplayed(false);
      }
    } else if (!MapState.getInstance().getGPS().isDialogDisplayed()
        && FRAGUEL.getInstance().getCurrentState().getId() == MapState.STATE_ID) {
      // si no hay ningún punto siendo visualizado , cogemos el de menos
      // distancia, siempre dentro del rango
      for (Route r : FRAGUEL.getInstance().routes) {
        for (PointOI p : r.pointsOI) {

          Location.distanceBetween(latitude, longitude, p.coords[0], p.coords[1], results);

          if (results[0] <= proximityAlertDistance) {
            if (results[0] < distance) {
              currentRoute = r;
              currentPoint = p;
              distance = results[0];
            }
          }
        }
      }
      if (currentRoute != null
          && currentPoint != null
          && !MapState.getInstance().getGPS().isDialogDisplayed()) {
        super.mediaNotification();
        FRAGUEL.getInstance().changeState(PointInfoState.STATE_ID);
        FRAGUEL.getInstance().getCurrentState().loadData(currentRoute, currentPoint);
        MapState.getInstance().getGPS().setDialogDisplayed(true);
        lastFix = results[0];
      }
    }
  }
示例#2
0
  public void CalculateStat() {
    Cnt = trackpoints.size();
    Duration = 0;
    if (trackpoints.size() > 0)
      Duration =
          (double)
              ((trackpoints.get(trackpoints.size() - 1).date.getTime()
                      - trackpoints.get(0).date.getTime())
                  / 1000);
    TrackPoint lastpt = null;
    Distance = 0;
    float[] results = {0};

    for (TrackPoint pt : trackpoints) {
      if (lastpt != null) {
        results[0] = 0;
        try {
          Location.distanceBetween(lastpt.lat, lastpt.lon, pt.lat, pt.lon, results);
          Distance += results[0];
        } catch (Exception e) {
        }
      }
      lastpt = pt;
    }
  }
示例#3
0
  private void findNearbyLocations(ArrayList<CoupersLocation> data) {

    double latitude;
    double longitude;
    boolean nearby_locations = false;
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    Location geoloc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (geoloc != null) {
      latitude = geoloc.getLatitude();
      longitude = geoloc.getLongitude();
    } else {
      latitude = -999;
      longitude = -999;
    }
    float[] results = new float[1];
    float distance = 0;

    for (CoupersLocation location : data) {
      location.show = true;
      if (geoloc != null) {
        Location.distanceBetween(
            latitude, longitude, location.location_latitude, location.location_longitude, results);
        distance = results[0];
        if (distance < 1000) {
          location.Nearby = true;
          nearby_locations = true;
        }
      }
    }
    app.nearby_locations = nearby_locations;
    app.gps_available = geoloc != null;
  }
示例#4
0
  @Override
  public void onMyLocationChange(Location location) {
    misCoordenadas = new double[] {location.getLongitude(), location.getLatitude()};

    if (!centered && mustCenter && getMap() != null) {
      getMap()
          .moveCamera(
              CameraUpdateFactory.newLatLng(new LatLng(misCoordenadas[1], misCoordenadas[0])));
      centered = true;
      buscarParadas();
    }

    if (posUltimaBusqueda == null) {
      posUltimaBusqueda = new LatLng(misCoordenadas[0], misCoordenadas[1]);
    } else {
      if (DataStorage.filtro.getDistancia() == Integer.MAX_VALUE) {
        return;
      }
      float[] distancia = new float[1];
      Location.distanceBetween(
          posUltimaBusqueda.latitude,
          posUltimaBusqueda.longitude,
          misCoordenadas[0],
          misCoordenadas[1],
          distancia);
      if (distancia[0] > 10) {
        buscarParadas();
        posUltimaBusqueda = new LatLng(misCoordenadas[0], misCoordenadas[1]);
      }
    }
  }
示例#5
0
    @Override
    public void onLocationChanged(Location location) {
      // counter++;
      // textD.setText(String.valueOf(counter));

      TextView textDistanceView = (TextView) findViewById(R.id.textDistance);

      float[] distanceMeters = new float[4];

      currentLat = location.getLatitude();
      currentLong = location.getLongitude();

      Location.distanceBetween(lastLat, lastLong, currentLat, currentLong, distanceMeters);
      totalDistance += distanceMeters[0];

      // changes current lat/long values to last lat/long values
      lastLat = currentLat;
      lastLong = currentLong;

      textDistanceView.setText("Current Location: " + String.valueOf(totalDistance));

      // Displays the current gps coordinates
      latitudeField.setText(String.valueOf(currentLat));
      longitudeField.setText(String.valueOf(currentLong));
    }
  @Override
  protected void drawMyLocation(
      Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLocation, long when) {
    if (!bugged) {
      try {
        super.drawMyLocation(canvas, mapView, lastFix, myLocation, when);
      } catch (Exception e) {
        // we found a buggy phone, draw the location icons ourselves
        bugged = true;
      }
    }

    if (bugged) {
      if (drawable == null) {

        accuracyPaint = new Paint();
        accuracyPaint.setAntiAlias(true);
        accuracyPaint.setStrokeWidth(2.0f);

        drawable =
            mapView
                .getContext()
                .getResources()
                .getDrawable(R.drawable.ic_maps_indicator_current_position);
        width = drawable.getIntrinsicWidth();
        height = drawable.getIntrinsicHeight();
        center = new Point();
        left = new Point();
      }

      Projection projection = mapView.getProjection();
      double latitude = lastFix.getLatitude();
      double longitude = lastFix.getLongitude();
      float accuracy = lastFix.getAccuracy();

      float[] result = new float[1];

      Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result);
      float longitudeLineDistance = result[0];

      GeoPoint leftGeo =
          new GeoPoint(
              (int) (latitude * 1e6), (int) ((longitude - accuracy / longitudeLineDistance) * 1e6));
      projection.toPixels(leftGeo, left);
      projection.toPixels(myLocation, center);
      int radius = center.x - left.x;

      accuracyPaint.setColor(0xff6666ff);
      accuracyPaint.setStyle(Style.STROKE);
      canvas.drawCircle(center.x, center.y, radius, accuracyPaint);

      accuracyPaint.setColor(0x186666ff);
      accuracyPaint.setStyle(Style.FILL);
      canvas.drawCircle(center.x, center.y, radius, accuracyPaint);

      drawable.setBounds(
          center.x - width / 2, center.y - height / 2, center.x + width / 2, center.y + height / 2);
      drawable.draw(canvas);
    }
  }
  /** Update GUI from currently selected POI Load POI actions */
  private void updateGUI() {
    try {
      TextView poiName = (TextView) findViewById(R.id.textPOIName);
      TextView poiDescription = (TextView) findViewById(R.id.textPOIDescription);
      View layoutLocation = findViewById(R.id.layoutPOILocation);

      poiThumbnail = (RemoteImageView) findViewById(R.id.imagePOIThumbnail);

      if (mPOI.getThumbnailURL().length() > 0) {
        poiThumbnail.setRemoteSource(new String(mPOI.getThumbnailURL()));
      } else {
        poiThumbnail.setVisibility(View.INVISIBLE);
      }

      final String name = mPOI.getName();
      if (name != null && name.length() >= 0) poiName.setText(name);

      poiDescription.setText(mPOI.getDescription());

      // add clickable links to strings like emails and websites
      Linkify.addLinks(poiDescription, Linkify.EMAIL_ADDRESSES | Linkify.WEB_URLS);

      // show location information only if the POI has LLA coordinates
      if (mPOI.hasLLA()) {
        TextView poiLocation = (TextView) findViewById(R.id.textPOILocation);
        LLACoordinate mylocation =
            JunaioPlugin.getSensorsManager(getApplicationContext()).getLocation();

        // get the distance and store in results[0], get the bearing and
        // store it in results[1]
        float[] results = new float[2];
        Location.distanceBetween(
            mylocation.getLatitude(),
            mylocation.getLongitude(),
            mPOI.getLocation().getLatitude(),
            mPOI.getLocation().getLongitude(),
            results);

        // get the proper units. To change units see
        // JunaioPlugin.Settings.useImperialUnits
        poiLocation.setText(
            JunaioUtils.getRelativeLocationString(
                mPOI.getCurrentDistance(), 0, false, JunaioPlugin.Settings.useImperialUnits));

        JunaioPlugin.log("Bearing: " + results[1]);

        pointer.updateOrientation(-results[1]);
        layoutLocation.setVisibility(View.VISIBLE);
      } else {
        layoutLocation.setVisibility(View.GONE);
      }

      loadPOIActions();

    } catch (Exception e) {
      JunaioPlugin.log("POIDetailDialog.updateGUI: " + e.getMessage());
    }
  }
示例#8
0
 public void updateDistances(Location location) {
   for (Marker ma : markerList) {
     float[] dist = new float[3];
     Location.distanceBetween(
         ma.getLatitude(),
         ma.getLongitude(),
         location.getLatitude(),
         location.getLongitude(),
         dist);
     ma.setDistance(dist[0]);
   }
 }
示例#9
0
  // ---------------------------------------------------------------------------------------------
  // Method for finding the nearest vet. ---------------------------------------------------------
  private void findNearestVet() {
    Double tempVetLat, tempVetLng;
    LatLng tempVetLatLng;
    String tempVetName;
    float minimumDistance = 0;
    nearestVetPosition = 0;
    Log.d("VetFirstActivity", "ready to read the data from the list");
    if (vetList != null) {
      for (int i = 0; i < vetList.size(); i++) {
        tempVetLat = vetList.get(i).getLat();
        tempVetLng = vetList.get(i).getLng();
        tempVetName = vetList.get(i).getName();
        Log.d(
            "VetFirstActivity",
            "(#" + i + ") " + tempVetName + "(" + tempVetLat + ", " + tempVetLng + ")");
        markerOptionsList.add(
            new MarkerOptions().position(new LatLng(tempVetLat, tempVetLng)).title(tempVetName));
        Log.d("VetFirstActivity", "added an item to markerOptionsList");

        tempVetLatLng = new LatLng(tempVetLat, tempVetLng);

        float[] distance_results = new float[2];
        Location.distanceBetween(
            currentLocationLatLng.latitude,
            currentLocationLatLng.longitude,
            tempVetLatLng.latitude,
            tempVetLatLng.longitude,
            distance_results);
        Log.d(
            "VetFirstActivity",
            "distance: "
                + distance_results[0]
                + " m - initial bearing: "
                + distance_results[1]
                + " degrees");

        if (i == 0) {
          minimumDistance = distance_results[0];
        } else if (minimumDistance > distance_results[0]) {
          minimumDistance = distance_results[0];
          nearestVetPosition = i;
        }
      }
    } else {
      Log.d("VetFirstActivity", "empty vetList");
    }
    nearestVet = vetList.get(nearestVetPosition);
    nearestVetLatLng = new LatLng(nearestVet.getLat(), nearestVet.getLng());
    Log.d(
        "VetFirstActivity",
        "nearest vet is: " + nearestVet.getName() + "(" + nearestVet.getTelephone() + ")");
  }
  @Override
  protected void drawMyLocation(
      Canvas canvas, MapView mapView, Location lastFix, GeoPoint myLocation, long when) {

    accuracyPaint = new Paint();
    accuracyPaint.setAntiAlias(true);
    accuracyPaint.setStrokeWidth(2.0f);
    center = new Point();
    left = new Point();

    Projection projection = mapView.getProjection();
    double latitude = lastFix.getLatitude();
    double longitude = lastFix.getLongitude();
    float accuracy = lastFix.getAccuracy();

    float[] result = new float[1];

    Location.distanceBetween(latitude, longitude, latitude, longitude + 1, result);
    float longitudeLineDistance = result[0];

    GeoPoint leftGeo =
        new GeoPoint(
            (int) (latitude * 1e6), (int) ((longitude - accuracy / longitudeLineDistance) * 1e6));
    projection.toPixels(leftGeo, left);
    projection.toPixels(myLocation, center);
    int radius = center.x - left.x;

    accuracyPaint.setColor(0xff6666ff);
    accuracyPaint.setStyle(Style.STROKE);
    canvas.drawCircle(center.x, center.y, radius, accuracyPaint);

    accuracyPaint.setColor(0x186666ff);
    accuracyPaint.setStyle(Style.FILL);
    canvas.drawCircle(center.x, center.y, radius, accuracyPaint);

    mapView.getProjection().toPixels(myLocation, point);
    rect.left = point.x - slips[currSlip].getIntrinsicWidth() / 2;
    rect.top = point.y - slips[currSlip].getIntrinsicHeight() / 2;
    rect.right = point.x + slips[currSlip].getIntrinsicWidth() / 2;
    rect.bottom = point.y + slips[currSlip].getIntrinsicHeight() / 2;
    slips[currSlip].setBounds(rect);
    slips[currSlip].draw(canvas);
  }
  protected double getBearing(int begin, int end) {

    ArrayList<Location> original = track.getGeoPoints();
    double bearing = 0;
    if (begin < 0) begin = 0;
    if (end > original.size()) end = original.size();
    if (begin > end) begin = end;

    double t[] = new double[end - begin],
        lng[] = new double[end - begin],
        lat[] = new double[end - begin];
    long t0 = original.get(begin).getTime();

    for (int j = 0, i = begin; i < end; i++, j++) {
      Location loc = original.get(i);
      t[j] = ((loc.getTime() - t0) / 1000.0);
      lat[j] = loc.getLatitude();
      lng[j] = loc.getLongitude();
    }

    if (latBearingApproximator.approximate(t, lat) && lngBearingApproximator.approximate(t, lng)) {
      int ind = end - 1;
      double time = (original.get(ind).getTime() - t0) / 1000.0;

      long deltaTime = 2;
      double latitude0, longitude0, latitude, longitude;

      latitude = latBearingApproximator.function(time);
      longitude = lngBearingApproximator.function(time);

      latitude0 = latBearingApproximator.function(time - deltaTime);
      longitude0 = lngBearingApproximator.function(time - deltaTime);

      float distanceAndBearing[] = new float[3];
      Location.distanceBetween(latitude0, longitude0, latitude, longitude, distanceAndBearing);

      bearing = distanceAndBearing[1];
    }

    return bearing;
  }
示例#12
0
  public void calcSpeed(Location location, Location dest) {
    //        double dist = GoogleMapUtils.getDistanceBetweenPoints(lat1, lng1, lat2, lng2 );
    //        double dist2 = GoogleMapUtils.getDistance(lat1, lng1, lat2, lng2 );
    //        long dist3 = GoogleMapUtils.getDistanceBetweenPoints2(lat1, lng1, lat2, lng2 );
    //
    //        Log.i(TAG, " Dist is: " + dist + " " + dist2 + " " + dist3);
    //
    //        long speed = Math.round(dist/GPS_FREQUENCY);
    //        double speed2 = Math.round(dist2/GPS_FREQUENCY);
    //        long speed3 = Math.round(dist3/GPS_FREQUENCY);
    //        Log.i(TAG, " SPEED is: " + speed + " " + speed2 + " " + speed3);
    //        userSession.setCurSpeed(new Double(GoogleMapUtils.convertMetersToMiles(speed)));

    //        float [] result = new float[3];
    //        Location.distanceBetween(lat1,lng1, lat2, lng2, result);
    float f = location.distanceTo(dest);
    Log.i(TAG, "distance to: ========> " + f);

    // Update speed
    userSession.setCurSpeed(((long) f / GPS_FREQUENCY));

    if (userSession.getDestLat() != null && userSession.getDestLng() != null) {
      float[] results = new float[3];
      Location.distanceBetween(
          location.getLatitude(),
          location.getLongitude(),
          userSession.getDestLat(),
          userSession.getDestLng(),
          results);
      //            double t2 = GoogleMapUtils.getDistance(lat1, lng1, userSession.getDestLat(),
      // userSession.getDestLng());
      userSession.setDistToDest(new Double((long) results[0]));
      Log.i(TAG, " Dist to destination is: " + results[0] + " ");
    }

    Toast.makeText(
            context,
            "speed: " + userSession.getCurSpeed() + " " + userSession.getDistToDest(),
            Toast.LENGTH_LONG)
        .show();
  }
示例#13
0
        public void onLocationChanged(Location loc2) {
          if (loc2 != null) {

            display.setText(String.valueOf(dist));

            lat2 = loc2.getLatitude();
            lon2 = loc2.getLongitude();

            float[] results = new float[1];
            Location.distanceBetween(lat1, lon1, lat2, lon2, results);

            dist = dist + results[0];
            double d = (double) dist;
            d = Math.round(d * 100.0) / 100.0;
            dist = (float) d;
            updateDistanceInTextView(dist);
            lat1 = lat2;
            lon1 = lon2;
            lat2 = 0;
            lon2 = 0;
          }
        }
示例#14
0
  /*
   * 返回 km
   * */
  public static double getDistance(double lat1, double lng1, double lat2, double lng2) {
    LatLng start = new LatLng(lat1, lng1);
    LatLng end = new LatLng(lat2, lng2);
    double radLat1 = rad(lat1);
    double radLat2 = rad(lat2);
    double a = radLat1 - radLat2;
    double b = rad(lng1) - rad(lng2);
    double s =
        2
            * Math.asin(
                Math.sqrt(
                    Math.pow(Math.sin(a / 2), 2)
                        + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000.0;
    float result[] = new float[1];
    Location.distanceBetween(lat1, lng1, lat2, lng2, result);
    s = Math.round(((double) result[0] / 1000) * 100) / 100.0;

    AMapUtils.calculateLineDistance(start, end);
    return s;
  }
  public static void loadTrackings(Calendar c) {
    trackings.clear();

    File file = new File(getTrackingFile(c));
    if (!file.exists()) {
      log.warn(file + "does not exist");
      return;
    }

    log.info("Loading " + file);

    float[] results = new float[1];
    LineIterator li = null;
    try {
      li = Files.lineIterator(file);
      while (li.hasNext()) {
        String line = li.next();
        if (Strings.isEmpty(line)) {
          continue;
        }

        TrackingData td = Jsons.fromJson(line, TrackingData.class);
        TrackingData ltd = getLastLocation();
        if (ltd != null) {
          Location.distanceBetween(
              ltd.getLatitude(), ltd.getLongitude(), td.getLatitude(), td.getLongitude(), results);
          td.setDistance(results[0]);
          td.setSpeed(td.getDistance() / DateTimes.subSeconds(td.getDate(), ltd.getDate()));
        }
        trackings.add(td);
      }
    } catch (IOException e) {
      log.error(e);
    } finally {
      Streams.safeClose(li);
    }
  }
  @SuppressWarnings({"rawtypes", "unchecked"})
  @Override
  public void onReceive(Context context, Intent intent) {
    Log.d("ReminderBroadcastReceiver", "onReceive: received location update");

    final LocationInfo currentLocationInfo =
        (LocationInfo)
            intent.getSerializableExtra(
                LocationLibraryConstants.LOCATION_BROADCAST_EXTRA_LOCATIONINFO);

    if (currentLocationInfo.anyLocationDataReceived()) {
      DBAdapter mDbAdapter = new DBAdapter(context);
      mDbAdapter.open();
      Cursor c =
          mDbAdapter.fetchAllTaskForLocation(
              (int) (currentLocationInfo.lastLat * 1E6),
              (int) (currentLocationInfo.lastLong * 1E6),
              200,
              50);
      c.moveToFirst();

      boolean deletedIndeterminate = true;
      ArrayList<HashMap> locations = new ArrayList<HashMap>();
      while (!c.isAfterLast()) {
        float[] results = new float[1];
        Location.distanceBetween(
            currentLocationInfo.lastLat,
            currentLocationInfo.lastLong,
            c.getInt(c.getColumnIndex(TaskTableSchema.KEY_LATITUDE)) / 1E6,
            c.getInt(c.getColumnIndex(TaskTableSchema.KEY_LONGITUDE)) / 1E6,
            results);
        float distanceInMeters = results[0];

        Log.d("----task", c.getString(c.getColumnIndex(TaskTableSchema.KEY_TASK)));
        Log.d(
            "----meters: ",
            distanceInMeters
                + " radius: "
                + c.getFloat(c.getColumnIndex(TaskTableSchema.KEY_RADIUS)));

        if (distanceInMeters <= c.getFloat(c.getColumnIndex(TaskTableSchema.KEY_RADIUS))) {
          Log.d("----", "----IN");
          HashMap data = new HashMap();
          data.put(
              IndeterminateTaskSchema.KEY_TASK_ID,
              c.getLong(c.getColumnIndex(TaskTableSchema._ID)));
          data.put("radius", c.getLong(c.getColumnIndex(TaskTableSchema.KEY_RADIUS)));
          data.put("snooze", c.getInt(c.getColumnIndex(TaskTableSchema.KEY_SNOOZE_ON)));
          locations.add(data);

          if (deletedIndeterminate) {
            deletedIndeterminate = false;
            mDbAdapter.deleteAllIndeterminateTask();
          }
          mDbAdapter.createIndeterminateTask(data);
        }

        c.moveToNext();
      }
      c.close();

      if (locations.size() > 0) {
        HashMap data = null;
        for (HashMap hashMap : locations) {
          Log.d(
              "----" + Integer.valueOf(hashMap.get("snooze").toString()),
              "----hashMap: " + hashMap);
          if (Integer.valueOf(hashMap.get("snooze").toString()) == AppConstants.DEACTIVATED) {
            data = hashMap;
            break;
          }
        }

        if (data != null) {
          // HashMap data = locations.get(0);
          long id = -1;
          id = Long.valueOf(data.get(IndeterminateTaskSchema.KEY_TASK_ID).toString());

          if (id != -1) {
            Cursor cursor = mDbAdapter.fetchTask(id);
            Log.d(
                "----IN task:", cursor.getString(cursor.getColumnIndex(TaskTableSchema.KEY_TASK)));

            String taskName = cursor.getString(cursor.getColumnIndex(TaskTableSchema.KEY_TASK));
            String desc = cursor.getString(cursor.getColumnIndex(TaskTableSchema.KEY_NOTES));
            cursor.close();

            Bundle extras = new Bundle();
            NotifierHelper.sendNotification(
                context,
                NotificationViewController.class,
                taskName,
                desc,
                locations.size(),
                true,
                false,
                extras);

            Intent i = new Intent();
            i.setClassName(
                "com.example.reminder.controllers",
                "com.example.reminder.controllers.AlarmReceiverActivity");
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.putExtra(TaskTableSchema._ID, id);
            i.putExtra(TaskTableSchema.KEY_TASK, taskName);
            i.putExtra(TaskTableSchema.KEY_NOTES, desc);
            context.startActivity(i);
          }
        }
      }

      mDbAdapter.close();

      if (currentLocationInfo.hasLatestDataBeenBroadcast()) {
        Log.d("ReminderBroadcastReceiver", "Latest location has been broadcast");

      } else {
        Log.d(
            "ReminderBroadcastReceiver",
            "Location broadcast pending (last "
                + LocationInfo.formatTimeAndDay(
                    currentLocationInfo.lastLocationUpdateTimestamp, true)
                + ")");
      }
    } else {
      Log.d("ReminderBroadcastReceiver", "No locations recorded yet");
    }
  }
  @Override
  public void run() {
    Log.v(Program.LOG, "DatabaseSearcher.run()");

    double radius =
        PreferenceManager.getDefaultSharedPreferences(context)
            .getInt(context.getResources().getString(R.string.radius), 20);

    Location l = StoreFinderApplication.getLastKnownLocation();

    double lat = l.getLatitude();
    double lon = l.getLongitude();

    database = database.open();
    db = database.getDatabase();

    Cursor c =
        db.query(
            "store",
            new String[] {
              "_id", "name", "address", "city", "state", "zip", "phone", "latitude", "longitude"
            },
            "latitude > "
                + (lat - radius / MILES_PER_LATLONG)
                + " AND latitude < "
                + (lat + radius / MILES_PER_LATLONG)
                + " AND longitude > "
                + (lon - radius / MILES_PER_LATLONG)
                + " AND longitude < "
                + (lon + radius / MILES_PER_LATLONG),
            null,
            null,
            null,
            null);

    double latitude, longitude;

    c.moveToFirst();
    if (c.getCount() > 0) {
      do {
        latitude = c.getDouble(7);
        longitude = c.getDouble(8);
        float[] results = new float[3];
        Location.distanceBetween(lat, lon, latitude, longitude, results);
        double distance = results[0] * Program.MILES_PER_METER;

        if (distance > radius) // Make user customizable search distance
        continue;

        Store store = new Store();
        store.setId(c.getInt(0));
        store.setName(c.getString(1));
        store.setAddress(c.getString(2));
        store.setCitystate(c.getString(3) + ", " + c.getString(4) + " " + c.getString(5));
        store.setPhone(c.getString(6));
        store.setDistance(distance);

        Location loc = new Location("");
        loc.setLatitude(latitude);
        loc.setLongitude(longitude);
        store.setLocation(loc);

        Message msg = new Message();
        Bundle b = new Bundle();
        b.putSerializable("store", store);
        msg.setData(b);
        msg.what = WHAT_SEARCHDB;
        handler.sendMessage(msg);
      } while (c.moveToNext());
    }

    c.close();
    database.close();

    Message finish = new Message();
    finish.what = WHAT_FINISHEDSEARCH;
    handler.sendMessage(finish);
  }
  @Override
  protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub

    // CommonUtil.tolog("ondraw-----------");
    int x;
    int y;

    boolean xAngleprod = true;
    boolean yAngleprod = true;

    int width = 150;
    int height = 150;

    double height_ratio = 0;

    float[] result = new float[3];

    try {

      if (flag == 0) {
        refreshThread = new refreshVisible(canvas, this);
        refreshThread.start();
        flag = 1;
      }
      currentAltitude = LocationHandler.ALTITUDE;
      currentLatitude = LocationHandler.LATITUDE;
      currentLongtitude = LocationHandler.LONGTITUDE;

      zeroToimageLongtitude = imageLongtitude - currentLongtitude;
      zeroToimageLatitude = imageLatitude - currentLatitude;
      zeroToImageAltitude = imageAltitude - currentAltitude;

      Location.distanceBetween(
          currentLatitude, currentLongtitude, imageLatitude, imageLongtitude, result);

      zeroToImageLength = result[0];

      X_arctan = zeroToimageLongtitude / zeroToimageLatitude;
      Y_arctan = zeroToImageAltitude / zeroToImageLength;

      height_ratio =
          Math.sqrt(getMarker().getArea())
              / (zeroToImageLength
                  * (Math.tan(Math.toRadians(WorldTabActivity.verticalAngle / 2))));

      height = (int) ((height_ratio) * (double) pt.y);

      // width = height;Math.sqrt(getMarker().getArea())

      // CommonUtil.tolog("-----------------start ---------------");
      //
      // CommonUtil.tolog("getMarker().getArea() = " +
      // getMarker().getArea());
      // CommonUtil.tolog("Math.sqrt(getMarker().getArea()) = " +
      // Math.sqrt(getMarker().getArea()));
      // CommonUtil.tolog("zeroToImageLength = " + zeroToImageLength);
      // CommonUtil.tolog("MainActivity.verticalAngle/2 = " +
      // WorldTabActivity.verticalAngle/2);
      // CommonUtil.tolog("Math.toRadians(MainActivity.verticalAngle/2 = "
      // + Math.toRadians(WorldTabActivity.verticalAngle/2));
      // CommonUtil.tolog("(Math.tan(Math.toRadians(MainActivity.verticalAngle/2)) = "
      // + (Math.tan(Math.toRadians(WorldTabActivity.verticalAngle/2))));
      // CommonUtil.tolog("height_ratio = " + height_ratio);
      // CommonUtil.tolog("height = " + height);
      // CommonUtil.tolog("pt.y = " + pt.y);
      // CommonUtil.tolog("((double)pt.y*(double)0.1) = " +
      // ((double)pt.y*(double)0.1));
      // CommonUtil.tolog("((double)pt.y*(double)0.8) = " +
      // ((double)pt.y*(double)0.8));
      //
      // CommonUtil.tolog("-----------------end---------------");

      if (height < ((double) pt.y * (double) 0.1)) {
        height = (int) ((double) pt.y * (double) 0.1);
      } else if (height > ((double) pt.y * (double) 0.8)) {
        height = (int) ((double) pt.y * (double) 0.8);
      }

      width = height;

      aziToViewAngle_X = Math.toDegrees(Math.atan(X_arctan)) - WorldTabActivity.azimuth;

      // 3 사분면
      if (zeroToimageLatitude < 0 && zeroToimageLongtitude < 0) {
        aziToViewAngle_X = (Math.toDegrees(Math.atan(X_arctan)) - 180) - WorldTabActivity.azimuth;
      }
      // 4 사분면
      else if (zeroToimageLatitude < 0 && zeroToimageLongtitude > 0) {
        aziToViewAngle_X = (Math.toDegrees(Math.atan(X_arctan)) + 180) - WorldTabActivity.azimuth;
      }

      aziToViewAngleASIN_X = Math.sin(Math.toRadians(aziToViewAngle_X));

      pitchToViewAngle_Y = WorldTabActivity.pitch - Math.toDegrees(Math.atan(Y_arctan));
      pitchToViewAngleASIN_Y = Math.sin(Math.toRadians(pitchToViewAngle_Y));

      double root =
          Math.sqrt(
                  Math.pow(
                          disHalf
                              / Math.sin(
                                  Math.toRadians(
                                      (double) WorldTabActivity.horizontalAngle / (double) 2)),
                          2)
                      - Math.pow(disHalf, 2))
              * Math.tan(Math.toRadians(aziToViewAngle_X));
      double root2 =
          Math.sqrt(
                  Math.pow(
                          disHalf
                              / Math.sin(
                                  Math.toRadians(
                                      (double) WorldTabActivity.verticalAngle / (double) 2)),
                          2)
                      - Math.pow(disHalf, 2))
              * Math.tan(Math.toRadians(pitchToViewAngle_Y));
      // x = (int) (((disHalf * 2) * aziToViewAngleASIN_X) +
      // disHalf);horizontalAngle
      x = (int) (root + disHalf);
      // y = (int) (((disHalf * 2) * pitchToViewAngleASIN_Y) + disHalf);
      y = (int) (root2 + disHalf);

      // CommonUtil.tolog("-----------------start ---------------");
      //
      // CommonUtil.tolog("this.getMarker().getMemo() = " +
      // this.getMarker().getMemo());
      //
      // // CommonUtil.tolog(" zeroToimageLongtitude = " +
      // zeroToimageLongtitude);
      // // CommonUtil.tolog(" zeroToimageLatitude = " +
      // zeroToimageLatitude);
      // // CommonUtil.tolog(" X_arctan = " + X_arctan);
      // // CommonUtil.tolog(" Math.toDegrees(Math.atan(X_arctan)) = " +
      // Math.toDegrees(Math.atan(X_arctan)));
      //
      // CommonUtil.tolog("aziToViewAngle_X = " + aziToViewAngle_X);
      // CommonUtil.tolog("aziToViewAngleASIN_X = " +
      // aziToViewAngleASIN_X);
      // CommonUtil.tolog("root = " + root);
      // CommonUtil.tolog("WorldTabActivity.verticalAngle = " +
      // WorldTabActivity.verticalAngle);
      // CommonUtil.tolog("x = " + x);
      // CommonUtil.tolog("aziToViewAngle_Y = " + pitchToViewAngle_Y);
      // CommonUtil.tolog("aziToViewAngleASIN_Y = " +
      // pitchToViewAngleASIN_Y);
      // CommonUtil.tolog("root2 = " + root2);
      // CommonUtil.tolog("WorldTabActivity.horizontalAngle = " +
      // WorldTabActivity.horizontalAngle);
      // CommonUtil.tolog("y = " + y);
      // CommonUtil.tolog("width = " + width);
      //
      // CommonUtil.tolog("-----------------end---------------");

      if (aziToViewAngle_X < 90 && aziToViewAngle_X > -90 && x > -width && x < pt.x) {
        // if (x > -width && x < pt.x ) {
        xAngleprod = true;
      } else {
        xAngleprod = false;
      }
      if (pitchToViewAngle_Y < 90 && pitchToViewAngle_Y > -90 && y > -height && y < pt.y) {
        // if ( y > -height && y < pt.y) {
        yAngleprod = true;
      } else {
        yAngleprod = false;
      }

      if (xAngleprod == true && yAngleprod == true) {

        if (flag_outside == true) {
          flag_outside = false;
          flag_arrow_side = -1;

          this.setImageBitmap(marker.getPic());
        }
        // CommonUtil.tolog("==========layout 동작=========");
        this.layout(x, y, x + width, y + height);
        // CommonUtil.tolog("pass if");
        // this.setsc

        // 스레드 스탑
        // 스레드가 인터럽트 걸리지 않았을때 = 스레드가 계속 돌고있을때.
      } else {
        // 인터럽트 걸리지 않았을경우
        // 보이지 않는 곳의 좌표가 찍힌 경우
        // 스레드 스타트
        // CommonUtil.tolog("pass not gone3");

        width = 32;
        height = 32;

        // left
        if (x < 0 && x > -2 * pt.x) {

          if (flag_outside == false) {

            flag_outside = true;

            if (flag_arrow_side != ARROW_LEFT) {
              flag_arrow_side = ARROW_LEFT;
              this.setImageDrawable(context.getResources().getDrawable(R.drawable.arrow_left));
            }
          }

          this.layout(0, y, width, y + height);

        }

        // right
        else if (x > pt.x && x < pt.x + pt.x) {

          if (flag_outside == false) {

            flag_outside = true;
            if (flag_arrow_side != AAROW_RIGHT) {
              flag_arrow_side = AAROW_RIGHT;
              this.setImageDrawable(context.getResources().getDrawable(R.drawable.arrow_right));
            }
          }

          this.layout(pt.x - width, y, pt.x, y + height);
        }

        // up
        else if (x > 0 && x < pt.x && y < 0) {

          if (flag_outside == false) {

            flag_outside = true;
            if (flag_arrow_side != ARROW_UP) {
              flag_arrow_side = ARROW_UP;
              this.setImageDrawable(context.getResources().getDrawable(R.drawable.arrow_up));
            }
          }

          this.layout(x, 0, x + width, height);

        }

        // down
        else if (x > 0 && x < pt.x && y > pt.y) {

          if (flag_outside == false) {

            flag_outside = true;
            if (flag_arrow_side != ARROW_DOWN) {
              flag_arrow_side = ARROW_DOWN;
              this.setImageDrawable(context.getResources().getDrawable(R.drawable.arrow_down));
            }
          }

          this.layout(x, pt.y - height, x + width, pt.y);

        } else {
          this.layout(0, 0, 1, 1);
        }
      }

      super.onDraw(canvas);
      // CommonUtil.tolog("ondraw end-----------");
      invalidateCustom(canvas);
    } catch (Exception e) {
      // TODO: handle exception
      e.printStackTrace();
    }
  }
 public static float getDistance(
     double startLati, double startLongi, double goalLati, double goalLongi) {
   float[] resultArray = new float[99];
   Location.distanceBetween(startLati, startLongi, goalLati, goalLongi, resultArray);
   return resultArray[0];
 }
  public void showPlace(Place place) {

    if (place != null) {
      this.currentPlace = place;
      // create place name.
      TextView name = (TextView) findViewById(R.id.place_name);
      if (name != null) {
        name.setText(place.getName());
      }

      // create PLACE description.
      TextView description = (TextView) findViewById(R.id.place_description);
      if (description != null) {
        String descStr = place.getDescription();

        if (descStr != null && !descStr.isEmpty() && !descStr.equals("null")) {
          description.setText(descStr);
        } else {
          description.setVisibility(View.GONE);
        }
      }

      if (place.getImage() != null && !place.getImage().isEmpty()) {
        // place image
        ImageView image = (ImageView) findViewById(R.id.place_image);
        if (image != null) {
          DataManager.getSingleton().downloadBitmap(place.getImage(), image);
        }
      }

      // place location
      Location location = place.getLocation();
      if (location != null) {
        TextView placeLocation = (TextView) findViewById(R.id.place_location);
        if (placeLocation != null) {
          placeLocation.setText(location.getAddress());
        }

        // place distance.
        TextView distance = (TextView) findViewById(R.id.place_distance);
        if (distance != null) {
          float[] distanceResults = new float[1];
          android.location.Location currentLocation = AppLocationManager.getCurrentLocation();
          DecimalFormat df = new DecimalFormat("#.#");

          if (currentLocation != null) {
            android.location.Location.distanceBetween(
                currentLocation.getLatitude(),
                currentLocation.getLongitude(),
                Double.valueOf(location.getLatitude()),
                Double.valueOf(location.getLongitude()),
                distanceResults);
            double miles = distanceResults[0] / 1609.34; // i mile =
            // 1.60934km
            distance.setText(df.format(miles) + "mi");
          } else {
            distance.setText("--");
          }
        }

        MapView map = (MapView) findViewById(R.id.mapview);
        if (map != null) {
          MapController mc = map.getController();
          if (mc != null) {

            List<Overlay> mapOverlaysList = map.getOverlays();
            Drawable drawable = this.getResources().getDrawable(R.drawable.red_pointer_icon);

            // creating an ItemizedOverlayActivity object so we can
            // have multiple overlays
            // added to a list to show them in a map
            ItemizedOverlayActivity itemizedoverlay = new ItemizedOverlayActivity(drawable, this);

            GeoPoint geoPoint =
                new GeoPoint(
                    (int) (Double.valueOf(location.getLatitude()) * 1E6),
                    (int) (Double.valueOf(location.getLongitude()) * 1E6));

            // Creates an overlay item with a geopoint to show in
            // the map
            OverlayItem overlayitem = new OverlayItem(geoPoint, "Place", place.getName());

            itemizedoverlay.addOverlay(overlayitem);
            mapOverlaysList.add(itemizedoverlay);

            mc.setCenter(geoPoint);
            mc.setZoom(17);
          }
        }

        showEventList(place.getEventsAtPlace());
      }
    }
  } // end showPlace
 public static float distanceBetween(LatLng first, LatLng second) {
   float[] distance = new float[1];
   Location.distanceBetween(
       first.latitude, first.longitude, second.latitude, second.longitude, distance);
   return distance[0];
 }
示例#22
0
  @Override
  public void onDraw(Canvas canvas, RectF latlonBounds, RectF tilesRect, boolean nightMode) {
    // prepare data (left distance, speed)
    if (map.getPointToNavigate() != null) {
      int d = 0;
      if (map.getRoutingHelper().isRouterEnabled()) {
        d = map.getRoutingHelper().getLeftDistance();
      }
      if (d == 0) {
        Location.distanceBetween(
            view.getLatitude(),
            view.getLongitude(),
            map.getPointToNavigate().getLatitude(),
            map.getPointToNavigate().getLongitude(),
            calculations);
        d = (int) calculations[0];
      }
      if (distChanged(cachedMeters, d)) {
        cachedMeters = d;
        if (cachedMeters <= 20) {
          cachedMeters = 0;
          cachedDistString = null;
        } else {
          cachedDistString = OsmAndFormatter.getFormattedDistance(cachedMeters, map);
          float right =
              paintBlack.measureText(cachedDistString) + 25 * scaleCoefficient + boundsForDist.left;
          if (cachedSpeedString != null) {
            boundsForSpeed.right = boundsForDist.right = Math.max(right, boundsForDist.right);
          } else {
            boundsForDist.right = right;
          }
        }
      }
    } else {
      cachedMeters = 0;
      cachedDistString = null;
    }
    if (view.getZoom() != cachedZoom) {
      cachedZoom = view.getZoom();
      cachedZoomString = view.getZoom() + ""; // $NON-NLS-1$
    }
    // draw zoom
    canvas.drawRoundRect(boundsForZoom, roundCorner, roundCorner, paintAlphaGray);
    canvas.drawRoundRect(boundsForZoom, roundCorner, roundCorner, paintBlack);
    canvas.drawText(
        cachedZoomString,
        boundsForZoom.left + 5 * scaleCoefficient,
        boundsForZoom.bottom - 8 * scaleCoefficient,
        paintBlack);

    // draw speed
    if (map.getLastKnownLocation() != null && map.getLastKnownLocation().hasSpeed()) {
      if (Math.abs(map.getLastKnownLocation().getSpeed() - cachedSpeed) > .3f) {
        cachedSpeed = map.getLastKnownLocation().getSpeed();
        cachedSpeedString = OsmAndFormatter.getFormattedSpeed(cachedSpeed, map);
        float right =
            paintBlack.measureText(cachedSpeedString) + 8 * scaleCoefficient + boundsForSpeed.left;
        boundsForSpeed.right = boundsForDist.right = Math.max(right, boundsForDist.right);
      }
      if (cachedSpeed > 0) {
        canvas.drawRoundRect(boundsForSpeed, roundCorner, roundCorner, paintAlphaGray);
        canvas.drawRoundRect(boundsForSpeed, roundCorner, roundCorner, paintBlack);
        canvas.drawText(
            cachedSpeedString,
            boundsForSpeed.left + 8 * scaleCoefficient,
            boundsForSpeed.bottom - 9f * scaleCoefficient,
            paintBlack);
      }
    }
    // draw distance to point
    if (cachedDistString != null) {
      canvas.drawRoundRect(boundsForDist, roundCorner, roundCorner, paintAlphaGray);
      canvas.drawRoundRect(boundsForDist, roundCorner, roundCorner, paintBlack);
      canvas.drawCircle(
          boundsForDist.left + 8 * scaleCoefficient,
          boundsForDist.bottom - 15 * scaleCoefficient,
          4 * scaleCoefficient,
          fillRed);
      canvas.drawText(
          cachedDistString,
          boundsForDist.left + 15 * scaleCoefficient,
          boundsForDist.bottom - 9f * scaleCoefficient,
          paintBlack);
    }

    // draw ruler
    drawRuler(canvas);

    // draw route information
    drawRouteInfo(canvas);

    // draw compass the last (!) because it use rotating
    canvas.drawRoundRect(boundsForCompass, roundCorner, roundCorner, paintAlphaGray);
    canvas.drawRoundRect(boundsForCompass, roundCorner, roundCorner, paintBlack);
    canvas.rotate(view.getRotate(), 15 * scaleCoefficient, 15 * scaleCoefficient);
    canvas.drawPath(pathForCompass2, fillRed);
    canvas.drawPath(pathForCompass, fillBlack);
  }
  public ArrayList<Direction> getDirectionsFromEdges(ArrayList<Edge> pathData) {
    if (pathData == null || pathData.size() == 0) return null;
    Node n;
    Edge edge;
    ArrayList<Direction> directions = new ArrayList<Direction>();
    int currentType = Edge.TYPE_WALK;
    Direction direction = null;

    int prevEdgeType = -1;
    String title = "";
    for (int i = 0; i < pathData.size(); i++) {
      try {
        edge = pathData.get(i);
        if (edge.getEdgeType() == Edge.TYPE_WAIT) {
          // special case: if the final destination is a bus/tram stop
          // we add a final indicator for destination node
          if (i == (pathData.size() - 1)) { // last edge. must display destination
            n = edge.getToNode();
            direction = new Direction(edge, "Reach destination at " + n.getTitle());
            directions.add(direction);
            direction.setFrom(edge.getFromNodeTitle());
            LogHelper.d("2359", "Edge: Direction added: " + "Reach destination at " + n.getTitle());
            break;
          }

          if (edge.getCostForEdge() > 0) title = edge.getFromNode().getTitle();
          continue;
        }

        if (i == 0) { // first edge. must display start point
          currentType = edge.getEdgeType();
          n = edge.getFromNode();
          if (n.getTitle() != null) title = n.getTitle();
          String descText = edge.getLineName();
          if (edge.getEdgeType() == Edge.TYPE_WALK) {
            if (edge.getCostForEdge() == Edge.DUMMY_EDGE_COST)
              descText = "Walk from your starting location";
            else descText = descText.replace("Alight", "Start").replace("#NODE_NAME#", title);
          } else {
            descText =
                descText
                    .replace("Board", "Start at " + title + " and board")
                    .replace("#NODE_NAME#", "");
          }
          direction = new Direction(edge, descText);
          directions.add(direction);
          direction.setFrom(edge.getFromNodeTitle());
          LogHelper.d("2359", "Edge: Direction added: " + descText);

        } else {
          if (edge.getEdgeType() != currentType) {
            // if there is a change in the type of edge
            currentType = edge.getEdgeType();
            n = edge.getFromNode();
            if (n.getTitle() != null) title = n.getTitle();
            String descText = edge.getLineName();
            if (prevEdgeType != Edge.TYPE_WALK && edge.getEdgeType() != Edge.TYPE_WALK)
              descText = descText.replace("Board", "Alight and change to");
            descText = descText.replace("#NODE_NAME#", title);
            direction = new Direction(edge, descText);
            directions.add(direction);
            direction.setFrom(edge.getFromNodeTitle());
            LogHelper.d("2359", "Edge: Direction added: " + descText);
          }
        }

        // add a final indicator for destination node
        if (i == (pathData.size() - 1)) { // last edge. must display destination
          n = edge.getToNode();
          direction = new Direction(edge, "Reach destination at " + n.getTitle());
          directions.add(direction);
          direction.setFrom(edge.getFromNodeTitle());
          LogHelper.d("2359", "Edge: Direction added: " + "Reach destination at " + n.getTitle());
        }

        prevEdgeType = edge.getEdgeType();

        float results[] = {0};
        Location.distanceBetween(
            edge.getFromNode().getLatE6() / 1E6,
            edge.getFromNode().getLongE6() / 1E6,
            edge.getToNode().getLatE6() / 1E6,
            edge.getToNode().getLongE6() / 1E6,
            results);

        LogHelper.d(
            "2359",
            "Edge: From:"
                + edge.getFromNodeTitle()
                + ", To: "
                + edge.getToNodeTitle()
                + ", Type: "
                + edge.getLineLabel()
                + ", Distance: "
                + results[0]
                + " m");
        if (direction != null) {
          direction.setDistance(direction.getDistance() + results[0]);
          direction.setTo(edge.getToNodeTitle());
          if (edge.getEdgeType() != Edge.TYPE_WAIT && edge.getEdgeType() != Edge.TYPE_WALK) {
            direction.setStops(direction.getStops() + 1);
          }
        }
      } catch (Exception ignore) {
        ignore.printStackTrace();
      }
    }
    return directions;
  }
示例#24
0
 private static double distanciaEnMetros(LatLng punto1, LatLng punto2) {
   float[] result = new float[1];
   Location.distanceBetween(
       punto1.latitude, punto1.longitude, punto2.latitude, punto2.longitude, result);
   return result[0];
 }
  public static boolean addLocation(Location location, Geocoder geocoder) {
    TrackingData ltd = getLastLocation();

    float distance = 0.0f;
    float speed = 0.0f;

    if (ltd != null) {
      float[] results = new float[1];
      Location.distanceBetween(
          ltd.getLatitude(),
          ltd.getLongitude(),
          location.getLatitude(),
          location.getLongitude(),
          results);

      distance = results[0];
      if (distance < 100) {
        log.debug("SKIP SAME " + location + ": " + distance);
        return false;
      }

      long delta = DateTimes.subSeconds(new Date(location.getTime()), ltd.getDate());
      // less than 30 minutes
      if (delta < 30 * 60) {
        speed = distance / delta;
        //				if (lastState == DetectedActivity.STILL) {
        //
        //				}
        // great than 120km/h
        if (speed >= 33) {
          log.debug("SKIP FAST " + location + ": " + distance);
          return false;
        }
      }
    }

    String address = "";
    try {
      List<Address> addresses =
          geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
      if (Collections.isNotEmpty(addresses)) {
        Address a = addresses.get(0);
        address = toAddress(a);
      }

      // if (ltd != null && Strings.isNotEmpty(address)) {
      // if (ltd.getAddress().equals(address)) {
      // log.debug("Skip (" + location + "): " + address);
      // return;
      // }
      // }
    } catch (Exception e) {
      // Catch network or other I/O problems.
      log.error(
          "Failed to get address of (" + location.getLatitude() + ", " + location.getLongitude(),
          e);
    }

    TrackingData td = new TrackingData();
    td.setDate(new Date(location.getTime()));
    td.setState(getBestState());
    td.setLatitude(location.getLatitude());
    td.setLongitude(location.getLongitude());
    td.setAddress(address);

    if (ltd != null) {
      float[] results = new float[1];
      Location.distanceBetween(
          ltd.getLatitude(), ltd.getLongitude(), td.getLatitude(), td.getLongitude(), results);
      td.setDistance(results[0]);
      td.setSpeed(td.getDistance() / DateTimes.subSeconds(td.getDate(), ltd.getDate()));
    }

    trackings.add(td);
    saveTrackingData(td);

    return true;
  }
示例#26
0
 /** 算出二点坐标距离差 */
 public float getTwoGeogeLength(double lat1, double lng1, double lat2, double lng2) {
   float[] result = new float[1];
   Location.distanceBetween(lat1, lng1, lat2, lng2, result);
   return result[0];
 }
 public boolean tooFarawayUPS() {
   float[] results = {0};
   Location.distanceBetween(latitude, longitude, latitudeUPS, longitudeUPS, results);
   if (results[0] < 1750) return false;
   return true;
 }