Java源码示例:com.github.davidmoten.geo.GeoHash

示例1
/**
 * @return ranges for rowkeys [0-255][startDay-endDay][setOfGeohashes]
 */
private List<Range> getRangeList() {
    List<Range> rangeList = new ArrayList<>();

    Coverage coverage = GeoHash.coverBoundingBoxMaxHashes(north, west, south, east, 100);
    log.debug("coverage:  [size:" + coverage.getHashes().size() + ", ratio:" + coverage.getRatio() + "]");

    Set<String> hashes = coverage.getHashes();
    for (String hash : hashes) {
        for (short day = startDay; day <= endDay; day++) {
            for (int spreadingByte = 0; spreadingByte <= 255; spreadingByte++) {
                ByteBuffer startKey = ByteBuffer.allocate(3 + hash.length());
                if (hash.length() > 8) {
                    hash = hash.substring(0, 8);
                }
                startKey.put((byte) spreadingByte).putShort(day).put(hash.getBytes());
                rangeList.add(Range.prefix(new Text(startKey.array())));
            }
        }
    }

    return rangeList;
}
 
示例2
@Test
public void testGeoHashGrid() throws Exception {
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1),"doc_count",10)))
            ));
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84);
    geohashGrid.initalize(envelope, features);
    assertEquals(GeoHash.widthDegrees(1), geohashGrid.getCellWidth(), 1e-10);
    assertEquals(GeoHash.heightDegrees(1), geohashGrid.getCellHeight(), 1e-10);
    assertEquals(new Envelope(-180+GeoHash.widthDegrees(1)/2.,180-GeoHash.widthDegrees(1)/2.,-90+GeoHash.heightDegrees(1)/2.,90-GeoHash.heightDegrees(1)/2.), geohashGrid.getEnvelope());
    int ny = (int) Math.round(180/geohashGrid.getCellHeight());
    int nx = (int) Math.round(360/GeoHash.widthDegrees(1));
    float[][] expected = new float[ny][nx];
    expected[ny-1][0] = 10;
    assertEquals(ny, geohashGrid.getGrid().length);
    assertEquals(nx, geohashGrid.getGrid()[0].length);
    IntStream.range(0, ny).forEach(i-> assertArrayEquals(expected[i], geohashGrid.getGrid()[i], 0.0f));
}
 
示例3
@Test
public void testGeoHashGrid_scaled() throws Exception {
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1),"doc_count",20))),
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(89.9,179.9),1),"doc_count",30)))
            ));
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84);
    geohashGrid.setScale(new RasterScale(5f, 10f));
    geohashGrid.initalize(envelope, features);
    assertEquals(GeoHash.widthDegrees(1), geohashGrid.getCellWidth(), 1e-10);
    assertEquals(GeoHash.heightDegrees(1), geohashGrid.getCellHeight(), 1e-10);
    assertEquals(new Envelope(-180+GeoHash.widthDegrees(1)/2.,180-GeoHash.widthDegrees(1)/2.,-90+GeoHash.heightDegrees(1)/2.,90-GeoHash.heightDegrees(1)/2.), geohashGrid.getEnvelope());
    int ny = (int) Math.round(180/geohashGrid.getCellHeight());
    int nx = (int) Math.round(360/GeoHash.widthDegrees(1));
    assertEquals(ny, geohashGrid.getGrid().length);
    assertEquals(nx, geohashGrid.getGrid()[0].length);
    float[][] expected = new float[ny][nx];
    expected[0][7] = 10;
    expected[ny-1][0] = 5;
    IntStream.range(0, ny).forEach(i-> assertArrayEquals(geohashGrid.getGrid()[i], expected[i], 0.0f));
}
 
示例4
private void insertRecords(Connection con, long now) throws SQLException {
	System.out.println("inserting...");
	PreparedStatement st = con
			.prepareStatement("insert into report(time,lat,lon,name,geohash1,geohash2,geohash3,geohash4,geohash5,geohash6,geohash7,geohash8,geohash9,geohash10,geohash11,geohash12) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
	long n;
	if (System.getProperty("n") != null)
		n = Long.parseLong(System.getProperty("n"));
	else
		n = 1000;
	for (int i = 0; i < n; i++) {
		long t = now - Math.round(TimeUnit.DAYS.toMillis(1));
		double lat = -Math.random() * 10;
		double lon = 135 + Math.random() * 10;
		st.setLong(1, t);
		st.setDouble(2, lat);
		st.setDouble(3, lon);
		st.setString(4, "name");
		for (int j = 5; j <= 16; j++)
			st.setString(j, GeoHash.encodeHash(lat, lon, j - 4));
		st.executeUpdate();
	}
	st.close();
}
 
示例5
@BeforeClass
public static void calcData() throws AccumuloException, AccumuloSecurityException, InterruptedException, IOException, JSONException {
    tweet = "{\"created_at\":\"Fri Apr 29 09:05:55 +0000 2016\",\"id\":725974381906804738,\"id_str\":\"725974381906804738\",\"text\":\"Das funktioniert doch nie! #haselnuss\",\"source\":\"\\u003ca href=\\\"http:\\/\\/twitter.com\\/download\\/android\\\" rel=\\\"nofollow\\\"\\u003eTwitter for Android\\u003c\\/a\\u003e\",\"truncated\":false,\"in_reply_to_status_id\":null,\"in_reply_to_status_id_str\":null,\"in_reply_to_user_id\":null,\"in_reply_to_user_id_str\":null,\"in_reply_to_screen_name\":null,\"user\":{\"id\":179905182,\"id_str\":\"179905182\",\"name\":\"Peter Tosh\",\"screen_name\":\"PakistAnnie_\",\"location\":null,\"url\":null,\"description\":\"http:\\/\\/annietheorphan.tumblr.com \\/ We Gucci, You crocks \\/ the smell of expensive perfume and cheap tobacco \\/ I edit my bio a lot\",\"protected\":false,\"verified\":false,\"followers_count\":147,\"friends_count\":136,\"listed_count\":2,\"favourites_count\":926,\"statuses_count\":7002,\"created_at\":\"Wed Aug 18 11:16:51 +0000 2010\",\"utc_offset\":3600,\"time_zone\":\"Edinburgh\",\"geo_enabled\":true,\"lang\":\"en\",\"contributors_enabled\":false,\"is_translator\":false,\"profile_background_color\":\"131516\",\"profile_background_image_url\":\"http:\\/\\/pbs.twimg.com\\/profile_background_images\\/794919404\\/cf1ea49974012270a0f5eda0fdbc4c1b.jpeg\",\"profile_background_image_url_https\":\"https:\\/\\/pbs.twimg.com\\/profile_background_images\\/794919404\\/cf1ea49974012270a0f5eda0fdbc4c1b.jpeg\",\"profile_background_tile\":true,\"profile_link_color\":\"009999\",\"profile_sidebar_border_color\":\"000000\",\"profile_sidebar_fill_color\":\"EFEFEF\",\"profile_text_color\":\"333333\",\"profile_use_background_image\":true,\"profile_image_url\":\"http:\\/\\/pbs.twimg.com\\/profile_images\\/709493600745299969\\/LrE_LZYK_normal.jpg\",\"profile_image_url_https\":\"https:\\/\\/pbs.twimg.com\\/profile_images\\/709493600745299969\\/LrE_LZYK_normal.jpg\",\"profile_banner_url\":\"https:\\/\\/pbs.twimg.com\\/profile_banners\\/179905182\\/1460640737\",\"default_profile\":false,\"default_profile_image\":false,\"following\":null,\"follow_request_sent\":null,\"notifications\":null},\"geo\":null,\"coordinates\":null,\"place\":{\"id\":\"1d73626cc863c69f\",\"url\":\"https:\\/\\/api.twitter.com\\/1.1\\/geo\\/id\\/1d73626cc863c69f.json\",\"place_type\":\"city\",\"name\":\"Riga\",\"full_name\":\"Riga, Latvia\",\"country_code\":\"LV\",\"country\":\"Latvija\",\"bounding_box\":{\"type\":\"Polygon\",\"coordinates\":[[[23.932583,56.857067],[23.932583,57.085918],[24.324730,57.085918],[24.324730,56.857067]]]},\"attributes\":{}},\"contributors\":null,\"is_quote_status\":false,\"retweet_count\":0,\"favorite_count\":0,\"entities\":{\"hashtags\":[],\"urls\":[],\"user_mentions\":[],\"symbols\":[],\"media\":[{\"id\":725974374491295744,\"id_str\":\"725974374491295744\",\"indices\":[32,55],\"media_url\":\"http:\\/\\/pbs.twimg.com\\/media\\/ChMt2OOXEAArNJb.jpg\",\"media_url_https\":\"https:\\/\\/pbs.twimg.com\\/media\\/ChMt2OOXEAArNJb.jpg\",\"url\":\"https:\\/\\/t.co\\/LfhhspVMwj\",\"display_url\":\"pic.twitter.com\\/LfhhspVMwj\",\"expanded_url\":\"http:\\/\\/twitter.com\\/PakistAnnie_\\/status\\/725974381906804738\\/photo\\/1\",\"type\":\"photo\",\"sizes\":{\"small\":{\"w\":340,\"h\":453,\"resize\":\"fit\"},\"large\":{\"w\":720,\"h\":960,\"resize\":\"fit\"},\"medium\":{\"w\":600,\"h\":800,\"resize\":\"fit\"},\"thumb\":{\"w\":150,\"h\":150,\"resize\":\"crop\"}}}]},\"extended_entities\":{\"media\":[{\"id\":725974374491295744,\"id_str\":\"725974374491295744\",\"indices\":[32,55],\"media_url\":\"http:\\/\\/pbs.twimg.com\\/media\\/ChMt2OOXEAArNJb.jpg\",\"media_url_https\":\"https:\\/\\/pbs.twimg.com\\/media\\/ChMt2OOXEAArNJb.jpg\",\"url\":\"https:\\/\\/t.co\\/LfhhspVMwj\",\"display_url\":\"pic.twitter.com\\/LfhhspVMwj\",\"expanded_url\":\"http:\\/\\/twitter.com\\/PakistAnnie_\\/status\\/725974381906804738\\/photo\\/1\",\"type\":\"photo\",\"sizes\":{\"small\":{\"w\":340,\"h\":453,\"resize\":\"fit\"},\"large\":{\"w\":720,\"h\":960,\"resize\":\"fit\"},\"medium\":{\"w\":600,\"h\":800,\"resize\":\"fit\"},\"thumb\":{\"w\":150,\"h\":150,\"resize\":\"crop\"}}}]},\"favorited\":false,\"retweeted\":false,\"possibly_sensitive\":false,\"filter_level\":\"low\",\"lang\":\"lv\",\"timestamp_ms\":\"1461920755255\"}\n" ;
    days = 16920;
    int bufferSize = tweet.length();
    ByteBuffer bb = ByteBuffer.allocate(bufferSize);
    bb.put(tweet.getBytes(Charsets.UTF_8));
    spreadingByte = hashFunction.hashBytes(bb.array()).asInt() % 255;
    Double[] loc = Extractor.extractLocation(new JSONObject(tweet));
    geoHash =  GeoHash.encodeHash(loc[1], loc[0], 8);
}
 
示例6
private void updateGrid(String geohash, Number value) {
    if (geohash != null && value != null) {
        final LatLong latLon = GeoHash.decodeHash(geohash);
        final double lat = latLon.getLat();
        double lon = latLon.getLon() + lonOffset;
        if (isValid(lat, lon-360)) updateGrid(lat, lon-360, value);
        if (isValid(lat, lon)) updateGrid(lat, lon, value);
        while (isValid(lat, lon+=360)) {
            updateGrid(lat, lon, value);
        }
    }
}
 
示例7
private Envelope computeEnvelope(ReferencedEnvelope outEnvelope, int precision) {
    final String minHash = GeoHash.encodeHash(Math.max(-90,outEnvelope.getMinY()), outEnvelope.getMinX(), precision);
    final LatLong minLatLon = GeoHash.decodeHash(minHash);
    final double minLon = minLatLon.getLon() + lonOffset;

    final double width = Math.ceil(outEnvelope.getWidth()/cellWidth)*cellWidth;
    final double maxLon = minLon + width - cellWidth;
    final String maxHash = GeoHash.encodeHash(Math.min(90, outEnvelope.getMaxY()), maxLon, precision);
    final LatLong maxLatLon = GeoHash.decodeHash(maxHash);

    return new Envelope(minLon, maxLon, minLatLon.getLat(), maxLatLon.getLat());
}
 
示例8
@Before
public void setup() throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1),"doc_count",10))),
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(0.1,0.1),1),"doc_count",10))),
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(89.9,179.9),1),"doc_count",10)))
            ));
    fineDelta = 0.45;
    ff = CommonFactoryFinder.getFilterFactory(null);
    process = new GeoHashGridProcess();
}
 
示例9
@Test
public void testGeoHashGridLowLonRange() throws Exception {
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1),"doc_count",10)))
            ));
    ReferencedEnvelope envelope = new ReferencedEnvelope(-360,180,-90,90,DefaultGeographicCRS.WGS84);
    geohashGrid.initalize(envelope, features);
    assertEquals(GeoHash.widthDegrees(1), geohashGrid.getCellWidth(), 1e-10);
    assertEquals(GeoHash.heightDegrees(1), geohashGrid.getCellHeight(), 1e-10);
    assertEquals(new Envelope(-360+GeoHash.widthDegrees(1)/2.,180-GeoHash.widthDegrees(1)/2.,-90+GeoHash.heightDegrees(1)/2.,90-GeoHash.heightDegrees(1)/2.), geohashGrid.getEnvelope());
    int ny = (int) Math.round(180/geohashGrid.getCellHeight());
    int nx = (int) Math.round(540/GeoHash.widthDegrees(1));
    assertEquals(ny, geohashGrid.getGrid().length);
    assertEquals(nx, geohashGrid.getGrid()[0].length);
}
 
示例10
@Test
public void testGeoHashGridHighLonRange() throws Exception {
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1),"doc_count",10)))
            ));
    ReferencedEnvelope envelope = new ReferencedEnvelope(360,540,-90,90,DefaultGeographicCRS.WGS84);
    geohashGrid.initalize(envelope, features);
    assertEquals(GeoHash.widthDegrees(1), geohashGrid.getCellWidth(), 1e-10);
    assertEquals(GeoHash.heightDegrees(1), geohashGrid.getCellHeight(), 1e-10);
    assertEquals(new Envelope(360+GeoHash.widthDegrees(1)/2.,540-GeoHash.widthDegrees(1)/2.,-90+GeoHash.heightDegrees(1)/2.,90-GeoHash.heightDegrees(1)/2.), geohashGrid.getEnvelope());
    int ny = (int) Math.round(180/geohashGrid.getCellHeight());
    int nx = (int) Math.round(180/GeoHash.widthDegrees(1));
    assertEquals(ny, geohashGrid.getGrid().length);
    assertEquals(nx, geohashGrid.getGrid()[0].length);
}
 
示例11
@Test
public void testGeoHashGridWithProjectedEnvelope() throws Exception {
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1),"doc_count",10)))
            ));
    ReferencedEnvelope envelope = new ReferencedEnvelope(-19926188.85,19926188.85,-30240971.96,30240971.96, CRS.decode("EPSG:3857"));
    geohashGrid.initalize(envelope, features);

    assertEquals(new ReferencedEnvelope(-180,180,-90,90,DefaultGeographicCRS.WGS84), geohashGrid.getBoundingBox());
}
 
示例12
@Test(expected=IllegalArgumentException.class)
public void testGeoHashGridWithNoDocCount() throws Exception {
    features = TestUtil.createAggregationFeatures(ImmutableList.of(
            ImmutableMap.of("_aggregation", mapper.writeValueAsBytes(ImmutableMap.of("key",GeoHash.encodeHash(new LatLong(-89.9,-179.9),1))))
            ));
    ReferencedEnvelope envelope = new ReferencedEnvelope(-180,180,-90,90,CRS.decode("EPSG:4326"));
    geohashGrid.initalize(envelope, features);
    IntStream.range(0, geohashGrid.getGrid().length).forEach(i-> assertArrayEquals(new float[geohashGrid.getGrid()[i].length], geohashGrid.getGrid()[i], 0.0f));
}
 
示例13
@Test
public void testGeoHash() {
    final double lat = rand.nextDouble() * 90 - 90;
    final double lon = rand.nextDouble() * 180 - 180;
    String geohash = GeoHash.encodeHash(lat, lon, 11);
    final Geometry expected = geometryFactory.createPoint(new Coordinate(lon, lat));
    final Geometry actual = parserUtil.createGeometry(geohash);
    assertEquals(0, expected.distance(actual), 1e-5);
}
 
示例14
private static String getGeoHash(Double[] coordinates){
    return GeoHash.encodeHash(coordinates[1], coordinates[0]);
}
 
示例15
private static String getGeoHash(Double[] coordinates){
    return GeoHash.encodeHash(coordinates[1], coordinates[0]);
}
 
示例16
public void initalize(ReferencedEnvelope srcEnvelope, SimpleFeatureCollection features) throws TransformException, FactoryException {
    final List<Map<String, Object>> buckets = readFeatures(features);

    final String firstGeohash = buckets.isEmpty() ? null : (String) buckets.get(0).get("key");
    final int precision;
    if (!isValid(firstGeohash)) {
        LOGGER.fine("No aggregations found or missing/invalid geohash key");
        precision = DEFAULT_PRECISION;
    } else {
        precision = ((String) buckets.get(0).get("key")).length();
    }

    cellWidth = GeoHash.widthDegrees(precision);
    cellHeight = GeoHash.heightDegrees(precision);

    if (srcEnvelope.getCoordinateReferenceSystem() != null) {
        srcEnvelope = srcEnvelope.transform(DefaultGeographicCRS.WGS84,false);
    }
    computeMinLonOffset(srcEnvelope);
    envelope = computeEnvelope(srcEnvelope, precision);

    boundingBox = new ReferencedEnvelope(envelope.getMinX()-cellWidth/2.0, envelope.getMaxX()+cellWidth/2.0,
            envelope.getMinY()-cellHeight/2.0, envelope.getMaxY()+cellHeight/2.0, DefaultGeographicCRS.WGS84);

    final int numCol = (int) Math.round((envelope.getMaxX()-envelope.getMinX())/cellWidth+1);
    final int numRow = (int) Math.round((envelope.getMaxY()-envelope.getMinY())/cellHeight+1);
    grid = new float[numRow][numCol];
    LOGGER.fine("Created grid with size (" + numCol + ", " + numRow + ")");

    if (emptyCellValue != 0) {
        for (float[] row: grid)
            Arrays.fill(row, emptyCellValue);
    }
    List<GridCell> cells = new ArrayList<>();
    buckets.forEach(bucket -> {
        Number rasterValue =  computeCellValue(bucket);
        cells.add(new GridCell((String) bucket.get("key"), rasterValue));
        scale.prepareScale(rasterValue.floatValue());
    });
    cells.forEach(cell -> updateGrid(cell.getGeohash(), cell.getValue()));
    LOGGER.fine("Read " + cells.size() + " aggregation buckets");
}
 
示例17
private boolean isValid(String geohash) {
    return geohash != null && GeoHash.encodeHash(GeoHash.decodeHash(geohash), geohash.length()).equals(geohash);
}
 
示例18
private static double computeSize(Envelope envelope, int n) {
    final double area = Math.min(360*180, envelope.getArea());
    return area/(GeoHash.widthDegrees(n)*GeoHash.heightDegrees(n));
}
 
示例19
/**
 * Returns as an {@link Iterable} the results of a search within the
 * bounding box given and where start &lt;=time &lt; finish.
 * 
 * @param topLeftLat
 *            latitude of top left point (north west)
 * @param topLeftLon
 *            longitude of top left point (north west)
 * @param bottomRightLat
 *            latitude of bottom right point (south east)
 * @param bottomRightLon
 *            longitude of bottom right point (south east)
 * @param start
 *            start time inclusive
 * @param finish
 *            finish time exclusive
 * @return info records
 */
public Iterable<Info<T, R>> find(double topLeftLat, double topLeftLon, double bottomRightLat,
        double bottomRightLon, long start, long finish) {

    Coverage cover = GeoHash.coverBoundingBox(topLeftLat, topLeftLon, bottomRightLat,
            bottomRightLon);
    Iterable<Info<T, R>> it = Collections.emptyList();
    for (String hash : cover.getHashes()) {
        it = Iterables.concat(it, find(topLeftLat, topLeftLon, bottomRightLat, bottomRightLon,
                start, finish, hash));
    }
    return it;
}
 
示例20
/**
 * Adds a record to the in-memory store with the given position, time and
 * id.
 * 
 * @param info
 *            info record to add
 */
public void add(Info<T, R> info) {
    String hash = GeoHash.encodeHash(info.lat(), info.lon());

    addToMap(mapByGeoHash, info, hash);
    addToMapById(mapById, info, hash);
}
 
示例21
/**
 * Calculates the geoHash
 *
 * @param loc location as long-lat-array
 * @return the 8 character long hash
 */
private static String calcGeoHash(Double[] loc) {

    return GeoHash.encodeHash(loc[1], loc[0], 8);
}
 
示例22
/**
 * Computes a geo-hash by given longitude and latitude.
 * @param coordinates Array of two doubles representing latitude and longitude.
 * @return Geo-Hash String
 */
private static String getGeoHash(Double[] coordinates){
    return GeoHash.encodeHash(coordinates[1], coordinates[0]);
}