com.mapbox.geojson.LineString Java Examples

The following examples show how to use com.mapbox.geojson.LineString. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PolylineUtilsTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void testFromPolyline6() {

  List<Point> originalPath = Arrays.asList(
    Point.fromLngLat(2.2862036, 48.8267868),
    Point.fromLngLat(2.4, 48.9)
  );
  String encoded = encode(originalPath, PRECISION_6);
  List<Point> path = LineString.fromPolyline(encoded, PRECISION_6).coordinates();

  assertEquals(originalPath.size(), path.size());
  for (int i = 0; i < originalPath.size(); i++) {
    assertEquals(originalPath.get(i).latitude(), path.get(i).latitude(), DELTA);
    assertEquals(originalPath.get(i).longitude(), path.get(i).longitude(), DELTA);
  }
}
 
Example #2
Source File: NavigationLauncherActivity.java    From graphhopper-navigation-example with Apache License 2.0 6 votes vote down vote up
private void boundCameraToRoute() {
    if (route != null) {
        List<Point> routeCoords = LineString.fromPolyline(route.geometry(),
                Constants.PRECISION_6).coordinates();
        List<LatLng> bboxPoints = new ArrayList<>();
        for (Point point : routeCoords) {
            bboxPoints.add(new LatLng(point.latitude(), point.longitude()));
        }
        if (bboxPoints.size() > 1) {
            try {
                LatLngBounds bounds = new LatLngBounds.Builder().includes(bboxPoints).build();
                // left, top, right, bottom
                animateCameraBbox(bounds, CAMERA_ANIMATION_DURATION, padding);
            } catch (InvalidLatLngBoundsException exception) {
                Toast.makeText(this, R.string.error_valid_route_not_found, Toast.LENGTH_SHORT).show();
            }
        }
    }
}
 
Example #3
Source File: TurfMetaTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void coordAllGeometryCollection() throws TurfException {
  List<Point> points = new ArrayList<>();
  points.add(Point.fromLngLat(1.0, 2.0));
  points.add(Point.fromLngLat(2.0, 3.0));
  LineString lineString = LineString.fromLngLats(points);
  List<Geometry> geometries = new ArrayList<>();
  geometries.add(points.get(0));
  geometries.add(lineString);

  BoundingBox bbox = BoundingBox.fromLngLats(1.0, 2.0, 3.0, 4.0);
  GeometryCollection geometryCollection = GeometryCollection.fromGeometries(geometries, bbox);

  FeatureCollection featureCollection = FeatureCollection.fromFeature(
    Feature.fromGeometry(geometryCollection)
  );

  assertNotNull(featureCollection);
  assertNotNull(TurfMeta.coordAll(featureCollection,true));
  assertEquals(3, TurfMeta.coordAll(featureCollection,true).size());
  assertEquals(1.0, TurfMeta.coordAll(featureCollection,true).get(0).longitude(), DELTA);
  assertEquals(2.0, TurfMeta.coordAll(featureCollection,true).get(0).latitude(), DELTA);
}
 
Example #4
Source File: TurfConversionTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void combine_featureCollectionSizeCheck() throws Exception {
  FeatureCollection pointMultiPolygonAndLineStringFeatureCollection =
    FeatureCollection.fromFeatures(
      Arrays.asList(
        Feature.fromGeometry(Point.fromLngLat(-2.46, 27.6835)),
        Feature.fromGeometry(MultiPolygon.fromPolygons(Arrays.asList(
          Polygon.fromLngLats(Arrays.asList(Arrays.asList(
            Point.fromLngLat(11.42578125, 16.636191878397664),
            Point.fromLngLat(7.91015625, -9.102096738726443),
            Point.fromLngLat(31.113281249999996, 17.644022027872726),
            Point.fromLngLat(11.42578125, 16.636191878397664)
          )))))),
        Feature.fromGeometry(LineString.fromLngLats(
          Arrays.asList(Point.fromLngLat(-11.25, 55.7765),
            Point.fromLngLat(41.1328, 22.91792)))
        )));

  FeatureCollection combinedFeatureCollection = TurfConversion.combine(pointMultiPolygonAndLineStringFeatureCollection);
  assertNotNull(combinedFeatureCollection);
  assertEquals(3, combinedFeatureCollection.features().size());
}
 
Example #5
Source File: RouteStepProgressTest.java    From graphhopper-navigation-android with MIT License 6 votes vote down vote up
@Test
public void distanceRemaining_equalsStepDistanceAtBeginning() throws Exception {
  DirectionsRoute route = buildTestDirectionsRoute();
  RouteLeg firstLeg = route.legs().get(0);
  LineString lineString = LineString.fromPolyline(firstLeg.steps().get(5).geometry(), Constants.PRECISION_6);
  double stepDistance = TurfMeasurement.length(lineString, TurfConstants.UNIT_METERS);

  double stepDistanceRemaining = firstLeg.steps().get(5).distance();
  double legDistanceRemaining = firstLeg.distance();
  double distanceRemaining = route.distance();
  int stepIndex = 4;
  RouteProgress routeProgress = buildTestRouteProgress(route, stepDistanceRemaining,
    legDistanceRemaining, distanceRemaining, stepIndex, 0);
  RouteStepProgress routeStepProgress = routeProgress.currentLegProgress().currentStepProgress();

  assertEquals(stepDistance, routeStepProgress.distanceRemaining(), BaseTest.LARGE_DELTA);
}
 
Example #6
Source File: CircleContainer.java    From AirMapSDK-Android with Apache License 2.0 6 votes vote down vote up
public void move(LatLng center) {
    this.center = center;
    this.points = calculateCirclePoints(center, radius);

    List<Point> positions = latLngsToPositions(points);
    List<List<Point>> coordinates = new ArrayList<>();
    coordinates.add(positions);

    List<Point> lineString = new ArrayList<>(positions);
    lineString.add(positions.get(0));

    GeoJsonSource pointSource = map.getStyle().getSourceAs(POINT_SOURCE);
    pointSource.setGeoJson(Feature.fromGeometry(Point.fromLngLat(center.getLongitude(), center.getLatitude())));

    GeoJsonSource polygonSource = map.getStyle().getSourceAs(POLYGON_SOURCE);
    polygonSource.setGeoJson(Feature.fromGeometry(Polygon.fromLngLats(coordinates)));

    FillLayer polygonFill = map.getStyle().getLayerAs(Container.POLYGON_LAYER);
    polygonFill.setProperties(PropertyFactory.fillColor(ContextCompat.getColor(context, R.color.colorAccent)));

    GeoJsonSource polylineSource = map.getStyle().getSourceAs(POLYLINE_SOURCE);
    polylineSource.setGeoJson(Feature.fromGeometry(LineString.fromLngLats(lineString)));
}
 
Example #7
Source File: TurfMetaTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void coordAllFeatureCollection() throws TurfException {
  String multipolygonJson = "{type: 'MultiPolygon', coordinates: [[[[0, 0], [1, 1], [0, 1], [0, 0]]]]}";
  String lineStringJson = "{type: 'LineString', coordinates: [[0, 0], [1, 1]]}";
  FeatureCollection featureCollection = FeatureCollection.fromFeatures(
    new Feature[] {
      Feature.fromGeometry(MultiPolygon.fromJson(multipolygonJson)),
      Feature.fromGeometry(LineString.fromJson(lineStringJson))}
  );
  assertNotNull(featureCollection);
  assertEquals(5, TurfMeta.coordAll(featureCollection,true).size());
  assertEquals(0, TurfMeta.coordAll(featureCollection,true).get(0).latitude(), DELTA);
  assertEquals(0, TurfMeta.coordAll(featureCollection,true).get(0).longitude(), DELTA);
  assertEquals(1, TurfMeta.coordAll(featureCollection,true).get(4).latitude(), DELTA);
  assertEquals(1, TurfMeta.coordAll(featureCollection,true).get(4).longitude(), DELTA);
}
 
Example #8
Source File: TurfMeta.java    From mapbox-java with MIT License 6 votes vote down vote up
/**
 * Get all coordinates from a {@link FeatureCollection} object, returning a
 * {@code List} of {@link Point} objects.
 *
 * @param pointList        the {@code List} of {@link Point}s.
 * @param geometry         the {@link Geometry} object to extract the {@link Point}s from
 * @param excludeWrapCoord whether or not to include the final coordinate of LinearRings that
 *                         wraps the ring in its iteration. Used if the {@link Feature}
 *                         passed through the method is a {@link Polygon} or {@link MultiPolygon}
 *                         geometry.
 * @return a {@code List} made up of {@link Point}s
 * @since 4.8.0
 */
@NonNull
private static List<Point> coordAllFromSingleGeometry(@NonNull List<Point> pointList,
                                                      @NonNull Geometry geometry,
                                                      @NonNull boolean excludeWrapCoord) {
  if (geometry instanceof Point) {
    pointList.add((Point) geometry);
  } else if (geometry instanceof MultiPoint) {
    pointList.addAll(((MultiPoint) geometry).coordinates());
  } else if (geometry instanceof LineString) {
    pointList.addAll(((LineString) geometry).coordinates());
  } else if (geometry instanceof MultiLineString) {
    coordAll(pointList, (MultiLineString) geometry);
  } else if (geometry instanceof Polygon) {
    coordAll(pointList, (Polygon) geometry, excludeWrapCoord);
  } else if (geometry instanceof MultiPolygon) {
    coordAll(pointList, (MultiPolygon) geometry, excludeWrapCoord);
  } else if (geometry instanceof GeometryCollection) {
    // recursive
    for (Geometry singleGeometry : ((GeometryCollection) geometry).geometries()) {
      coordAllFromSingleGeometry(pointList, singleGeometry, excludeWrapCoord);
    }
  }
  return pointList;
}
 
Example #9
Source File: TurfMeasurementTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void bboxPolygonFromLineStringWithId() throws IOException, TurfException {
  // Create a LineString
  LineString lineString = LineString.fromJson(loadJsonFixture(TURF_BBOX_POLYGON_LINESTRING));

  // Use the LineString object to calculate its BoundingBox area
  double[] bbox = TurfMeasurement.bbox(lineString);

  // Use the BoundingBox coordinates to create an actual BoundingBox object
  BoundingBox boundingBox = BoundingBox.fromPoints(
    Point.fromLngLat(bbox[0], bbox[1]), Point.fromLngLat(bbox[2], bbox[3]));

  // Use the BoundingBox object in the TurfMeasurement.bboxPolygon() method.
  Feature featureRepresentingBoundingBox = TurfMeasurement.bboxPolygon(boundingBox, null, "TEST_ID");
  Polygon polygonRepresentingBoundingBox = (Polygon) featureRepresentingBoundingBox.geometry();

  assertNotNull(polygonRepresentingBoundingBox);
  assertEquals(0, polygonRepresentingBoundingBox.inner().size());
  assertEquals(5, polygonRepresentingBoundingBox.coordinates().get(0).size());
  assertEquals("TEST_ID", featureRepresentingBoundingBox.id());
  assertEquals(Point.fromLngLat(102.0, -10.0), polygonRepresentingBoundingBox.coordinates().get(0).get(0));
  assertEquals(Point.fromLngLat(130, -10.0), polygonRepresentingBoundingBox.coordinates().get(0).get(1));
  assertEquals(Point.fromLngLat(130.0, 4.0), polygonRepresentingBoundingBox.coordinates().get(0).get(2));
  assertEquals(Point.fromLngLat(102.0, 4.0), polygonRepresentingBoundingBox.coordinates().get(0).get(3));
  assertEquals(Point.fromLngLat(102.0, -10.0), polygonRepresentingBoundingBox.coordinates().get(0).get(4));
}
 
Example #10
Source File: TurfMeasurementTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void bboxPolygonFromLineString() throws IOException, TurfException {
  // Create a LineString
  LineString lineString = LineString.fromJson(loadJsonFixture(TURF_BBOX_POLYGON_LINESTRING));

  // Use the LineString object to calculate its BoundingBox area
  double[] bbox = TurfMeasurement.bbox(lineString);

  // Use the BoundingBox coordinates to create an actual BoundingBox object
  BoundingBox boundingBox = BoundingBox.fromPoints(
    Point.fromLngLat(bbox[0], bbox[1]), Point.fromLngLat(bbox[2], bbox[3]));

  // Use the BoundingBox object in the TurfMeasurement.bboxPolygon() method.
  Feature featureRepresentingBoundingBox = TurfMeasurement.bboxPolygon(boundingBox);

  Polygon polygonRepresentingBoundingBox = (Polygon) featureRepresentingBoundingBox.geometry();

  assertNotNull(polygonRepresentingBoundingBox);
  assertEquals(0, polygonRepresentingBoundingBox.inner().size());
  assertEquals(5, polygonRepresentingBoundingBox.coordinates().get(0).size());
  assertEquals(Point.fromLngLat(102.0, -10.0), polygonRepresentingBoundingBox.coordinates().get(0).get(0));
  assertEquals(Point.fromLngLat(130, -10.0), polygonRepresentingBoundingBox.coordinates().get(0).get(1));
  assertEquals(Point.fromLngLat(130.0, 4.0), polygonRepresentingBoundingBox.coordinates().get(0).get(2));
  assertEquals(Point.fromLngLat(102.0, 4.0), polygonRepresentingBoundingBox.coordinates().get(0).get(3));
  assertEquals(Point.fromLngLat(102.0, -10.0), polygonRepresentingBoundingBox.coordinates().get(0).get(4));
}
 
Example #11
Source File: SnapToRoute.java    From graphhopper-navigation-android with MIT License 6 votes vote down vote up
/**
 * Creates a snapped bearing for the snapped {@link Location}.
 * <p>
 * This is done by measuring 1 meter ahead of the current step distance traveled and
 * creating a {@link Point} with this distance using {@link TurfMeasurement#along(LineString, double, String)}.
 * <p>
 * If the step distance remaining is zero, the distance ahead is 1 meter into the upcoming step.
 * This way, an accurate bearing is upheld transitioning between steps.
 *
 * @param routeProgress for all current progress values
 * @return float bearing snapped to route
 */
private static float snapLocationBearing(RouteProgress routeProgress) {

  RouteLegProgress legProgress = routeProgress.currentLegProgress();
  RouteStepProgress stepProgress = legProgress.currentStepProgress();
  double distanceTraveled = stepProgress.distanceTraveled();
  double distanceRemaining = stepProgress.distanceRemaining();
  boolean distanceRemainingZero = distanceRemaining == 0;

  // Either want to measure our current step distance traveled + 1 or 1 meter into the upcoming step
  double distanceAhead = distanceRemainingZero ? 1 : distanceTraveled + 1;
  // Create the step linestring from the geometry
  LineString upcomingLineString = createUpcomingLineString(legProgress, distanceRemainingZero);
  LineString currentLineString = createCurrentLineString(legProgress);

  // Measure 1 meter ahead of the users current location, only if the distance remaining isn't zero
  Point futurePoint = createFuturePoint(distanceAhead, upcomingLineString, currentLineString);
  Point currentPoint = TurfMeasurement.along(currentLineString, distanceTraveled, TurfConstants.UNIT_METERS);

  // Get bearing and convert azimuth to degrees
  double azimuth = TurfMeasurement.bearing(currentPoint, futurePoint);
  return (float) MathUtils.wrap(azimuth, 0, 360);
}
 
Example #12
Source File: TurfMiscTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void testTurfLineSliceVertical() throws IOException, TurfException {
  Point start = Point.fromLngLat(-121.25447809696198, 38.70582415504791);
  Point stop = Point.fromLngLat(-121.25447809696198, 38.70634324369764);

  Feature vertical = Feature.fromJson(loadJsonFixture(LINE_SLICE_VERTICAL));

  LineString sliced = TurfMisc.lineSlice(start, stop, vertical);
  assertNotNull(sliced);

  // No duplicated coords
  assertEquals(2, sliced.coordinates().size());

  // Vertical slice does not collapse to 1st coord
  assertNotEquals(sliced.coordinates().get(0), sliced.coordinates().get(1));
}
 
Example #13
Source File: NavigationHelper.java    From graphhopper-navigation-android with MIT License 6 votes vote down vote up
/**
 * Creates a list of pairs {@link StepIntersection} and double distance in meters along a step.
 * <p>
 * Each pair represents an intersection on the given step and its distance along the step geometry.
 * <p>
 * The first intersection is the same point as the first point of the list of step points, so will
 * always be zero meters.
 *
 * @param stepPoints    representing the step geometry
 * @param intersections along the step to be measured
 * @return list of measured intersection pairs
 * @since 0.13.0
 */
@NonNull
public static List<Pair<StepIntersection, Double>> createDistancesToIntersections(List<Point> stepPoints,
                                                                           List<StepIntersection> intersections) {
  boolean lessThanTwoStepPoints = stepPoints.size() < TWO_POINTS;
  boolean noIntersections = intersections.isEmpty();
  if (lessThanTwoStepPoints || noIntersections) {
    return Collections.emptyList();
  }

  LineString stepLineString = LineString.fromLngLats(stepPoints);
  Point firstStepPoint = stepPoints.get(FIRST_POINT);
  List<Pair<StepIntersection, Double>> distancesToIntersections = new ArrayList<>();

  for (StepIntersection intersection : intersections) {
    Point intersectionPoint = intersection.location();
    if (firstStepPoint.equals(intersectionPoint)) {
      distancesToIntersections.add(new Pair<>(intersection, ZERO_METERS));
    } else {
      LineString beginningLineString = TurfMisc.lineSlice(firstStepPoint, intersectionPoint, stepLineString);
      double distanceToIntersectionInMeters = TurfMeasurement.length(beginningLineString, TurfConstants.UNIT_METERS);
      distancesToIntersections.add(new Pair<>(intersection, distanceToIntersectionInMeters));
    }
  }
  return distancesToIntersections;
}
 
Example #14
Source File: TurfMiscTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void testLineSliceAlongLine1() throws IOException, TurfException {
  Feature line1 = Feature.fromJson(loadJsonFixture(LINE_SLICE_ALONG_LINE_ONE));
  LineString lineStringLine1 = (LineString) line1.geometry();

  double start = 500;
  double stop = 750;

  Point start_point = TurfMeasurement.along(lineStringLine1, start, TurfConstants.UNIT_MILES);
  Point end_point = TurfMeasurement.along(lineStringLine1, stop, TurfConstants.UNIT_MILES);
  LineString sliced = TurfMisc.lineSliceAlong(line1, start, stop, TurfConstants.UNIT_MILES);

  assertEquals(sliced.coordinates().get(0).coordinates(),
    start_point.coordinates());
  assertEquals(sliced.coordinates().get(sliced.coordinates().size() - 1).coordinates(),
    end_point.coordinates());
}
 
Example #15
Source File: ShifterTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void linestring_basic_shift_with_bbox() {
  // set shifter
  CoordinateShifterManager.setCoordinateShifter(new TestCoordinateShifter());

  List<Point> points = new ArrayList<>();
  points.add(Point.fromLngLat(1.0, 1.0));
  points.add(Point.fromLngLat(2.0, 2.0));
  points.add(Point.fromLngLat(3.0, 3.0));
  BoundingBox bbox = BoundingBox.fromLngLats(1.0, 2.0, 3.0, 4.0);
  LineString lineString = LineString.fromLngLats(points, bbox);

  String jsonString = lineString.toJson();
  compareJson("{\"coordinates\":[[1,1],[2,2],[3,3]],"
                  + "\"type\":\"LineString\",\"bbox\":[1.0,2.0,3.0,4.0]}",
          jsonString);

  CoordinateShifterManager.setCoordinateShifter(null);
}
 
Example #16
Source File: TurfMiscTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
 public void testLineSliceAlongOvershootLine1() throws IOException, TurfException {
  Feature line1 = Feature.fromJson(loadJsonFixture(LINE_SLICE_ALONG_LINE_ONE));
  LineString lineStringLine1 = (LineString) line1.geometry();

  double start = 500;
  double stop = 1500;

  Point start_point = TurfMeasurement.along(lineStringLine1, start, TurfConstants.UNIT_MILES);
  Point end_point = TurfMeasurement.along(lineStringLine1, stop, TurfConstants.UNIT_MILES);
  LineString sliced = TurfMisc.lineSliceAlong(line1, start, stop, TurfConstants.UNIT_MILES);

  assertEquals(sliced.coordinates().get(0).coordinates(),
    start_point.coordinates());
  assertEquals(sliced.coordinates().get(sliced.coordinates().size() - 1).coordinates(),
    end_point.coordinates());
}
 
Example #17
Source File: TurfMiscTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void testLineSliceAlongRoute1() throws IOException, TurfException {
  Feature route1 = Feature.fromJson(loadJsonFixture(LINE_SLICE_ALONG_ROUTE_ONE));
  LineString lineStringRoute1 = (LineString)route1.geometry();

  double start = 500;
  double stop = 750;

  Point start_point = TurfMeasurement.along(lineStringRoute1, start, TurfConstants.UNIT_MILES);
  Point end_point = TurfMeasurement.along(lineStringRoute1, stop, TurfConstants.UNIT_MILES);

  LineString sliced = TurfMisc.lineSliceAlong(route1, start, stop, TurfConstants.UNIT_MILES);

  assertEquals(sliced.coordinates().get(0).coordinates(),
    start_point.coordinates());
  assertEquals(sliced.coordinates().get(sliced.coordinates().size() - 1).coordinates(),
    end_point.coordinates());
}
 
Example #18
Source File: NavigationLauncherActivity.java    From graphhopper-navigation-android with MIT License 6 votes vote down vote up
public void boundCameraToRoute() {
  if (route != null) {
    List<Point> routeCoords = LineString.fromPolyline(route.geometry(),
      Constants.PRECISION_6).coordinates();
    List<LatLng> bboxPoints = new ArrayList<>();
    for (Point point : routeCoords) {
      bboxPoints.add(new LatLng(point.latitude(), point.longitude()));
    }
    if (bboxPoints.size() > 1) {
      try {
        LatLngBounds bounds = new LatLngBounds.Builder().includes(bboxPoints).build();
        // left, top, right, bottom
        int topPadding = launchBtnFrame.getHeight() * 2;
        animateCameraBbox(bounds, CAMERA_ANIMATION_DURATION, new int[] {50, topPadding, 50, 100});
      } catch (InvalidLatLngBoundsException exception) {
        Toast.makeText(this, R.string.error_valid_route_not_found, Toast.LENGTH_SHORT).show();
      }
    }
  }
}
 
Example #19
Source File: RerouteActivity.java    From graphhopper-navigation-android with MIT License 6 votes vote down vote up
private void drawRoute(DirectionsRoute route) {
  List<LatLng> points = new ArrayList<>();
  List<Point> coords = LineString.fromPolyline(route.geometry(), Constants.PRECISION_6).coordinates();

  for (Point point : coords) {
    points.add(new LatLng(point.latitude(), point.longitude()));
  }

  if (!points.isEmpty()) {

    if (polyline != null) {
      mapboxMap.removePolyline(polyline);
    }

    // Draw polyline on map
    polyline = mapboxMap.addPolyline(new PolylineOptions()
      .addAll(points)
      .color(Color.parseColor("#4264fb"))
      .width(5));
  }
}
 
Example #20
Source File: TurfMiscTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void testLineSliceAlongRoute2() throws IOException, TurfException {

  Feature route2 = Feature.fromJson(loadJsonFixture(LINE_SLICE_ALONG_ROUTE_TWO));
  LineString lineStringRoute2 = (LineString)route2.geometry();
  double start = 25;
  double stop = 50;

  Point start_point = TurfMeasurement.along(lineStringRoute2, start, TurfConstants.UNIT_MILES);
  Point end_point = TurfMeasurement.along(lineStringRoute2, stop, TurfConstants.UNIT_MILES);
  LineString sliced = TurfMisc.lineSliceAlong(route2, start, stop, TurfConstants.UNIT_MILES);

  assertEquals(sliced.coordinates().get(0).coordinates(),
    start_point.coordinates());
  assertEquals(sliced.coordinates().get(sliced.coordinates().size() - 1).coordinates(),
    end_point.coordinates());
}
 
Example #21
Source File: TurfMiscTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Test
public void testShortLine() throws IOException, TurfException {

  // Distance between points is about 186 miles
  LineString lineStringLine1 = LineString.fromLngLats(Arrays.asList(
    Point.fromLngLat(113.99414062499999, 22.350075806124867),
    Point.fromLngLat(116.76269531249999, 23.241346102386135)));

  double start = 50;
  double stop =  100;

  Point start_point = TurfMeasurement.along(lineStringLine1, start, TurfConstants.UNIT_MILES);
  Point end_point = TurfMeasurement.along(lineStringLine1, stop, TurfConstants.UNIT_MILES);
  LineString sliced = TurfMisc.lineSliceAlong(lineStringLine1, start, stop, TurfConstants.UNIT_MILES);

  assertEquals(sliced.coordinates().get(0).coordinates(),
    start_point.coordinates());
  assertEquals(sliced.coordinates().get(sliced.coordinates().size() - 1).coordinates(),
    end_point.coordinates());
}
 
Example #22
Source File: NavigationMapRoute.java    From graphhopper-navigation-android with MIT License 6 votes vote down vote up
private List<Point> obtainArrowPointsFrom(RouteProgress routeProgress) {
  List<Point> reversedCurrent = new ArrayList<>(routeProgress.currentStepPoints());
  Collections.reverse(reversedCurrent);

  LineString arrowLineCurrent = LineString.fromLngLats(reversedCurrent);
  LineString arrowLineUpcoming = LineString.fromLngLats(routeProgress.upcomingStepPoints());

  LineString arrowCurrentSliced = TurfMisc.lineSliceAlong(arrowLineCurrent, 0, THIRTY, TurfConstants.UNIT_METERS);
  LineString arrowUpcomingSliced = TurfMisc.lineSliceAlong(arrowLineUpcoming, 0, THIRTY, TurfConstants.UNIT_METERS);

  Collections.reverse(arrowCurrentSliced.coordinates());

  List<Point> combined = new ArrayList<>();
  combined.addAll(arrowCurrentSliced.coordinates());
  combined.addAll(arrowUpcomingSliced.coordinates());
  return combined;
}
 
Example #23
Source File: TurfMiscTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Test
public void testTurfLineSliceRoute2() throws IOException, TurfException {
  Point start = Point.fromLngLat(-112.60660171508789, 45.96021963947196);
  Point stop = Point.fromLngLat(-111.97265625, 48.84302835299516);

  Feature route2 = Feature.fromJson(loadJsonFixture(LINE_SLICE_ROUTE_TWO));

  LineString sliced = TurfMisc.lineSlice(start, stop, route2);
  assertNotNull(sliced);
}
 
Example #24
Source File: TurfMeasurementTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Test
public void testLineDistanceWithGeometries() throws IOException, TurfException {
  Feature route1 = Feature.fromJson(loadJsonFixture(LINE_DISTANCE_ROUTE_ONE));
  Feature route2 = Feature.fromJson(loadJsonFixture(LINE_DISTANCE_ROUTE_TWO));
  assertEquals(202, Math.round(TurfMeasurement.length((LineString) route1.geometry(),
    TurfConstants.UNIT_MILES)));
  Assert.assertEquals(741.7787396994203,
    TurfMeasurement.length((LineString) route2.geometry(), TurfConstants.UNIT_KILOMETERS), DELTA);
}
 
Example #25
Source File: TurfMisc.java    From mapbox-java with MIT License 5 votes vote down vote up
/**
 * Takes a line, a start {@link Point}, and a stop point and returns the line in between those
 * points.
 *
 * @param startPt used for calculating the lineSlice
 * @param stopPt  used for calculating the lineSlice
 * @param line    geometry that should be sliced
 * @return a sliced {@link LineString}
 * @see <a href="http://turfjs.org/docs/#lineslice">Turf Line slice documentation</a>
 * @since 1.2.0
 */
@NonNull
public static LineString lineSlice(@NonNull Point startPt, @NonNull Point stopPt,
                                   @NonNull LineString line) {

  List<Point> coords = line.coordinates();

  if (coords.size() < 2) {
    throw new TurfException("Turf lineSlice requires a LineString made up of at least 2 "
      + "coordinates.");
  } else if (startPt.equals(stopPt)) {
    throw new TurfException("Start and stop points in Turf lineSlice cannot equal each other.");
  }

  Feature startVertex = nearestPointOnLine(startPt, coords);
  Feature stopVertex = nearestPointOnLine(stopPt, coords);
  List<Feature> ends = new ArrayList<>();
  if ((int) startVertex.getNumberProperty(INDEX_KEY)
    <= (int) stopVertex.getNumberProperty(INDEX_KEY)) {
    ends.add(startVertex);
    ends.add(stopVertex);
  } else {
    ends.add(stopVertex);
    ends.add(startVertex);
  }
  List<Point> points = new ArrayList<>();
  points.add((Point) ends.get(0).geometry());
  for (int i = (int) ends.get(0).getNumberProperty(INDEX_KEY) + 1;
       i < (int) ends.get(1).getNumberProperty(INDEX_KEY) + 1; i++) {
    points.add(coords.get(i));
  }
  points.add((Point) ends.get(1).geometry());
  return LineString.fromLngLats(points);
}
 
Example #26
Source File: TurfMetaTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Test
public void coordAllSingleFeature() throws TurfException {
  String lineStringJson = "{type: 'LineString', coordinates: [[0, 0], [1, 1]]}";
  FeatureCollection featureCollection = FeatureCollection.fromFeature(
    Feature.fromGeometry(LineString.fromJson(lineStringJson))
  );
  assertNotNull(featureCollection);
  assertEquals(2, TurfMeta.coordAll(featureCollection,true).size());
  assertEquals(0, TurfMeta.coordAll(featureCollection,true).get(0).latitude(), DELTA);
  assertEquals(0, TurfMeta.coordAll(featureCollection,true).get(0).longitude(), DELTA);
  assertEquals(1, TurfMeta.coordAll(featureCollection,true).get(1).latitude(), DELTA);
  assertEquals(1, TurfMeta.coordAll(featureCollection,true).get(1).longitude(), DELTA);
}
 
Example #27
Source File: TurfMetaTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Test
public void coordAllLineString() throws TurfException {
  String jsonLineString = "{type: 'LineString', coordinates: [[0, 0], [1, 1]]}";
  LineString lineStringGeometry = LineString.fromJson(jsonLineString);
  List<Point> resultList = TurfMeta.coordAll(lineStringGeometry);

  assertEquals(resultList.size(), 2, DELTA);
  assertEquals(resultList.get(0), Point.fromLngLat(0, 0));
  assertEquals(resultList.get(1), Point.fromLngLat(1, 1));
}
 
Example #28
Source File: TurfMeasurementTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Test
public void bboxFromLine() throws TurfException, IOException {
  LineString lineString = LineString.fromJson(loadJsonFixture(TURF_BBOX_LINESTRING));
  double[] bbox = TurfMeasurement.bbox(lineString);

  assertEquals(4, bbox.length);
  assertEquals(102, bbox[0], DELTA);
  assertEquals(-10, bbox[1], DELTA);
  assertEquals(130, bbox[2], DELTA);
  assertEquals(4, bbox[3], DELTA);
}
 
Example #29
Source File: TurfMeasurementTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Test
public void testTurfAlong() throws IOException, TurfException {
  Feature feature = Feature.fromJson(loadJsonFixture(TURF_ALONG_DC_LINE));
  LineString line = (LineString) feature.geometry();

  Point pt1 = TurfMeasurement.along(line, 1, "miles");
  Point pt2 = TurfMeasurement.along(line, 1.2, "miles");
  Point pt3 = TurfMeasurement.along(line, 1.4, "miles");
  Point pt4 = TurfMeasurement.along(line, 1.6, "miles");
  Point pt5 = TurfMeasurement.along(line, 1.8, "miles");
  Point pt6 = TurfMeasurement.along(line, 2, "miles");
  Point pt7 = TurfMeasurement.along(line, 100, "miles");
  Point pt8 = TurfMeasurement.along(line, 0, "miles");
  FeatureCollection fc = FeatureCollection.fromFeatures(new Feature[] {
    Feature.fromGeometry(pt1),
    Feature.fromGeometry(pt2),
    Feature.fromGeometry(pt3),
    Feature.fromGeometry(pt4),
    Feature.fromGeometry(pt5),
    Feature.fromGeometry(pt6),
    Feature.fromGeometry(pt7),
    Feature.fromGeometry(pt8)
  });

  for (Feature f : fc.features()) {
    assertNotNull(f);
    assertEquals("Feature", f.type());
    assertEquals("Point", f.geometry().type());
  }

  assertEquals(8, fc.features().size());
  assertEquals(((Point) fc.features().get(7).geometry()).longitude(), pt8.longitude(), DELTA);
  assertEquals(((Point) fc.features().get(7).geometry()).latitude(), pt8.latitude(), DELTA);
}
 
Example #30
Source File: TurfMeasurementTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Test
public void turfAlong_returnsZeroWhenRouteIsPoint() throws Exception {
  List<Point> coords = new ArrayList<>();
  coords.add(Point.fromLngLat(1.0, 1.0));

  LineString lineString = LineString.fromLngLats(coords);
  Point point = TurfMeasurement.along(lineString, 0, TurfConstants.UNIT_METERS);
  assertEquals(1.0, point.latitude(), DELTA);
  assertEquals(1.0, point.longitude(), DELTA);
}