public static List<Location> getPoints(File gpxFile) throws Exception {
    List<Location> points;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();

    FileInputStream fis = new FileInputStream(gpxFile);
    Document dom = builder.parse(fis);
    Element root = dom.getDocumentElement();
    NodeList items = root.getElementsByTagName("trkpt");

    points = new ArrayList<Location>();

    for (int j = 0; j < items.getLength(); j++) {
      Node item = items.item(j);
      NamedNodeMap attrs = item.getAttributes();
      NodeList props = item.getChildNodes();

      Location pt = new Location("test");

      pt.setLatitude(Double.parseDouble(attrs.getNamedItem("lat").getNodeValue()));
      pt.setLongitude(Double.parseDouble(attrs.getNamedItem("lon").getNodeValue()));

      for (int k = 0; k < props.getLength(); k++) {
        Node item2 = props.item(k);
        String name = item2.getNodeName();

        if (name.equalsIgnoreCase("ele")) {
          pt.setAltitude(Double.parseDouble(item2.getFirstChild().getNodeValue()));
        }
        if (name.equalsIgnoreCase("course")) {
          pt.setBearing(Float.parseFloat(item2.getFirstChild().getNodeValue()));
        }
        if (name.equalsIgnoreCase("speed")) {
          pt.setSpeed(Float.parseFloat(item2.getFirstChild().getNodeValue()));
        }
        if (name.equalsIgnoreCase("hdop")) {
          pt.setAccuracy(Float.parseFloat(item2.getFirstChild().getNodeValue()) * 5);
        }
        if (name.equalsIgnoreCase("time")) {
          pt.setTime((getDateFormatter().parse(item2.getFirstChild().getNodeValue())).getTime());
        }
      }

      for (int y = 0; y < props.getLength(); y++) {
        Node item3 = props.item(y);
        String name = item3.getNodeName();
        if (!name.equalsIgnoreCase("ele")) {
          continue;
        }
        pt.setAltitude(Double.parseDouble(item3.getFirstChild().getNodeValue()));
      }

      points.add(pt);
    }

    fis.close();

    return points;
  }
  /**
   * Fills a track point from a cursor.
   *
   * @param cursor the cursor pointing to a location.
   * @param indexes the cached track points indexes
   * @param location the track point
   */
  private void fillTrackPoint(Cursor cursor, CachedTrackPointsIndexes indexes, Location location) {
    location.reset();

    if (!cursor.isNull(indexes.longitudeIndex)) {
      location.setLongitude(((double) cursor.getInt(indexes.longitudeIndex)) / 1E6);
    }
    if (!cursor.isNull(indexes.latitudeIndex)) {
      location.setLatitude(((double) cursor.getInt(indexes.latitudeIndex)) / 1E6);
    }
    if (!cursor.isNull(indexes.timeIndex)) {
      location.setTime(cursor.getLong(indexes.timeIndex));
    }
    if (!cursor.isNull(indexes.altitudeIndex)) {
      location.setAltitude(cursor.getFloat(indexes.altitudeIndex));
    }
    if (!cursor.isNull(indexes.accuracyIndex)) {
      location.setAccuracy(cursor.getFloat(indexes.accuracyIndex));
    }
    if (!cursor.isNull(indexes.speedIndex)) {
      location.setSpeed(cursor.getFloat(indexes.speedIndex));
    }
    if (!cursor.isNull(indexes.bearingIndex)) {
      location.setBearing(cursor.getFloat(indexes.bearingIndex));
    }
    if (location instanceof MyTracksLocation && !cursor.isNull(indexes.sensorIndex)) {
      MyTracksLocation myTracksLocation = (MyTracksLocation) location;
      try {
        myTracksLocation.setSensorDataSet(
            SensorDataSet.parseFrom(cursor.getBlob(indexes.sensorIndex)));
      } catch (InvalidProtocolBufferException e) {
        Log.w(TAG, "Failed to parse sensor data.", e);
      }
    }
  }
  private void connectUsingOldApi() {
    Location lastKnownGpsLocation =
        mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
    Location lastKnownNetworkLocation =
        mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
    Location bestLastKnownLocation = mCurrentBestLocation;
    if (lastKnownGpsLocation != null
        && LocationUtil.isBetterLocation(lastKnownGpsLocation, bestLastKnownLocation)) {
      bestLastKnownLocation = lastKnownGpsLocation;
    }
    if (lastKnownNetworkLocation != null
        && LocationUtil.isBetterLocation(lastKnownNetworkLocation, bestLastKnownLocation)) {
      bestLastKnownLocation = lastKnownNetworkLocation;
    }
    mCurrentBestLocation = bestLastKnownLocation;

    if (mLocationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER)
        && mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
      mLocationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, FASTEST_INTERVAL_IN_MS, 0.0f, mGpsLocationListener);
    }
    if (mLocationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)
        && mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
      mLocationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, FASTEST_INTERVAL_IN_MS, 0.0f, mNetworkLocationListener);
    }
    if (bestLastKnownLocation != null) {
      Log.i(TAG, "Received last known location via old API: " + bestLastKnownLocation);
      if (mBearing != null) {
        bestLastKnownLocation.setBearing(mBearing);
      }
      mLocationCallback.handleNewLocation(bestLastKnownLocation);
    }
  }
Exemple #4
0
 public Location getLocation() {
   if (this.lat == 0 && this.lon == 0) {
     return null;
   }
   Location current = new Location("reverseGeocoded");
   current.setLatitude(this.lat);
   current.setLongitude(this.lon);
   current.setAccuracy(3333);
   current.setBearing(333);
   return current;
 }
 @Override
 public void onLocationChanged(Location location) {
   if (location == null) {
     return;
   }
   mCurrentBestLocation = location;
   if (mBearing != null) {
     mCurrentBestLocation.setBearing(mBearing);
   }
   mLocationCallback.handleNewLocation(mCurrentBestLocation);
 }
Exemple #6
0
 public static android.location.Location protoLocationToAndroidLocation(
     de.uvwxy.daisy.proto.Messages.Location protoLoc) {
   android.location.Location androidLoc = new android.location.Location(protoLoc.getProvider());
   androidLoc.setAccuracy((float) protoLoc.getAccuracy());
   androidLoc.setAltitude(protoLoc.getAltitude());
   androidLoc.setBearing((float) protoLoc.getBearing());
   androidLoc.setLatitude(protoLoc.getLatitude());
   androidLoc.setLongitude(protoLoc.getLongitude());
   androidLoc.setSpeed((float) protoLoc.getSpeed());
   androidLoc.setTime(protoLoc.getTime());
   return androidLoc;
 }
 private Location map(LatLng latLng1, float bearing) {
   Location location = new Location(PROVIDER);
   location.setLatitude(latLng1.lat);
   location.setLongitude(latLng1.lng);
   location.setAccuracy(3.0f);
   location.setTime(System.currentTimeMillis());
   location.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
   location.setBearing(bearing);
   location.setSpeed(13.4f);
   location.setAltitude(0d);
   return location;
 }
Exemple #8
0
  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {

    Log.i(MockService.TAG, "MockService onStartCommand.");
    mWorkThread = new HandlerThread("UpdateThread", Process.THREAD_PRIORITY_BACKGROUND);
    mWorkThread.start();

    // Get the Looper for the thread
    mUpdateLooper = mWorkThread.getLooper();
    locationHandler = new LocationHandler(mUpdateLooper);

    mManager = MyWindowManager.createInstance(MockService.this);

    lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    try {
      lm.addTestProvider(providerName, false, false, false, false, false, true, true, 0, 5);
      lm.setTestProviderEnabled(providerName, true);

    } catch (SecurityException e1) {
      Toast.makeText(this, e1.getMessage().toString(), Toast.LENGTH_LONG).show();
      e1.printStackTrace();
    }

    initFloatviews();

    mLocation = new Location(providerName);
    if (MainActivity.localLocation != null) {
      mLocation.setLatitude(MainActivity.localLocation.getLatitude());
      mLocation.setLongitude(MainActivity.localLocation.getLongitude());
      mLocation.setBearing(MainActivity.localLocation.getBearing());
    } else {
      mLocation.setLatitude(XIAMEN[1]);
      mLocation.setLongitude(XIAMEN[0]);
      mLocation.setBearing(0);
    }
    return super.onStartCommand(intent, flags, startId);
  }
  @SmallTest
  public void testPlacemarkXml_BasicInfo() {

    Kml22AnnotateHandler kmlHandler = new Kml22AnnotateHandler(null, null, null);
    Location loc = new Location("MOCK");
    loc.setLatitude(12.193);
    loc.setLongitude(19.111);
    loc.setAltitude(9001);
    loc.setBearing(91.88f);
    loc.setSpeed(188.44f);

    String actual = kmlHandler.GetPlacemarkXml("This is the annotation", loc);
    String expected =
        "<Placemark><name>This is the annotation</name><Point><coordinates>19.111,12.193,9001.0</coordinates></Point></Placemark>\n";

    assertEquals("Basic Placemark XML", expected, actual);
  }
  /** Tests {@link LocationMessageHandler#handleMessage}: Only bearing is transmitted. */
  public void testHandleMessage_BearingOnly() {
    // Configure Test
    location = false;
    bearing = true;
    speed = false;
    initFeatures();

    logicListenerMock.setBearing(42);

    // Run Test
    Location remoteLocation = new Location((String) null);
    remoteLocation.setBearing(42);
    runTest(remoteLocation);

    // Verify Test
    verifyFieldMocks();
  }
Exemple #11
0
    private Location nodeToLocation(NodeList nodeList, NodeList speedList, int i) {
      final Node node = nodeList.item(i);
      String lat = node.getAttributes().getNamedItem(TAG_LAT).getNodeValue();
      String lng = node.getAttributes().getNamedItem(TAG_LNG).getNodeValue();

      final Location location = new Location(MOCK_PROVIDER);
      location.setLatitude(Double.parseDouble(lat));
      location.setLongitude(Double.parseDouble(lng));
      location.setTime(System.currentTimeMillis());
      location.setSpeed(Float.parseFloat(speedList.item(i).getFirstChild().getNodeValue()));

      if (previous != null) {
        location.setBearing(previous.bearingTo(location));
      }

      previous = location;
      return location;
    }
  @SmallTest
  public void testTrackPointXml_NewTrackSegment() {

    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, true, 0, null);

    Location loc = new Location("MOCK");
    loc.setLatitude(12.193);
    loc.setLongitude(19.111);
    loc.setAltitude(9001);
    loc.setBearing(91.88f);
    loc.setSpeed(188.44f);

    String actual = writeHandler.GetTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected =
        "<trkseg><trkpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time>"
            + "<course>91.88</course><speed>188.44</speed><src>MOCK</src></trkpt>\n</trkseg></trk></gpx>";

    assertEquals("Trackpoint XML with a new segment", expected, actual);
  }
  private void ReadFile() {
    long ticks = 0;
    try {
      BufferedReader br = new BufferedReader(new FileReader(mFile));
      char[] buf = new char[(int) mFile.length()];
      br.read(buf, 0, (int) mFile.length());
      br.close();
      String text = String.copyValueOf(buf);

      String[] lines = text.split("\n");

      mCoords.clear();
      for (int i = 0; i < lines.length; i++) {
        String[] parts = lines[i].split(",");
        if (parts.length < 8) continue;

        if (parts[0].trim().equals("Date")) continue;

        Location location = new Location("File");
        int strength = 0;
        try {
          ticks = Long.parseLong(parts[1].trim());
          location.setTime(ticks);

          location.setLongitude(Double.parseDouble(parts[2].trim()));
          location.setLatitude(Double.parseDouble(parts[3].trim()));
          location.setAltitude(Double.parseDouble(parts[4].trim()));
          location.setAccuracy(Float.parseFloat(parts[5].trim()));
          location.setBearing(Float.parseFloat(parts[6].trim()));
          location.setSpeed(Float.parseFloat(parts[7].trim()));
          strength = Integer.parseInt(parts[8].trim());
        } catch (Exception e) {
          ErrorFile.WriteException(e, null);
        }

        mCoords.add(new GPSCoordinate(location, strength));
      }
    } catch (Exception e) {
      ErrorFile.WriteException(e, mContext);
    }
  }
 @Override
 public void onSensorChanged(SensorEvent event) {
   float rotationMatrix[] = new float[16];
   SensorManager.getRotationMatrixFromVector(rotationMatrix, event.values);
   float[] orientationValues = new float[3];
   readDisplayRotation();
   SensorManager.remapCoordinateSystem(rotationMatrix, mAxisX, mAxisY, rotationMatrix);
   SensorManager.getOrientation(rotationMatrix, orientationValues);
   double azimuth = Math.toDegrees(orientationValues[0]);
   // Azimuth values are now -180-180 (N=0), but once added to the location object
   // they become 0-360 (N=0).
   @SuppressLint("UseValueOf")
   Float newBearing = new Float(azimuth);
   if (mBearing == null || Math.abs(mBearing - newBearing) > MIN_BEARING_DIFF) {
     mBearing = newBearing;
     if (mCurrentBestLocation != null) {
       mCurrentBestLocation.setBearing(mBearing);
     }
     mLocationCallback.handleNewBearing(mBearing);
   }
 }
  @SmallTest
  public void testTrackPointXml_BundledGeoIdHeight() {

    Gpx10WriteHandler writeHandler = new Gpx10WriteHandler(null, null, null, true, 0, null);

    Location loc = new Location("MOCK");
    loc.setLatitude(12.193);
    loc.setLongitude(19.111);
    loc.setAltitude(9001);
    loc.setBearing(91.88f);
    loc.setSpeed(188.44f);
    Bundle b = new Bundle();
    b.putString("GEOIDHEIGHT", "MYGEOIDHEIGHT");
    loc.setExtras(b);

    String actual = writeHandler.GetTrackPointXml(loc, "2011-09-17T18:45:33Z");
    String expected =
        "<trkseg><trkpt lat=\"12.193\" lon=\"19.111\"><ele>9001.0</ele><time>2011-09-17T18:45:33Z</time>"
            + "<course>91.88</course><speed>188.44</speed><src>MOCK</src><geoidheight>MYGEOIDHEIGHT</geoidheight></trkpt>\n</trkseg></trk></gpx>";

    assertEquals("Trackpoint XML with a geoid height", expected, actual);
  }
  @Override
  public void onConnected(Bundle bundle) {
    Log.i(TAG, "Connected to location services");

    LocationAvailability locationAvailability =
        mFusedLocationProviderApi.getLocationAvailability(mGoogleApiClient);
    if (!locationAvailability.isLocationAvailable()) {
      mLocationCallback.handleLocationNotAvailable();
      return;
    }

    Location lastKnownLocation = mFusedLocationProviderApi.getLastLocation(mGoogleApiClient);
    mFusedLocationProviderApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    if (lastKnownLocation != null) {
      Log.i(TAG, "Received last known location: " + lastKnownLocation);
      mCurrentBestLocation = lastKnownLocation;
      if (mBearing != null) {
        mCurrentBestLocation.setBearing(mBearing);
      }
      mLocationCallback.handleNewLocation(mCurrentBestLocation);
    }
  }
  /** Tests {@link LocationMessageHandler#handleMessage}: Everything is transmitted. */
  public void testHandleMessage_All() {
    // Configure Test
    location = true;
    bearing = true;
    speed = true;
    initFeatures();
    initMyLocation();

    // Looking from myLocation to remoteLocation:
    // 42,45 +-0,1 km distance, -2° +-1 bearing
    logicListenerMock.setDistance(AndroidMock.eq(42.45f * 1000, 100), AndroidMock.eq(-2f, 1f));
    logicListenerMock.setBearing(45);
    logicListenerMock.setSpeed(10);

    // Run Test
    Location remoteLocation = new Location((String) null);
    setLatLong(remoteLocation);
    remoteLocation.setBearing(45);
    remoteLocation.setSpeed(10);
    runTest(remoteLocation);

    // Verify Test
    verifyFieldMocks();
  }
  @Override
  public Waypoint createWaypoint(Cursor cursor) {
    int idIndex = cursor.getColumnIndexOrThrow(WaypointsColumns._ID);
    int nameIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.NAME);
    int descriptionIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.DESCRIPTION);
    int categoryIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.CATEGORY);
    int iconIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.ICON);
    int trackIdIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.TRACKID);
    int typeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.TYPE);
    int lengthIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.LENGTH);
    int durationIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.DURATION);
    int startTimeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTTIME);
    int startIdIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.STARTID);
    int stopIdIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.STOPID);
    int longitudeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.LONGITUDE);
    int latitudeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.LATITUDE);
    int timeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.TIME);
    int altitudeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.ALTITUDE);
    int accuracyIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.ACCURACY);
    int speedIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.SPEED);
    int bearingIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.BEARING);
    int totalDistanceIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALDISTANCE);
    int totalTimeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.TOTALTIME);
    int movingTimeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MOVINGTIME);
    int maxSpeedIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXSPEED);
    int minElevationIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MINELEVATION);
    int maxElevationIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXELEVATION);
    int elevationGainIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.ELEVATIONGAIN);
    int minGradeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MINGRADE);
    int maxGradeIndex = cursor.getColumnIndexOrThrow(WaypointsColumns.MAXGRADE);

    Waypoint waypoint = new Waypoint();

    if (!cursor.isNull(idIndex)) {
      waypoint.setId(cursor.getLong(idIndex));
    }
    if (!cursor.isNull(nameIndex)) {
      waypoint.setName(cursor.getString(nameIndex));
    }
    if (!cursor.isNull(descriptionIndex)) {
      waypoint.setDescription(cursor.getString(descriptionIndex));
    }
    if (!cursor.isNull(categoryIndex)) {
      waypoint.setCategory(cursor.getString(categoryIndex));
    }
    if (!cursor.isNull(iconIndex)) {
      waypoint.setIcon(cursor.getString(iconIndex));
    }
    if (!cursor.isNull(trackIdIndex)) {
      waypoint.setTrackId(cursor.getLong(trackIdIndex));
    }
    if (!cursor.isNull(typeIndex)) {
      waypoint.setType(cursor.getInt(typeIndex));
    }
    if (!cursor.isNull(lengthIndex)) {
      waypoint.setLength(cursor.getFloat(lengthIndex));
    }
    if (!cursor.isNull(durationIndex)) {
      waypoint.setDuration(cursor.getLong(durationIndex));
    }
    if (!cursor.isNull(startIdIndex)) {
      waypoint.setStartId(cursor.getLong(startIdIndex));
    }
    if (!cursor.isNull(stopIdIndex)) {
      waypoint.setStopId(cursor.getLong(stopIdIndex));
    }

    Location location = new Location("");
    if (!cursor.isNull(longitudeIndex) && !cursor.isNull(latitudeIndex)) {
      location.setLongitude(((double) cursor.getInt(longitudeIndex)) / 1E6);
      location.setLatitude(((double) cursor.getInt(latitudeIndex)) / 1E6);
    }
    if (!cursor.isNull(timeIndex)) {
      location.setTime(cursor.getLong(timeIndex));
    }
    if (!cursor.isNull(altitudeIndex)) {
      location.setAltitude(cursor.getFloat(altitudeIndex));
    }
    if (!cursor.isNull(accuracyIndex)) {
      location.setAccuracy(cursor.getFloat(accuracyIndex));
    }
    if (!cursor.isNull(speedIndex)) {
      location.setSpeed(cursor.getFloat(speedIndex));
    }
    if (!cursor.isNull(bearingIndex)) {
      location.setBearing(cursor.getFloat(bearingIndex));
    }
    waypoint.setLocation(location);

    TripStatistics tripStatistics = new TripStatistics();
    boolean hasTripStatistics = false;
    if (!cursor.isNull(startTimeIndex)) {
      tripStatistics.setStartTime(cursor.getLong(startTimeIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(totalDistanceIndex)) {
      tripStatistics.setTotalDistance(cursor.getFloat(totalDistanceIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(totalTimeIndex)) {
      tripStatistics.setTotalTime(cursor.getLong(totalTimeIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(movingTimeIndex)) {
      tripStatistics.setMovingTime(cursor.getLong(movingTimeIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(maxSpeedIndex)) {
      tripStatistics.setMaxSpeed(cursor.getFloat(maxSpeedIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(minElevationIndex)) {
      tripStatistics.setMinElevation(cursor.getFloat(minElevationIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(maxElevationIndex)) {
      tripStatistics.setMaxElevation(cursor.getFloat(maxElevationIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(elevationGainIndex)) {
      tripStatistics.setTotalElevationGain(cursor.getFloat(elevationGainIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(minGradeIndex)) {
      tripStatistics.setMinGrade(cursor.getFloat(minGradeIndex));
      hasTripStatistics = true;
    }
    if (!cursor.isNull(maxGradeIndex)) {
      tripStatistics.setMaxGrade(cursor.getFloat(maxGradeIndex));
      hasTripStatistics = true;
    }

    if (hasTripStatistics) {
      waypoint.setTripStatistics(tripStatistics);
    }
    return waypoint;
  }
  /**
   * (non-Javadoc)
   *
   * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
   */
  @Override
  public Uri insert(Uri uri, ContentValues values) {
    // Log.d( TAG, "insert on "+uri );
    Uri insertedUri = null;
    int match = GPStrackingProvider.sURIMatcher.match(uri);
    List<String> pathSegments = null;
    long trackId;
    long segmentId;
    long waypointId = -1;
    switch (match) {
      case WAYPOINTS:
        pathSegments = uri.getPathSegments();
        trackId = Integer.parseInt(pathSegments.get(1));
        segmentId = Integer.parseInt(pathSegments.get(3));

        Location loc = new Location(TAG);

        Double latitude = values.getAsDouble(Waypoints.LATITUDE);
        Double longitude = values.getAsDouble(Waypoints.LONGITUDE);
        Long time = values.getAsLong(Waypoints.TIME);
        Float speed = values.getAsFloat(Waypoints.SPEED);
        if (time == null) {
          time = System.currentTimeMillis();
        }
        if (speed == null) {
          speed = 0f;
        }
        loc.setLatitude(latitude);
        loc.setLongitude(longitude);
        loc.setTime(time);
        loc.setSpeed(speed);

        if (values.containsKey(Waypoints.ACCURACY)) {
          loc.setAccuracy(values.getAsFloat(Waypoints.ACCURACY));
        }
        if (values.containsKey(Waypoints.ALTITUDE)) {
          loc.setAltitude(values.getAsDouble(Waypoints.ALTITUDE));
        }
        if (values.containsKey(Waypoints.BEARING)) {
          loc.setBearing(values.getAsFloat(Waypoints.BEARING));
        }
        waypointId = this.mDbHelper.insertWaypoint(trackId, segmentId, loc);
        //            Log.d( TAG, "Have inserted to segment "+segmentId+" with waypoint "+waypointId
        // );
        insertedUri = ContentUris.withAppendedId(uri, waypointId);
        break;
      case SEGMENTS:
        pathSegments = uri.getPathSegments();
        trackId = Integer.parseInt(pathSegments.get(1));
        segmentId = this.mDbHelper.toNextSegment(trackId);
        insertedUri = ContentUris.withAppendedId(uri, segmentId);
        break;
      case TRACKS:
        String name = (values == null) ? "" : values.getAsString(Tracks.NAME);
        trackId = this.mDbHelper.toNextTrack(name);
        insertedUri = ContentUris.withAppendedId(uri, trackId);
        break;
      default:
        Log.e(GPStrackingProvider.LOG_TAG, "Unable to match the URI:" + uri.toString());
        insertedUri = null;
        break;
    }
    return insertedUri;
  }
Exemple #20
0
  public void mockGpsPoint(int diretion) {

    // 1.将基点坐标转化为UTM坐标;
    String utmLatlon = ConverUtil.latLon2UTM(mLocation.getLatitude(), mLocation.getLongitude());
    int[] xy = UTM2Xy(utmLatlon);

    // 2.将UTM坐标向指定方向偏移;
    x = xy[0];
    y = xy[1];
    if (diretion == TO_LEFT) {
      bearing -= 15;
    } else if (diretion == TO_RIGHT) {
      bearing += 15;
    } else if (diretion == TO_TOP) {
      // 处理前进算法
      double sin = Math.sin(Math.PI * bearing / 180.0);
      double cos = Math.cos(Math.PI * bearing / 180.0);
      int x_dis = (int) (dis_array[mManager.current_Gear] * sin);
      int y_dis = (int) (dis_array[mManager.current_Gear] * cos);
      x += x_dis;
      y += y_dis;
      Log.i(
          MockService.TAG,
          "Math bearing="
              + bearing
              + ",sin="
              + sin
              + ",cos="
              + cos
              + ", x_dis="
              + x_dis
              + ",y_dis="
              + y_dis);
    }

    // 3.将偏移后的UTM坐标转为经纬度坐标;
    String str = "50 R " + x + " " + y;
    double[] latlon = ConverUtil.utm2LatLon(str);
    Log.i(
        MockService.TAG,
        "utmLatlon="
            + utmLatlon
            + ",getLatitude="
            + mLocation.getLatitude()
            + ",getLongitude="
            + mLocation.getLongitude());

    /*同一个经纬度,经纬度转UTM,UTM转经纬度,经纬度再转UTM后,y总是会减1,该算法有误差
    Log.i(MockService.TAG, "utmLatlon1="+str+",latlon1="+latlon[0]+",latlon2="+latlon[1]);
    String utmLatlon0 = ConverUtil.latLon2UTM(latlon[0], latlon[1]);
    int[] xy0 = UTM2Xy(utmLatlon0);
    String str0 = "50 R "+ xy0[0] + " " + xy0[1];
    double[] latlon0 = ConverUtil.utm2LatLon(str0);
    Log.i(MockService.TAG, "utmLatlon2="+utmLatlon0+",latlon2="+latlon0[0]+",latlon2="+latlon0[1]);*/

    mLocation.setLatitude(latlon[0]);
    mLocation.setLongitude(latlon[1]);
    mLocation.setBearing(bearing);
    mLocation.setAccuracy(70);
    mLocation.setSpeed(dis_array[mManager.current_Gear] / 1); // 每秒移动dis_array[i]的距离
    mLocation.setTime(System.currentTimeMillis());

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
      // 没有设该时间,高德地图不会移动
      mLocation.setElapsedRealtimeNanos(SystemClock.elapsedRealtimeNanos());
    }
    try {
      lm.setTestProviderLocation(providerName, mLocation);
    } catch (SecurityException e) {
      Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG);
      e.printStackTrace();
    }
  }
  /** called from native code to update our position. */
  private void reportLocation(
      int flags,
      double latitude,
      double longitude,
      double altitude,
      float speed,
      float bearing,
      float accuracy,
      long timestamp) {
    if (VERBOSE)
      Log.v(
          TAG,
          "reportLocation lat: " + latitude + " long: " + longitude + " timestamp: " + timestamp);

    mLastFixTime = System.currentTimeMillis();
    // report time to first fix
    if (mTTFF == 0 && (flags & LOCATION_HAS_LAT_LONG) == LOCATION_HAS_LAT_LONG) {
      mTTFF = (int) (mLastFixTime - mFixRequestTime);
      if (DEBUG) Log.d(TAG, "TTFF: " + mTTFF);

      // notify status listeners
      synchronized (mListeners) {
        int size = mListeners.size();
        for (int i = 0; i < size; i++) {
          Listener listener = mListeners.get(i);
          try {
            listener.mListener.onFirstFix(mTTFF);
          } catch (RemoteException e) {
            Log.w(TAG, "RemoteException in stopNavigating");
            mListeners.remove(listener);
            // adjust for size of list changing
            size--;
          }
        }
      }
    }

    synchronized (mLocation) {
      mLocationFlags = flags;
      if ((flags & LOCATION_HAS_LAT_LONG) == LOCATION_HAS_LAT_LONG) {
        mLocation.setLatitude(latitude);
        mLocation.setLongitude(longitude);
        mLocation.setTime(timestamp);
      }
      if ((flags & LOCATION_HAS_ALTITUDE) == LOCATION_HAS_ALTITUDE) {
        mLocation.setAltitude(altitude);
      } else {
        mLocation.removeAltitude();
      }
      if ((flags & LOCATION_HAS_SPEED) == LOCATION_HAS_SPEED) {
        mLocation.setSpeed(speed);
      } else {
        mLocation.removeSpeed();
      }
      if ((flags & LOCATION_HAS_BEARING) == LOCATION_HAS_BEARING) {
        mLocation.setBearing(bearing);
      } else {
        mLocation.removeBearing();
      }
      if ((flags & LOCATION_HAS_ACCURACY) == LOCATION_HAS_ACCURACY) {
        mLocation.setAccuracy(accuracy);
      } else {
        mLocation.removeAccuracy();
      }

      try {
        mLocationManager.reportLocation(mLocation, false);
      } catch (RemoteException e) {
        Log.e(TAG, "RemoteException calling reportLocation");
      }
    }

    if (mStarted && mStatus != LocationProvider.AVAILABLE) {
      // we still want to time out if we do not receive MIN_FIX_COUNT
      // within the time out and we are requesting infrequent fixes
      if (mFixInterval < NO_FIX_TIMEOUT) {
        mAlarmManager.cancel(mTimeoutIntent);
      }

      // send an intent to notify that the GPS is receiving fixes.
      Intent intent = new Intent(GPS_FIX_CHANGE_ACTION);
      intent.putExtra(EXTRA_ENABLED, true);
      mContext.sendBroadcast(intent);
      updateStatus(LocationProvider.AVAILABLE, mSvCount);
    }

    if (mFixCount++ >= MIN_FIX_COUNT && mFixInterval > 1) {
      if (DEBUG) Log.d(TAG, "exceeded MIN_FIX_COUNT");
      hibernate();
    }
  }