Java Code Examples for com.mapbox.geojson.Feature

The following examples show how to use com.mapbox.geojson.Feature. 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
Source Project: mapbox-java   Author: mapbox   File: TurfMiscTest.java    License: 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 #2
Source Project: mapbox-java   Author: mapbox   File: TurfConversionTest.java    License: 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 #3
Source Project: graphhopper-navigation-android   Author: graphhopper   File: MapUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Takes a {@link FeatureCollection} and creates a map GeoJson source using the sourceId also
 * provided.
 *
 * @param mapboxMap  that the current mapView is using
 * @param collection the feature collection to be added to the map style
 * @param sourceId   the source's id for identifying it when adding layers
 * @since 0.8.0
 */
public static void updateMapSourceFromFeatureCollection(@NonNull MapboxMap mapboxMap,
                                                        @Nullable FeatureCollection collection,
                                                        @NonNull String sourceId) {
  if (collection == null) {
    collection = FeatureCollection.fromFeatures(new Feature[] {});
  }

  GeoJsonSource source = mapboxMap.getSourceAs(sourceId);
  if (source == null) {
    GeoJsonOptions routeGeoJsonOptions = new GeoJsonOptions().withMaxZoom(16);
    GeoJsonSource routeSource = new GeoJsonSource(sourceId, collection, routeGeoJsonOptions);
    mapboxMap.addSource(routeSource);
  } else {
    source.setGeoJson(collection);
  }
}
 
Example #4
Source Project: AirMapSDK-Android   Author: airmap   File: MapStyleController.java    License: Apache License 2.0 6 votes vote down vote up
public void highlight(Feature feature) {
    String id = feature.getStringProperty("id");
    String type = feature.getStringProperty("category");

    // remove old highlight
    unhighlight();

    // add new highlight
    String sourceId = feature.getStringProperty("ruleset_id");
    highlightLayerId = "airmap|highlight|line|" + sourceId;
    LineLayer highlightLayer = map.getMap().getStyle().getLayerAs(highlightLayerId);
    highlightLayer.setSourceLayer(sourceId + "_" + type);

    // feature's airspace_id can be an int or string (tile server bug), so match on either
    Expression filter;
    try {
        int airspaceId = Integer.parseInt(id);
        filter = Expression.any(Expression.eq(Expression.get("id"), id), Expression.eq(Expression.get("id"), airspaceId));
    } catch (NumberFormatException e) {
        filter = Expression.any(Expression.eq(Expression.get("id"), id));
    }
    highlightLayer.setFilter(filter);
}
 
Example #5
Source Project: mapbox-java   Author: mapbox   File: TurfConversionTest.java    License: MIT License 6 votes vote down vote up
@Test
public void combinePointsToMultiPoint() throws Exception {
  FeatureCollection pointFeatureCollection =
    FeatureCollection.fromFeatures(
      Arrays.asList(
        Feature.fromGeometry(Point.fromLngLat(-2.46, 27.6835)),
        Feature.fromGeometry(Point.fromLngLat(41.83, 7.3624))
      ));

  FeatureCollection featureCollectionWithNewMultiPointObject = TurfConversion.combine(pointFeatureCollection);
  assertNotNull(featureCollectionWithNewMultiPointObject);

  MultiPoint multiPoint = (MultiPoint) featureCollectionWithNewMultiPointObject.features().get(0).geometry();
  assertNotNull(multiPoint);

  assertEquals(-2.46, multiPoint.coordinates().get(0).longitude(), DELTA);
  assertEquals(27.6835, multiPoint.coordinates().get(0).latitude(), DELTA);
  assertEquals(41.83, multiPoint.coordinates().get(1).longitude(), DELTA);
  assertEquals(7.3624, multiPoint.coordinates().get(1).latitude(), DELTA);
}
 
Example #6
Source Project: graphhopper-navigation-android   Author: graphhopper   File: MapWaynameTest.java    License: MIT License 6 votes vote down vote up
@Test
public void onRoadsReturnedFromQuery_layoutProviderGeneratesBitmap() {
  String roadName = "roadName";
  PointF point = mock(PointF.class);
  SymbolLayer waynameLayer = mock(SymbolLayer.class);
  List<Feature> roads = new ArrayList<>();
  Feature road = mock(Feature.class);
  when(road.hasNonNullValueForProperty("name")).thenReturn(true);
  when(road.getStringProperty("name")).thenReturn(roadName);
  roads.add(road);
  WaynameLayoutProvider layoutProvider = mock(WaynameLayoutProvider.class);
  when(layoutProvider.generateLayoutBitmap(roadName)).thenReturn(mock(Bitmap.class));
  MapWayname mapWayname = buildMapWayname(point, layoutProvider, waynameLayer, roads);
  mapWayname.updateWaynameVisibility(true, waynameLayer);

  mapWayname.updateWaynameWithPoint(point, waynameLayer);

  verify(layoutProvider).generateLayoutBitmap(roadName);
}
 
Example #7
Source Project: mapbox-java   Author: mapbox   File: TurfConversionTest.java    License: MIT License 6 votes vote down vote up
@Test
public void combinePointAndMultiPointToMultiPoint() throws Exception {
  FeatureCollection pointAndMultiPointFeatureCollection =
      FeatureCollection.fromFeatures(
          Arrays.asList(
              Feature.fromGeometry(Point.fromLngLat(-2.46, 27.6835)),
              Feature.fromGeometry(MultiPoint.fromLngLats(
                  Arrays.asList(Point.fromLngLat(41.83, 7.3624),
                      Point.fromLngLat(100, 101)))
              )));

  FeatureCollection combinedFeatureCollection =
      TurfConversion.combine(pointAndMultiPointFeatureCollection);

  assertNotNull(combinedFeatureCollection);

  MultiPoint multiPoint = (MultiPoint) combinedFeatureCollection.features().get(0).geometry();
  assertNotNull(multiPoint);

  assertEquals(-2.46, multiPoint.coordinates().get(0).longitude(), DELTA);
  assertEquals(27.6835, multiPoint.coordinates().get(0).latitude(), DELTA);
  assertEquals(41.83, multiPoint.coordinates().get(1).longitude(), DELTA);
  assertEquals(7.3624, multiPoint.coordinates().get(1).latitude(), DELTA);
  assertEquals(100, multiPoint.coordinates().get(2).longitude(), DELTA);
  assertEquals(101, multiPoint.coordinates().get(2).latitude(), DELTA);
}
 
Example #8
Source Project: mapbox-plugins-android   Author: mapbox   File: BulkSymbolActivity.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void showSymbols(int amount) {
  List<SymbolOptions> options = new ArrayList<>();
  Random random = new Random();
  int randomIndex;

  List<Feature> features = locations.features();
  if (features == null) {
    return;
  }

  for (int i = 0; i < amount; i++) {
    randomIndex = random.nextInt(features.size());
    Feature feature = features.get(randomIndex);
    options.add(new SymbolOptions()
      .withGeometry((Point) feature.geometry())
      .withIconImage("fire-station-11")
    );
  }
  symbols = symbolManager.create(options);
}
 
Example #9
Source Project: mapbox-java   Author: mapbox   File: TurfMeasurement.java    License: MIT License 6 votes vote down vote up
/**
 * Takes a set of features, calculates the bbox of all input features, and returns a bounding box.
 *
 * @param geoJson a {@link GeoJson} object
 * @return a double array defining the bounding box in this order {@code [minX, minY, maxX, maxY]}
 * @since 4.8.0
 */
public static double[] bbox(GeoJson geoJson) {
  BoundingBox boundingBox = geoJson.bbox();
  if (boundingBox != null) {
    return new double[] {
      boundingBox.west(),
      boundingBox.south(),
      boundingBox.east(),
      boundingBox.north()
    };
  }

  if (geoJson instanceof Geometry) {
    return bbox((Geometry) geoJson);
  } else if (geoJson instanceof FeatureCollection) {
    return bbox((FeatureCollection) geoJson);
  } else if (geoJson instanceof Feature) {
    return bbox((Feature) geoJson);
  } else {
    throw new UnsupportedOperationException("bbox type not supported for GeoJson instance");
  }
}
 
Example #10
Source Project: deltachat-android   Author: deltachat   File: MapActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
private boolean handlePoiLongClick(LatLng point) {
    final PointF pixel = mapboxMap.getProjection().toScreenLocation(point);
    List<Feature> features = mapboxMap.queryRenderedFeatures(pixel, mapDataManager.getMarkerLayers());
    for (Feature feature : features) {
        if (feature.getBooleanProperty(IS_POI)) {
            new AlertDialog.Builder(MapActivity.this)
                    .setMessage(getString(R.string.menu_delete_location))
                    .setPositiveButton(R.string.yes, (dialog, which) -> {
                        int messageId = feature.getNumberProperty(MESSAGE_ID).intValue();
                        int[] messages = new int[1];
                        messages[0] = messageId;
                        ApplicationContext.getInstance(MapActivity.this).dcContext.deleteMsgs(messages);
                    })
                    .setNegativeButton(R.string.no, null)
                    .show();
            return true;
        }
    }
    return false;
}
 
Example #11
Source Project: AirMapSDK-Android   Author: airmap   File: PolygonContainer.java    License: Apache License 2.0 6 votes vote down vote up
public boolean checkForIntersections() {
    List<LatLng> points = PointMath.findIntersections(path);
    if (points.isEmpty()) {
        return false;
    }

    List<Point> intersections = latLngsToPositions(points);
    if (map.getStyle().getLayer(INTERSECTION_LAYER) == null) {
        Source intersectionSource = new GeoJsonSource(INTERSECTION_SOURCE, Feature.fromGeometry(MultiPoint.fromLngLats(intersections)));
        map.getStyle().addSource(intersectionSource);
        Layer intersectionLayer = new SymbolLayer(INTERSECTION_LAYER, INTERSECTION_SOURCE)
                .withProperties(PropertyFactory.iconImage(INTERSECTION_IMAGE));
        map.getStyle().addLayer(intersectionLayer);
    } else {
        GeoJsonSource intersectionsSource = map.getStyle().getSourceAs(INTERSECTION_SOURCE);
        intersectionsSource.setGeoJson(Feature.fromGeometry(MultiPoint.fromLngLats(intersections)));
    }

    return true;
}
 
Example #12
Source Project: mapbox-java   Author: mapbox   File: TurfAssertions.java    License: MIT License 6 votes vote down vote up
/**
 * Enforce expectations about types of {@link FeatureCollection} inputs for Turf. Internally
 * this uses {@link Feature#type()}} to judge geometry types.
 *
 * @param featureCollection for which features will be judged
 * @param type              expected GeoJson type
 * @param name              name of calling function
 * @see <a href="http://turfjs.org/docs/#collectionof">Turf collectionOf documentation</a>
 * @since 1.2.0
 */
public static void collectionOf(FeatureCollection featureCollection, String type, String name) {
  if (name == null || name.length() == 0) {
    throw new TurfException("collectionOf() requires a name");
  }
  if (featureCollection == null || !featureCollection.type().equals("FeatureCollection")
    || featureCollection.features() == null) {
    throw new TurfException(String.format(
      "Invalid input to %s, FeatureCollection required", name));
  }
  for (Feature feature : featureCollection.features()) {
    if (feature == null || !feature.type().equals("Feature") || feature.geometry() == null) {
      throw new TurfException(String.format(
        "Invalid input to %s, Feature with geometry required", name));
    }
    if (feature.geometry() == null || !feature.geometry().type().equals(type)) {
      throw new TurfException(String.format(
        "Invalid input to %s: must be a %s, given %s", name, type, feature.geometry().type()));
    }
  }
}
 
Example #13
Source Project: mapbox-java   Author: mapbox   File: TurfClassificationTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testLineDistanceWithGeometries() throws IOException, TurfException {
  Point pt = (Point) Feature.fromJson(loadJsonFixture(PT)).geometry();
  FeatureCollection pts = FeatureCollection.fromJson(loadJsonFixture(PTS));

  List<Point> pointList = new ArrayList<>();
  for (Feature feature : pts.features()) {
    pointList.add((Point) (feature.geometry()));
  }
  Point closestPt = TurfClassification.nearestPoint(pt, pointList);

  Assert.assertNotNull(closestPt);
  Assert.assertEquals(closestPt.type(), "Point");
  Assert.assertEquals(closestPt.longitude(), -75.33, DELTA);
  Assert.assertEquals(closestPt.latitude(), 39.44, DELTA);
}
 
Example #14
Source Project: AirMapSDK-Android   Author: airmap   File: CircleContainer.java    License: 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 #15
Source Project: mapbox-java   Author: mapbox   File: TurfMiscTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testTurfPointOnLinePointsOnSidesOfLines() throws TurfException {
  List<Point> line = new ArrayList<>();
  line.add(Point.fromLngLat(-122.45616137981413, 37.72125936929241));
  line.add(Point.fromLngLat(-122.45717525482178, 37.718242366859215));
  Point first = line.get(0);
  Point last = line.get(1);

  List<Point> pts = new ArrayList<>();
  pts.add(Point.fromLngLat(-122.45702505111694, 37.71881098149625));
  pts.add(Point.fromLngLat(-122.45733618736267, 37.719235317933844));
  pts.add(Point.fromLngLat(-122.45686411857605, 37.72027068864082));
  pts.add(Point.fromLngLat(-122.45652079582213, 37.72063561093274));

  for (Point pt : pts) {
    Feature snappedFeature = TurfMisc.nearestPointOnLine(pt, line);
    Point snapped = (Point) snappedFeature.geometry();
    // pt did not snap to first vertex
    assertNotEquals(snapped, first);
    // pt did not snap to last vertex
    assertNotEquals(snapped, last);
  }
}
 
Example #16
Source Project: mapbox-java   Author: mapbox   File: TurfMiscTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testTurfPointOnLinePointsInFrontOfLastPoint() throws TurfException {
  List<Point> line = new ArrayList<>();
  line.add(Point.fromLngLat(-122.45616137981413, 37.72125936929241));
  line.add(Point.fromLngLat(-122.45717525482178, 37.72003306385638));
  line.add(Point.fromLngLat(-122.45717525482178, 37.718242366859215));

  Point last = line.get(2);

  List<Point> pts = new ArrayList<>();
  pts.add(Point.fromLngLat(-122.45696067810057, 37.7181405249708));
  pts.add(Point.fromLngLat(-122.4573630094528, 37.71813203814049));
  pts.add(Point.fromLngLat(-122.45730936527252, 37.71797927502795));
  pts.add(Point.fromLngLat(-122.45718061923981, 37.71704571582896));

  for (Point pt : pts) {
    Feature snappedFeature = TurfMisc.nearestPointOnLine(pt, line);
    Point snapped = (Point) snappedFeature.geometry();
    // pt behind start moves to last vertex
    assertEquals(last, snapped);
  }
}
 
Example #17
Source Project: mapbox-java   Author: mapbox   File: TurfMeasurementTest.java    License: 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 #18
Source Project: mapbox-java   Author: mapbox   File: TurfMeasurementTest.java    License: MIT License 6 votes vote down vote up
@Test
public void bboxPolygonFromMultiPolygon() throws IOException, TurfException {
  // Create a MultiPolygon
  MultiPolygon multiPolygon = MultiPolygon.fromJson(loadJsonFixture(TURF_BBOX_POLYGON_MULTIPOLYGON));

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

  // 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(100, 0.0), polygonRepresentingBoundingBox.coordinates().get(0).get(4));
}
 
Example #19
@Override
public boolean onMapClick(@NonNull LatLng point) {
    PointF pointf = map.getProjection().toScreenLocation(point);
    RectF rectF = new RectF(pointf.x - 10, pointf.y - 10, pointf.x + 10, pointf.y + 10);
    List<Feature> features = map.queryRenderedFeatures(rectF, featureType == FeatureType.POINT ? "POINT_LAYER" : "POLYGON_LAYER");
    if (!features.isEmpty()) {
        for (Feature feature : features) {
            presenter.getEventInfo(feature.getStringProperty("eventUid"), point);
        }
        return true;
    }

    return false;
}
 
Example #20
Source Project: mapbox-java   Author: mapbox   File: TurfMetaTest.java    License: 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 #21
Source Project: AirMapSDK-Android   Author: airmap   File: AdvisorySelector.java    License: Apache License 2.0 5 votes vote down vote up
private boolean hasHigherPriority(Feature feature, Feature selectedFeature) {
    String type = selectedFeature.getStringProperty("category");
    switch (type) {
        case "emergency":
        case "school":
        case "fire":
        case "prison":
        case "wildfire":
        case "power_plant":
            return false;
        default:
            return true;
    }
}
 
Example #22
Source Project: graphhopper-navigation-android   Author: graphhopper   File: NavigationMapRoute.java    License: MIT License 5 votes vote down vote up
/**
 * The routes also display an icon for each waypoint in the route, we use symbol layers for this.
 */
private FeatureCollection waypointFeatureCollection(DirectionsRoute route) {
  final List<Feature> waypointFeatures = new ArrayList<>();
  for (RouteLeg leg : route.legs()) {
    waypointFeatures.add(getPointFromLineString(leg, 0));
    waypointFeatures.add(getPointFromLineString(leg, leg.steps().size() - 1));
  }
  return FeatureCollection.fromFeatures(waypointFeatures);
}
 
Example #23
Source Project: graphhopper-navigation-android   Author: graphhopper   File: NavigationMapRoute.java    License: MIT License 5 votes vote down vote up
private Feature getPointFromLineString(RouteLeg leg, int index) {
  Feature feature = Feature.fromGeometry(Point.fromLngLat(
    leg.steps().get(index).maneuver().location().longitude(),
    leg.steps().get(index).maneuver().location().latitude()
  ));
  feature.addStringProperty(SOURCE_KEY, WAYPOINT_SOURCE_ID);
  feature.addStringProperty("waypoint",
    index == 0 ? "origin" : "destination"
  );
  return feature;
}
 
Example #24
Source Project: mapbox-java   Author: mapbox   File: TurfMiscTest.java    License: MIT License 5 votes vote down vote up
@Test
public void testTurfLineSliceLine1() throws IOException, TurfException {
  Point start = Point.fromLngLat(-97.79617309570312, 22.254624939561698);
  Point stop = Point.fromLngLat(-97.72750854492188, 22.057641623615734);

  Feature line1 = Feature.fromJson(loadJsonFixture(LINE_SLICE_ONE));

  LineString sliced = TurfMisc.lineSlice(start, stop, line1);
  assertNotNull(sliced);
}
 
Example #25
Source Project: mapbox-java   Author: mapbox   File: GeoJsonAdapterFactory.java    License: MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
  Class<?> rawType = type.getRawType();
  if (BoundingBox.class.isAssignableFrom(rawType)) {
    return (TypeAdapter<T>) BoundingBox.typeAdapter(gson);
  } else if (Feature.class.isAssignableFrom(rawType)) {
    return (TypeAdapter<T>) Feature.typeAdapter(gson);
  } else if (FeatureCollection.class.isAssignableFrom(rawType)) {
    return (TypeAdapter<T>) FeatureCollection.typeAdapter(gson);
  } else if (GeometryCollection.class.isAssignableFrom(rawType)) {
    return (TypeAdapter<T>) GeometryCollection.typeAdapter(gson);
  } else if (LineString.class.isAssignableFrom(rawType)) {
    return (TypeAdapter<T>) LineString.typeAdapter(gson);
  } else if (MultiLineString.class.isAssignableFrom(rawType)) {
    return (TypeAdapter<T>) MultiLineString.typeAdapter(gson);
  } else if (MultiPoint.class.isAssignableFrom(rawType)) {
    return (TypeAdapter<T>) MultiPoint.typeAdapter(gson);
  } else if (MultiPolygon.class.isAssignableFrom(rawType)) {
    return (TypeAdapter<T>) MultiPolygon.typeAdapter(gson);
  } else if (Polygon.class.isAssignableFrom(rawType)) {
    return (TypeAdapter<T>) Polygon.typeAdapter(gson);
  } else if (Point.class.isAssignableFrom(rawType)) {
    return (TypeAdapter<T>) Point.typeAdapter(gson);
  }
  return null;
}
 
Example #26
Source Project: mapbox-java   Author: mapbox   File: TurfConversionTest.java    License: MIT License 5 votes vote down vote up
@Test
public void combineTwoLineStringsToMultiLineString() throws Exception {
  FeatureCollection lineStringFeatureCollection =
      FeatureCollection.fromFeatures(
          Arrays.asList(
              Feature.fromGeometry(LineString.fromLngLats(
                  Arrays.asList(Point.fromLngLat(-11.25, 55.7765),
                      Point.fromLngLat(41.1328, 22.91792)))),
              Feature.fromGeometry(LineString.fromLngLats(
                  Arrays.asList(Point.fromLngLat(3.8671, 19.3111),
                      Point.fromLngLat(20.742, -20.3034))))
          ));

  FeatureCollection featureCollectionWithNewMultiLineStringObject = TurfConversion.combine(lineStringFeatureCollection);
  assertNotNull(featureCollectionWithNewMultiLineStringObject);

  MultiLineString multiLineString = (MultiLineString) featureCollectionWithNewMultiLineStringObject.features().get(0).geometry();
  assertNotNull(multiLineString);

  // Checking the first LineString in the MultiLineString
  assertEquals(-11.25, multiLineString.coordinates().get(0).get(0).longitude(), DELTA);
  assertEquals(55.7765, multiLineString.coordinates().get(0).get(0).latitude(), DELTA);

  // Checking the second LineString in the MultiLineString
  assertEquals(41.1328, multiLineString.coordinates().get(0).get(1).longitude(), DELTA);
  assertEquals(22.91792, multiLineString.coordinates().get(0).get(1).latitude(), DELTA);
}
 
Example #27
Source Project: graphhopper-navigation-android   Author: graphhopper   File: NavigationHelper.java    License: MIT License 5 votes vote down vote up
/**
 * Takes in a raw location, converts it to a point, and snaps it to the closest point along the
 * route. This is isolated as separate logic from the snap logic provided because we will always
 * need to snap to the route in order to get the most accurate information.
 */
static Point userSnappedToRoutePosition(Location location, List<Point> coordinates) {
  if (coordinates.size() < 2) {
    return Point.fromLngLat(location.getLongitude(), location.getLatitude());
  }

  Point locationToPoint = Point.fromLngLat(location.getLongitude(), location.getLatitude());

  // Uses Turf's pointOnLine, which takes a Point and a LineString to calculate the closest
  // Point on the LineString.
  Feature feature = TurfMisc.nearestPointOnLine(locationToPoint, coordinates);
  return ((Point) feature.geometry());
}
 
Example #28
Source Project: mapbox-java   Author: mapbox   File: TurfMeasurementTest.java    License: MIT License 5 votes vote down vote up
@Test
public void centerFeatureWithProperties() {
  JsonObject properties = new JsonObject();
  properties.addProperty("key", "value");
  Feature inputFeature = Feature.fromJson(loadJsonFixture(TURF_AREA_POLYGON_GEOJSON));
  Feature returnedCenterFeature = TurfMeasurement.center(inputFeature, properties, null);
  Point returnedPoint = (Point) returnedCenterFeature.geometry();
  if (returnedPoint != null) {
    assertEquals(133.5, returnedPoint.longitude(), 0);
    assertEquals(-27.0, returnedPoint.latitude(), 0);
    if (returnedCenterFeature.properties() != null) {
      assertTrue(returnedCenterFeature.properties().toString().contains("{\"key\":\"value\"}"));
    }
  }
}
 
Example #29
public String getOfflineRegionName() {
  List<Feature> featureList = mapboxMap.queryRenderedFeatures(boundingBox, LAYER_IDS);
  if (featureList.isEmpty() && style != null) {
    Timber.v("Rendered features empty, attempting to query vector source.");
    VectorSource source = style.getSourceAs("composite");
    if (source != null) {
      featureList = source.querySourceFeatures(SOURCE_LAYER_IDS, null);
    }
  }
  if (!featureList.isEmpty() && featureList.get(0).properties().has("name")) {
    return featureList.get(0).getStringProperty("name");
  }
  return getString(R.string.mapbox_offline_default_region_name);
}
 
Example #30
Source Project: mapbox-java   Author: mapbox   File: TurfMetaTest.java    License: MIT License 5 votes vote down vote up
@Test
public void wrongFeatureGeometryForGetCoordThrowsException() throws TurfException {
  thrown.expect(TurfException.class);
  thrown.expectMessage(startsWith("A Feature with a Point geometry is required."));
  TurfMeta.getCoord(Feature.fromGeometry(LineString.fromLngLats(Arrays.asList(
    Point.fromLngLat(0, 9),
    Point.fromLngLat(0, 10)
  ))));
}