/** * Builds a new Place document to insert in the Places index. * @param placeId the identifier of the place in the database. * @param placeName the name of the place. * @param placeAddress the address of the place. * @param location the GPS location of the place, as a GeoPt. * @return the Place document created. */ public static Document buildDocument( final Long placeId, final String placeName, final String placeAddress, final GeoPt location) { GeoPoint geoPoint = new GeoPoint(location.getLatitude(), location.getLongitude()); Document.Builder builder = Document.newBuilder() .addField(Field.newBuilder().setName("id") .setText(placeId.toString())) .addField(Field.newBuilder().setName("name").setText(placeName)) .addField(Field.newBuilder().setName("address") .setText(placeAddress)) .addField(Field.newBuilder().setName("place_location") .setGeoPoint(geoPoint)); // geo-location doesn't work under dev_server, so let's add another // field to use for retrieving documents if (environment.value() == Development) { builder.addField(Field.newBuilder().setName("value").setNumber(1)); } return builder.build(); }
public SearchResultProxy getTrainConnections(float lat1, float lon1, float lat2, float lon2, boolean ignoreTrains, boolean ignoreSubte) throws IllegalArgumentException { QuotaService qs = QuotaServiceFactory.getQuotaService(); long start = qs.getCpuTimeInMegaCycles(); Dao.getInstance(); Objectify ofy = ObjectifyService.begin(); String functionName = "getTrainConnections"; HashSet<Key<Line>> tabuTrainsSet = new HashSet<Key<Line>>(); if(ignoreTrains) { tabuTrainsSet.addAll(Dao.getTrainKeys()); } if(ignoreSubte) { tabuTrainsSet.addAll(Dao.getSubteKeys()); } ConnectionProxy connTren = Dao.getInstance().indirectSearch(new GeoPt(lat1, lon1), new GeoPt(lat2, lon2), tabuTrainsSet, new HashSet<Key<Line>>(), ofy); List<ConnectionProxy> conns = new LinkedList<ConnectionProxy>(); conns.add(connTren); long end = qs.getCpuTimeInMegaCycles(); double cpuSeconds = qs.convertMegacyclesToCpuSeconds(end - start); Logger.getLogger("LineListServiceImpl").log(Level.INFO, functionName + ": " + cpuSeconds + " CPU seconds."); if(connTren != null) { return new SearchResultProxy(conns, null, null); } else { return null; } }
public static Point closestPoint(GeoPt thePoint, Collection<Point> points) { GeoPt p = thePoint; double dMin = 99999999.9; Point pMin = null; for(Point pCur : points) { double distCur = Utils.distanceApprox(p, pCur); if(pCur.isIgnore()) { // absolutely avoid points that are set as ignore. Related to the dirty hack that searches any point, if none were found that are not "ignore"-flagged. Theoretically there shouldn't be any case where this is necessary, but right now there is (rarely). distCur += 10000; } if(distCur < dMin) { dMin = distCur; pMin = pCur; } } return pMin; }
public static List<Place> getPlacesByProximity(GeoPt origin, Double proximityMeters, int count){ List<Place> places = new ArrayList<Place>(); //hmmm... inequality filters are limited to one operation // this would be expensive on a large DB... List<Place> results = new ArrayList<Place>(); places.addAll(ofy().load().type(Place.class).limit(count).list()); for(Place p : places) { GeoPt placeLocation = new GeoPt(p.getLatitude().floatValue(), p.getLongitude().floatValue()); double distance = PlaceUtil.getDistanceInMeters(origin,placeLocation); if(distance <= proximityMeters){ // covert distance to string and pack into payload for device double distanceMiles = distance * metersToMiles; String distanceStr = String.format("%.2f", distanceMiles); p.setDistance(distanceStr + " miles"); results.add(p); } } return results; }
/** * Return a collection of registered devices * * @param count The number of devices to list * @param userLongitude The coordinate of user device * @param userLatitude The coordinate of user deivce * @param radiusInMeters Proximity to search * @return a list of Google Cloud Messaging registration Ids */ @ApiMethod(name = "listPlaces") public Collection<Place> listPlaces(@Named("count") int count, @Named("longitude") Double userLongitude, @Named("latitude") Double userLatitude, @Named("range") Double radiusInMeters) { DataInjector injector = new DataInjector(); injector.createDataSet(); // Convert Strings into floats float longitude, latitude; longitude = userLongitude.floatValue(); latitude = userLatitude.floatValue(); GeoPt location = new GeoPt(latitude, longitude); List<Place> places = PlaceUtil.getPlacesByProximity(location,radiusInMeters,count); log.info(places.size() + " places returned "); return places; //return CollectionResponse.<Place>builder().setItems(places).build(); }
@Before public void addData() throws InterruptedException { Query query = new Query(kindName, rootKey); if (service.prepare(query).countEntities(fetchOption) == 0) { List<Entity> elist = new ArrayList<Entity>(); for (int i = 0; i < count; i++) { Entity newRec = new Entity(kindName, rootKey); newRec.setProperty("stringData", "string test data " + i); newRec.setProperty("intData", 10 * i); newRec.setProperty("stringList", Arrays.asList("abc" + i, "xyz" + i, "abc" + i)); newRec.setProperty("intList", Arrays.asList(i, 50 + i, 90 + i)); newRec.setProperty("timestamp", new Date()); newRec.setProperty("floatData", new Float(i + 0.1)); newRec.setProperty("ratingData", new Rating(i + 20)); newRec.setProperty("booleanData", true); newRec.setProperty("geoptData", new GeoPt((float) (i * 20 - 90), new Float(i * 30 - 179.1))); newRec.setProperty("byteStrProp", new ShortBlob(("shortblob" + (i * 30)).getBytes())); elist.add(newRec); } service.put(elist); sync(waitTime); } }
@Test public void testWithPropertyProjection() { Query query = new Query(kindName, rootKey); query.addProjection(new PropertyProjection("geoptData", GeoPt.class)); Filter filter1 = Query.CompositeFilterOperator.or( Query.FilterOperator.LESS_THAN.of("intList", 5), Query.FilterOperator.GREATER_THAN.of("intList", 90)); Filter filter2 = Query.FilterOperator.EQUAL.of("intList", 52); query.setFilter(Query.CompositeFilterOperator.and(filter1, filter2)); // sql statement String sql = "SELECT geoptData FROM " + kindName; sql += " WHERE ((intList < 5 or intList > 90) AND intList = 52)"; sql += " AND __ancestor__ is " + rootKey; assertEquals(sql.toLowerCase(), query.toString().toLowerCase()); // check query result List<Entity> results = service.prepare(query).asList(fo); Assert.assertTrue(results.size() > 0); assertEquals(new GeoPt((float) (2.12), (float) (2.98)), results.get(0).getProperty("geoptData")); for (Entity e : results) { assertEquals(1, e.getProperties().size()); assertTrue(e.getProperties().containsKey("geoptData")); } }
static Document buildDocument( String placeId, String placeName, String placeAddress, GeoPt location) { GeoPoint geoPoint = new GeoPoint(location.getLatitude(), location.getLongitude()); Document.Builder builder = Document.newBuilder() .addField(Field.newBuilder().setName("id").setText(placeId)) .addField(Field.newBuilder().setName("name").setText(placeName)) .addField(Field.newBuilder().setName("address").setText(placeAddress)) .addField(Field.newBuilder().setName("place_location").setGeoPoint(geoPoint)); // geo-location doesn't work under dev_server, so let's add another // field to use for retrieving documents if (environment.value() == Development) { builder.addField(Field.newBuilder().setName("value").setNumber(1)); } Document place = builder.build(); return place; }
@Test public void testComplexRow() throws IOException { Table table = new Table().setColumns(Arrays.asList( new Column().setName("first").setType("LOCATION"), new Column().setName("second").setType("STRING"), new Column().setName("third").setType("STRING"), new Column().setName("fourth").setType("DATETIME") )); FusionTableContentWriter writer = new FusionTableContentWriter(table); DateTime dateTime = DateTime.parse("2013-05-22T11:00:00-03:00"); writer.writeRecord(new GeoPt(44.990288f, -64.131035f), "a string", "another string", dateTime); Assert.assertEquals( "\"first\",\"second\",\"third\",\"fourth\"\n" + "\"44.990288 -64.131035\",\"a string\",\"another string\",\"2013-05-22T11:00:00-03:00\"\n", getOutputString(writer) ); }
@Test public void testGeoptEncoding() throws IOException { Table table = new Table().setColumns(Arrays.asList( new Column().setName("name").setType("STRING"), new Column().setName("location").setType("LOCATION") )); FusionTableContentWriter writer = new FusionTableContentWriter(table); writer.writeRecord("John Smith", new GeoPt(40.767838f, -73.981972f)); writer.writeRecord("Jane Adams", new GeoPt(44.990288f, -64.131035f)); writer.writeRecord("Bob Mcconnell", new GeoPt(46.099918f, -60.754677f)); Assert.assertEquals( "\"name\",\"location\"\n" + "\"John Smith\",\"40.767838 -73.981972\"\n" + "\"Jane Adams\",\"44.990288 -64.131035\"\n" + "\"Bob Mcconnell\",\"46.099918 -60.754677\"\n", getOutputString(writer) ); }
private Address getAddress(@Nullable Location fbLocation) { if (fbLocation == null) { return null; } Address address = new Address(); address.setStreet(fbLocation.getStreet()); address.setCity(fbLocation.getCity()); address.setState(fbLocation.getState()); address.setCountry(fbLocation.getCountry()); address.setZip(fbLocation.getZip()); if ((fbLocation.getLatitude() != null) && (fbLocation.getLongitude() != null)) { address.setGeoPt(GeoPtWrapper.create( new GeoPt(fbLocation.getLatitude().floatValue(), fbLocation.getLongitude().floatValue()))); } return address; }
@Nullable public static GeoPt getGeoPt(String addressStr) { // TODO(avaliani): use an api key to avoid geocoding quota limits final Geocoder geocoder = new Geocoder(); GeocoderRequest geocoderRequest = new GeocoderRequestBuilder() .setAddress(addressStr) .setLanguage("en") .getGeocoderRequest(); GeocodeResponse geocoderResponse = geocoder.geocode(geocoderRequest); if (geocoderResponse.getStatus() == GeocoderStatus.OK) { GeocoderResult firstResult = geocoderResponse.getResults().get(0); return new GeoPt( firstResult.getGeometry().getLocation().getLat().floatValue(), firstResult.getGeometry().getLocation().getLng().floatValue()); } else { log.log(GEOCODE_LOG_LEVEL, "Geocoding failed: status=" + geocoderResponse.getStatus() + ", " + "response=" + geocoderResponse); // TODO(avaliani): Properly handle geopt encoding failures. Retrying in cases where // the error is over quota. return null; } }
public static IndexTypeLookup defaultIndexTypeLookup() { IndexTypeLookup indexTypeLookup = new IndexTypeLookup(); indexTypeLookup.addMapping(Key.class, IndexType.Identifier); indexTypeLookup.addMapping(com.google.appengine.api.datastore.Key.class, IndexType.Identifier); indexTypeLookup.addMapping(GeoPt.class, IndexType.GeoPoint); return indexTypeLookup; }
@Test public void shouldCreateGeoPointFromGeoPt() { GeoPoint geoPoint = new GeoPoint(1.23, 4.56); GeoPt result = transformer.from(geoPoint); assertThat(result.getLatitude(), is(1.23f)); assertThat(result.getLongitude(), is(4.56f)); }
@Test public void shouldCreateGeoPointFromGeoPt() { GeoPt geoPt = new GeoPt(1.23f, 4.56f); GeoPoint result = transformer.from(geoPt); assertThat(result.getLatitude(), is((double) 1.23f)); assertThat(result.getLongitude(), is((double) 4.56f)); }
/** * This is the overloaded constructor used to create a complete instance of * a station. * * @param name * @param description * @param location * @param knownTrails */ public Station(String name, String description, IndexedGPSLocation location) { super(); this.displayName = name; this.name = name.toUpperCase().trim(); this.description = description; this.location = location; if (location != null) { this.geopt = new GeoPt(location.getLatitude().floatValue(), location.getLongitude().floatValue()); } }
/** * Instantiates a new platform. * * @param station the station * @param name the name * @param description the description * @param location the location */ public Platform(Ref<Station> station, String name, String description, IndexedGPSLocation location) { super(); this.station=station; this.name = name; this.description = description; this.location = location; this.geopt = new GeoPt(location.getLatitude().floatValue(), location.getLongitude().floatValue()); }
public Point(String street, float lat, float lon, boolean ignore, boolean forSearchOnly, Key<Line> owner) { this.street = street; this.latlon = new GeoPt(lat, lon); this.ignore = ignore; this.forSearchOnly = forSearchOnly; this.nextMainPointIndex = -1; // this.lat = lat; // this.lon = lon; if(forSearchOnly && ignore) { System.err.println("Point(...): forSearchOnly and ignore are set at the same time. This should not happen since it makes no sense to create a point for search only, yet ignore it in search then"); } defaultGeoCell = generateGeoCell(); this.owner = owner; }
public UserFavouritePositionProxy addFavourite(UserFavouritePositionProxy fpp) { UserService userService = UserServiceFactory.getUserService(); User user = userService.getCurrentUser(); if (user != null) { Objectify ofy = Dao.getInstance().getObjectify(); UserFavouritePosition toSave = new UserFavouritePosition(user, new GeoPt((float)fpp.getLat(), (float)fpp.getLon()), fpp.getName()); Dao.getInstance().addUserFavouritePosition(toSave, ofy); return new UserFavouritePositionProxy(fpp.getName(), fpp.getLat(), fpp.getLon(), toSave.getId().toString()); } else { return null; } }
public static double getDistanceInMeters(GeoPt location1, GeoPt location2){ // derived from haversine double loc1Lat = Math.toRadians(location1.getLatitude()); double loc2Lat = Math.toRadians(location2.getLatitude()); double latDelta = Math.toRadians(location2.getLatitude()-location1.getLatitude()); double lonDelta = Math.toRadians(location2.getLongitude() - location1.getLongitude()); double a = Math.sin(latDelta/2) * Math.sin(latDelta/2) + Math.cos(loc1Lat) * Math.cos(loc2Lat) * Math.sin(lonDelta/2) * Math.sin(lonDelta/2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return radiusEarthMeters * c; }
@Test public void testGets() throws Exception { Query query = new Query(kindName, rootKey); GeoPt filter = new GeoPt(Float.valueOf(60).floatValue(), Float.valueOf(145).floatValue()); query.setFilter(new FilterPredicate(propertyName, Query.FilterOperator.EQUAL, filter)); Entity entity = service.prepare(query).asSingleEntity(); GeoPt geopt = (GeoPt) entity.getProperty(propertyName); assertTrue(geopt.equals(filter)); assertEquals(Float.valueOf(geopt.getLatitude()).toString(), Float.valueOf(60).toString()); assertEquals(Float.valueOf(geopt.getLongitude()).toString(), Float.valueOf(145).toString()); }
@Test public void testGeoptType() { List<Entity> elist = doQuery(kindName, propertyName, GeoPt.class, true); GeoPt rate = (GeoPt) elist.get(0).getProperty(propertyName); GeoPt sameDat = (GeoPt) elist.get(0).getProperty(propertyName); GeoPt diffDat = (GeoPt) elist.get(1).getProperty(propertyName); assertTrue(rate.equals(sameDat)); assertFalse(rate.equals(diffDat)); assertEquals(-12, rate.getLatitude(), 0); assertEquals(120, rate.getLongitude(), 0); assertEquals(0, rate.compareTo(sameDat)); assertTrue(rate.compareTo(diffDat) != 0); assertEquals(rate.hashCode(), rate.hashCode()); }
@Before public void createData() throws InterruptedException { clearData(kindName); List<Entity> elist = new ArrayList<>(); for (int i = 0; i < count; i++) { Entity newRec = new Entity(kindName, rootKey); newRec.setProperty("stringData", "string data" + i); newRec.setProperty("timestamp", new Date()); newRec.setProperty("shortBlobData", new ShortBlob(("shortBlobData" + i).getBytes())); newRec.setProperty("intData", 20 * i); newRec.setProperty("textData", new Text("textData" + i)); newRec.setProperty("floatData", 1234 + 0.1 * i); newRec.setProperty("booleanData", true); newRec.setProperty("urlData", new Link("http://www.google.com")); newRec.setProperty("emailData", new Email("somebody123" + i + "@google.com")); newRec.setProperty("phoneData", new PhoneNumber("408-123-000" + i)); newRec.setProperty("adressData", new PostalAddress("123 st. CA 12345" + i)); newRec.setProperty("ratingData", new Rating(10 * i)); newRec.setProperty("geoptData", new GeoPt((float) (i + 0.12), (float) (i + 0.98))); newRec.setProperty("categoryData", new Category("category" + i)); newRec.setProperty("intList", Arrays.asList(i, 50 + i, 90 + i)); elist.add(newRec); } service.put(elist); sync(1000); }
@Before public void createData() throws InterruptedException { Query query = new Query(kindName, rootKey); if (service.prepare(query).countEntities(fo) == 0) { int props = 15; List<Entity> elist = new ArrayList<Entity>(); elist.clear(); for (int i = 0; i < count; i++) { Entity newRec = new Entity(kindName, rootKey); if (i == 0) { newRec.setProperty("stringData", null); } else if (i == 15) { newRec.setProperty("stringData", ""); } else { newRec.setProperty("stringData", "string" + i / (props)); } newRec.setProperty("timestamp", new Date()); newRec.setProperty("intData", i / (props - 2)); if (i == 4) { newRec.setProperty("floatData", null); } else { newRec.setProperty("floatData", new Double(12 + i / (props - 4) * 0.1)); } if ((count % 2) == 0) { newRec.setProperty("booleanData", true); } else { newRec.setProperty("booleanData", false); } newRec.setProperty("geoptData", new GeoPt((float) (i / (props - 9) + 12.0), (float) (i / (props - 9) + 90.0))); newRec.setProperty("intList", Arrays.asList(i / (props - 11), 50 + i / (props - 11), 90 + i / (props - 11))); elist.add(newRec); } service.put(elist); sync(waitTime); } }
public static GeoPt parseGeoPt(String latlng) { if (latlng == null) { return null; } String[] parts = latlng.split(",", 2); // TODO: Validation return new GeoPt(Float.parseFloat(parts[0]), Float.parseFloat(parts[1])); }
public static GeoPt geocode(String address) throws GeocodeFailedException, GeocodeNotFoundException { // The underlying geocoder library fails if it receives an empty address. if (address.trim().isEmpty()) { throw new GeocodeFailedException(address, GeocoderStatus.INVALID_REQUEST); } String cacheKey = "geocode:" + address; CacheProxy cache = new CacheProxy(); Object cacheEntry = cache.get(cacheKey); // Backwards comparison -- cacheEntry may be null if (INVALID_LOCATION.equals(cacheEntry)) { throw new GeocodeNotFoundException(address); } if (cacheEntry != null) { return (GeoPt) cacheEntry; } Geocoder geocoder = new Geocoder(); // TODO: Use Maps for Business? GeocoderRequest request = new GeocoderRequestBuilder().setAddress(address).getGeocoderRequest(); GeocodeResponse response = geocoder.geocode(request); GeocoderStatus status = response.getStatus(); if (status == GeocoderStatus.ZERO_RESULTS) { cache.put(cacheKey, INVALID_LOCATION); throw new GeocodeNotFoundException(address); } else if (status != GeocoderStatus.OK) { // We've encountered a temporary error, so return without caching the missing point. throw new GeocodeFailedException(address, response.getStatus()); } else { LatLng location = response.getResults().get(0).getGeometry().getLocation(); GeoPt geoPt = new GeoPt(location.getLat().floatValue(), location.getLng().floatValue()); cache.put(cacheKey, geoPt); return geoPt; } }
private static String serializeObjectForFusionTables(Object object) { if (object instanceof GeoPt) { GeoPt geoPt = (GeoPt) object; return String.format("%f %f", geoPt.getLatitude(), geoPt.getLongitude()); } else if (object instanceof DateTime) { DateTime dateTime = (DateTime) object; DateTimeFormatter iso8601Formatter = ISODateTimeFormat.dateTimeNoMillis(); return iso8601Formatter.print(dateTime); } else { return object.toString(); } }
private UserProfile createProfile(String userId, GeoPt location) { UserProfile userProfile = new UserProfile(); userProfile.setUserId(userId); userProfile.setLocation(location); OfyService.ofy().put(userProfile); return userProfile; }
/** * @return the geopt */ public GeoPt getGeopt() { return geopt; }
/** * @param location * the location to set */ public void setLocation(IndexedGPSLocation location) { this.location = location; this.geopt = new GeoPt(location.getLatitude().floatValue(), location.getLongitude().floatValue()); }
public UserFavouritePosition(User user, GeoPt pos, String name) { this.user = user; this.pos = pos; this.name = name; }
public GeoPt getPos() { return pos; }
public GeoPt getLatlon() { return latlon; }