A 2d sphere index supports queries that calculate geometries on an earth-like sphere. The index supports data stored as both GeoJSON objects and as legacy coordinate pairs. The index supports legacy coordinate pairs by converting the data to the GeoJSON Point type.
翻譯: 2d sphere index 支援球體幾何查詢。資料存放區以GeoJSON objects為主。
Store your location data as GeoJSON objects with this coordinate-axis order: longitude, latitude. The coordinate reference system for GeoJSON uses the WGS84 datum.
/** * 轉換為GeoJSON對象 */ public String getGeoJson(String lon,String lat) throws JSONException{ JSONObject point = new JSONObject(); point.put( "type", "Point"); JSONArray coord = new JSONArray( "["+lon+ ","+lat+ "]"); point.put( "coordinates", coord); return point.toString(); } /** * 插入空間資料 * @param collection * @throws JSONException */ public void insert(DBCollection collection) throws JSONException{ DBObject point1 = new BasicDBObject(); point1.put( "name", "001"); point1.put( "geo", getGeoJson( "116.342176", "39.995376")); DBObject point2 = new BasicDBObject(); point2.put( "name", "002"); point2.put( "geo", getGeoJson( "116.348694", "39.990965")); DBObject point3 = new BasicDBObject(); point3.put( "name", "003"); point3.put( "geo", getGeoJson( "116.343318", "39.991184")); DBObject point4 = new BasicDBObject(); point4.put( "name", "004"); point4.put( "geo", getGeoJson( "116.359590", "39.982762")); List<DBObject> list = new ArrayList<DBObject>(); list.add(point1); list.add(point2); list.add(point3); list.add(point4); collection.insert(list).getN(); } /** * 建立空間索引 * @param collection */ public void makeSpatialIndexs(DBCollection collection){ collection.ensureIndex( new BasicDBObject( "geo", "2dsphere"), "geospatialIdx"); } /** * 查詢矩形內的所有要素 * @param collection */ public void query(DBCollection collection){ List<Double[]> box = new ArrayList<Double[]>(); box.add( new Double[] {116.341795,39.992277}); //左上方 coordinate box.add( new Double[]{116.350122,39.989251}); // 右下角 coordinate BasicDBObject query = new BasicDBObject( "loc", new BasicDBObject("$within",new BasicDBObject("$box" , box))); DBCursor cur1 = collection.find(query); while (cur1.hasNext()) { BasicDBObject o = (BasicDBObject) cur1.next(); System. out.println(o.get( "name")); System. out.println(o.get( "geometry")); } }
更多的空間操作參考:
http://java.dzone.com/articles/writing-geospatial-queries
參考資料: geojson: http://www.geojson.org/geojson-spec.htmlGeospatial
Indexes and Queries:http://docs.mongodb.org/manual/applications/geospatial-indexes/