Java Code Examples for com.mapbox.geojson.LineString#fromLngLats()

The following examples show how to use com.mapbox.geojson.LineString#fromLngLats() . These examples are extracted from open source projects. 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
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 2
/**
 * 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 3
Source Project: mapbox-java   File: TurfMetaTest.java    License: 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 Project: mapbox-java   File: TurfMiscTest.java    License: 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 5
Source Project: mapbox-java   File: ShifterTest.java    License: 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 6
@NonNull
private LineString obtainRoute(Point point, Location lastLocation) {
  List<Point> pointList = new ArrayList<>();
  pointList.add(Point.fromLngLat(lastLocation.getLongitude(), lastLocation.getLatitude()));
  pointList.add(point);
  return LineString.fromLngLats(pointList);
}
 
Example 7
Source Project: mapbox-java   File: TurfConversion.java    License: MIT License 5 votes vote down vote up
@Nullable
private static Feature coordsToLine(@NonNull List<List<Point>> coordinates,
                                    @Nullable JsonObject properties) {
  if (coordinates.size() > 1) {
    return Feature.fromGeometry(MultiLineString.fromLngLats(coordinates), properties);
  } else if (coordinates.size() == 1) {
    LineString lineString = LineString.fromLngLats(coordinates.get(0));
    return Feature.fromGeometry(lineString, properties);
  }
  return null;
}
 
Example 8
Source Project: mapbox-java   File: TurfMisc.java    License: 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 9
Source Project: mapbox-java   File: TurfMeasurementTest.java    License: MIT License 5 votes vote down vote up
@Test
public void lineDistance_returnsZeroWhenRouteIsPoint() throws Exception {
  List<Point> coords = new ArrayList<>();
  coords.add(Point.fromLngLat(1.0, 1.0));

  LineString lineString = LineString.fromLngLats(coords);
  double distance = TurfMeasurement.length(lineString, TurfConstants.UNIT_METERS);
  assertEquals(0d, distance, DELTA);
}
 
Example 10
Source Project: mapbox-java   File: TurfMeasurementTest.java    License: 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);
}
 
Example 11
Source Project: mapbox-java   File: TurfMiscTest.java    License: MIT License 5 votes vote down vote up
@Test
public void lineSlice_throwsStartStopPointException() throws Exception {
  thrown.expect(TurfException.class);
  thrown.expectMessage(startsWith("Turf lineSlice requires a LineString made up of at least 2 "
    + "coordinates."));

  List<Point> coords = new ArrayList<>();
  coords.add(Point.fromLngLat(1.0, 1.0));
  Point point = Point.fromLngLat(1.0, 1.0);
  Point point2 = Point.fromLngLat(2.0, 2.0);
  LineString lineString = LineString.fromLngLats(coords);
  TurfMisc.lineSlice(point, point2, lineString);
}
 
Example 12
Source Project: mapbox-java   File: TurfMiscTest.java    License: MIT License 5 votes vote down vote up
@Test
public void lineSlice_throwLineMustContainTwoOrMorePoints() throws Exception {
  thrown.expect(TurfException.class);
  thrown.expectMessage(startsWith("Start and stop points in Turf lineSlice cannot equal each "
    + "other."));

  List<Point> coords = new ArrayList<>();
  coords.add(Point.fromLngLat(1.0, 1.0));
  coords.add(Point.fromLngLat(2.0, 2.0));
  Point point = Point.fromLngLat(1.0, 1.0);
  LineString lineString = LineString.fromLngLats(coords);
  TurfMisc.lineSlice(point, point, lineString);
}
 
Example 13
Source Project: mapbox-java   File: TurfMiscTest.java    License: MIT License 5 votes vote down vote up
@Test
public void lineSlice_returnsEmptyLineStringRatherThanNull() throws Exception {
  List<Point> coords = new ArrayList<>();
  coords.add(Point.fromLngLat(1.0, 1.0));
  coords.add(Point.fromLngLat(2.0, 2.0));
  LineString lineString = LineString.fromLngLats(coords);
  assertNotNull(TurfMisc.lineSlice(coords.get(0), coords.get(1), lineString));
}
 
Example 14
Source Project: mapbox-java   File: TurfMiscTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testTurfLineSliceLine2() throws TurfException {
  Point start = Point.fromLngLat(0, 0.1);
  Point stop = Point.fromLngLat(.9, .8);

  ArrayList<Point> coordinates = new ArrayList<>();
  coordinates.add(Point.fromLngLat(0, 0));
  coordinates.add(Point.fromLngLat(1, 1));
  LineString line2 = LineString.fromLngLats(coordinates);

  LineString sliced = TurfMisc.lineSlice(start, stop, line2);
  assertNotNull(sliced);
}
 
Example 15
private void updateArrowShaftWith(List<Point> points) {
  LineString shaft = LineString.fromLngLats(points);
  arrowShaftGeoJsonFeature = Feature.fromGeometry(shaft);
  arrowShaftGeoJsonSource.setGeoJson(arrowShaftGeoJsonFeature);
}
 
Example 16
/**
 * Checks to see if the current point is moving away from the maneuver.
 * <p>
 * If the current point is farther away from the maneuver than the last point in the
 * stack, add it to the stack.
 * <p>
 * If the stack if >= 3 distances, return true to fire an off-route event as it
 * can be considered that the user is no longer going in the right direction.
 *
 * @param routeProgress             for the upcoming step maneuver
 * @param distancesAwayFromManeuver current stack of distances away
 * @param stepPoints                current step points being traveled along
 * @param currentPoint              to determine if moving away or not
 * @return true if moving away from maneuver, false if not
 */
private static boolean movingAwayFromManeuver(RouteProgress routeProgress,
                                              RingBuffer<Integer> distancesAwayFromManeuver,
                                              List<Point> stepPoints,
                                              Point currentPoint) {
  boolean invalidUpcomingStep = routeProgress.currentLegProgress().upComingStep() == null;
  boolean invalidStepPointSize = stepPoints.size() < TWO_POINTS;
  if (invalidUpcomingStep || invalidStepPointSize) {
    return false;
  }

  LineString stepLineString = LineString.fromLngLats(stepPoints);
  Point maneuverPoint = stepPoints.get(stepPoints.size() - 1);
  Point userPointOnStep = (Point) TurfMisc.nearestPointOnLine(currentPoint, stepPoints).geometry();

  if (userPointOnStep == null || maneuverPoint.equals(userPointOnStep)) {
    return false;
  }

  LineString remainingStepLineString = TurfMisc.lineSlice(userPointOnStep, maneuverPoint, stepLineString);
  double userDistanceToManeuver = TurfMeasurement.length(remainingStepLineString, TurfConstants.UNIT_METERS);

  boolean hasDistances = !distancesAwayFromManeuver.isEmpty();
  boolean validOffRouteDistanceTraveled = hasDistances && distancesAwayFromManeuver.peekLast()
    - distancesAwayFromManeuver.peekFirst() < MINIMUM_BACKUP_DISTANCE_FOR_OFF_ROUTE;
  boolean exceedsManeuverDistancesThreshold = validOffRouteDistanceTraveled
    && distancesAwayFromManeuver.size() >= 3;

  if (exceedsManeuverDistancesThreshold) {
    // User's moving away from maneuver position, thus offRoute.
    return true;
  }
  if (distancesAwayFromManeuver.isEmpty()) {
    distancesAwayFromManeuver.push((int) userDistanceToManeuver);
  } else if (userDistanceToManeuver > distancesAwayFromManeuver.peek()) {
    distancesAwayFromManeuver.push((int) userDistanceToManeuver);
  } else {
    // If we get a descending distance, reset the counter
    distancesAwayFromManeuver.clear();
  }
  return false;
}
 
Example 17
public void updateSource(int chatId,
                          int contactId,
                          long startTimestamp,
                          long endTimestamp) {
    DcArray locations = dcContext.getLocations(chatId, contactId, startTimestamp, endTimestamp);

    MapSource contactMapMetadata = contactMapSources.get(contactId);
    if (contactMapMetadata == null) {
        contactMapMetadata = addContactMapSource(contactMapSources, contactId);
    }
    int count = locations.getCnt();

    LinkedList<Feature> sortedPointFeatures = featureCollections.get(contactMapMetadata.getMarkerFeatureCollection());
    if (sortedPointFeatures != null && sortedPointFeatures.size() == count) {
        return;
    } else {
        sortedPointFeatures = new LinkedList<>();
    }
    LinkedList<Feature> sortedLineFeatures = new LinkedList<>();

    for (int i = count - 1; i >= 0; i--) {
        Point point = Point.fromLngLat(locations.getLongitude(i), locations.getLatitude(i));

        String codepointChar =
                locations.getMarker(i) != null ?
                        locations.getMarker(i) :
                        "";
        boolean isPoi = locations.isIndependent(i);
        int messageId = locations.getMsgId(i);

        Feature pointFeature = Feature.fromGeometry(point, new JsonObject(), String.valueOf(locations.getLocationId(i)));
        pointFeature.addBooleanProperty(MARKER_SELECTED, false);
        pointFeature.addBooleanProperty(LAST_LOCATION, false);
        pointFeature.addNumberProperty(CONTACT_ID, contactId);
        pointFeature.addNumberProperty(TIMESTAMP, locations.getTimestamp(i));
        pointFeature.addNumberProperty(MESSAGE_ID, messageId);
        pointFeature.addNumberProperty(ACCURACY, locations.getAccuracy(i));
        pointFeature.addStringProperty(MARKER_CHAR, codepointChar);
        pointFeature.addStringProperty(MARKER_ICON, isPoi ?
                contactMapMetadata.getMarkerPoi() :
                contactMapMetadata.getMarkerIcon());
        pointFeature.addBooleanProperty(IS_POI, isPoi);
        if (isPoi && codepointChar.length() == 0 && messageId != 0) {
            //has a long poi label
            DcMsg poiMsg = dcContext.getMsg(messageId);
            String poiLongDescription = poiMsg.getText();
            pointFeature.addStringProperty(POI_LONG_DESCRIPTION, poiLongDescription);
        }

        sortedPointFeatures.addFirst(pointFeature);

        if (!locations.isIndependent(i) && sortedPointFeatures.size() > 1) {
            Point lastPoint = (Point) sortedPointFeatures.get(1).geometry();
            ArrayList<Point> lineSegmentPoints = new ArrayList<>(3);
            lineSegmentPoints.add(lastPoint);
            lineSegmentPoints.add(point);
            LineString l = LineString.fromLngLats(lineSegmentPoints);
            Feature lineFeature = Feature.fromGeometry(l, new JsonObject(), "l_" + pointFeature.id());
            lineFeature.addNumberProperty(TIMESTAMP, pointFeature.getNumberProperty(TIMESTAMP));
            sortedLineFeatures.addFirst(lineFeature);
        }

        if (boundingBuilder != null) {
            boundingBuilder.include(new LatLng(locations.getLatitude(i), locations.getLongitude(i)));
        }
    }

    if (sortedPointFeatures.size() > 0) {
        for (Feature position : sortedPointFeatures) {
            if (!position.getBooleanProperty(IS_POI)) {
                position.addStringProperty(LAST_POSITION_ICON, contactMapMetadata.getMarkerLastPositon());
                position.addStringProperty(LAST_POSITION_LABEL, contactMapMetadata.getDisplayName());
                position.removeProperty(MARKER_ICON);
                position.addBooleanProperty(LAST_LOCATION, true);
                lastPositions.put(contactId, position);
                break;
            }
        }
    }

    featureCollections.put(contactMapMetadata.getMarkerFeatureCollection(), sortedPointFeatures);
    featureCollections.put(contactMapMetadata.getLineFeatureCollection(), sortedLineFeatures);
}