Spring Java MongoDB Geo Location Search service sample

Source: Internet
Author: User
Tags aop findone

1, configure the Pom.xml, add the following 2 in the original Spring project.

<span style= "White-space:pre" ></span><!--MONGO DB drive--><dependency>    <groupId> org.mongodb</groupid>    <artifactId>mongo-java-driver</artifactId>    <version> 3.2.2</version></dependency><!--spring-data-mongodb--><dependency>    <groupId> org.springframework.data</groupid>    <artifactId>spring-data-mongodb</artifactId>    < Version>1.9.2.release</version></dependency>

2, Configuration Spring-data-mongo.xml

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: context= "Http://www.springframework.org/schema/context" xmlns:p= "http://www.springframework.org/schema/p" xmlns: aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:xsi= " Http://www.w3.org/2001/XMLSchema-instance "xmlns:mongo=" Http://www.springframework.org/schema/data/mongo "xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.0.xsdhttp://www.springframework.org/schema/context Http://www.springframework.org/schema/context /spring-context-4.0.xsd Http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/ DATA/MONGO/SPRING-MONGO-1.0.XSDHTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/ Aop/spring-aop-4.0.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-4.0.xsdhttp://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd "><!--Default Bean name is ' MONGO '--><mongo:mongo host=" localhost "port=" 27017 "/><!--offers Convenience methods and automatic mapping between MongoDB JSON documents and your domain classes. --<bean id= "mongotemplate" class= "Org.springframework.data.mongodb.core.MongoTemplate" > < Constructor-arg ref= "Mongo"/> <constructor-arg name= "databaseName" value= "test"/> </bean></beans& Gt

3. MongoDB Parent Interface Class


package Com.zjp.cache;import Java.util.list;import com.mongodb.dbobject;/** * MongoDB Parent Interface class * @author Babylon * @version 1.1 * @dat E July 12, 2016-PM 1:22:23 */public Interface Mongodao {public DBObject findOne (String collection, dbobject query, Dbobje     CT fields); Public list<dbobject> Find (String collection, dbobject query, dbobject fields, dbobject by, int pagenum, int pa     Gesize);     Public list<dbobject> Find (String collection, dbobject query, dbobject fields, dbobject by, int limit);     public void Delete (String collection, DBObject dbobject);     public void Save (String collection, DBObject dbobject);     public void Update (String collection, dbobject query, DBObject Update, Boolean Upsert, Boolean multi);     Public Long count (String collection, dbobject query); Public list<?> Distinct (string collection, string key, DBObject query); }

4, MONDODB address Operation interface class


Package Com.zjp.cache; Import Com.mongodb.DBObject; Import java.util.List; /** * MONDODB Address Arithmetic Interface class * * @author Babylon * @version 1.1 * @date July 12, 2016-PM 1:42:06 */public Interface Mongogeodao exte NDS mongodao{
   /** * Aggregate query, query the point near a point, and return each point to the center point of the distance, in the case of the coordinate table Shard $nearsphere is not supported, * can use this method to query * @param Collection collection name * @param query criteria * @param Point Center coordinates * @param limit returns the number of records limits * @param Maxdistanc e Maximum distance * @return non-null List */public list<dbobject> geonear (String collection, DBObject q    Uery, point point,int limit, long maxdistance); /** * Query the coordinate points within the circular area, you need to specify the center point coordinates and radius, the RADIUS unit is m * * @param collection collection name * @param locationfield coordinate field * @pa         RAM center point coordinate [longitude, latitude] * @param radius radius Unit: M * @param fields query field * @param query Query condition * @param limit returns the number of record limits * @return non-null List */public list<dbobject> WI Thincircle (String collection,string Locationfield, point Center, long radius, dbobje     CT fields, dbobject query, int limit); /** * Specifies a point that returns the coordinate point near the point and is near to far, $nearSphere need to be indexed2dsphere or 2d, and supports Geojson and general coordinate pairs * Note: $nearSphere not valid in a shard cluster, use geonear * * @param Collection collection name * @para M Locationfield coordinate field * @param center point coordinate [longitude, latitude] * @param mindistance Nearest distance * @param maxdistance Farthest              Distance * @param query criteria * @param fields Query field * @param limit returns the number of record limits * @return  Non-null List */Public list<dbobject> Nearsphere (String collection, String Locationfield, point center,      Long mindistance, long maxdistance, dbobject query, dbobject fields, int limit); /** * Query all coordinate points within the specified enclosing polygon, the given polygon coordinate point must be first connected to form a closed polygon * such as a triangle * final linkedlist<double[]> polygon = n     EW linkedlist<> ();     * Polygon.addlast (new double[] {121.36, 31.18});     * Polygon.addlast (new double[] {121.35, 31.36});     * Polygon.addlast (new double[] {121.39, 31.17});     * Polygon.addlast (new double[] {121.36, 31.18}); * MongoDB will also look at the boundaries of polygons asPoll for part of a shape * @param collection collection name * @param locationfield coordinate field * @param polygon Polygon coordinates * @param fiel     DS query Field * @param query condition * @param limit returns the number of record limits * @return non-null list                                        */Public list<dbobject> Withinpolygon (String collection,string Locationfield,      list<double[]> polygon,dbobject fields,dbobject query,int limit);     /** * Queries all coordinate points within a specified number of enclosing polygons, a given polygon coordinate point must first meet to form a closed polygon * @param Collection collection name * @param locationfield coordinate field         * @param polygons Polygon Coordinate array * @param fields query field * @param query condition * @param limit Returns the number of record limits * @return non-null List */public list<dbobject> Withinmultipolygon (String collectio N,string Locationfield, list<list<double[]>> polygons,dbobject fields,d      Bobject query,int limit); /** * Find coordinate points within a rectangular area, this method is only 2dIndex is supported, not supported in 2dsphere * @param collection collection name * @param locationfield coordinate field * @param bottomleft lower left corner * @ Param upperright * @param fields query field * @param query criteria * @param limit returns the number of record limits Volume * @return non-null List */@Deprecated public list<dbobject> Withinbox (String collection, String Locationfield, point Bottomleft, point Upperright, dbobject fields, dbobject que Ry,int limit); }

5. MongoDB Service Implementation Class


Package Com.zjp.service.impl; Import Com.mongodb.aggregationoptions;import Com.mongodb.basicdbobject;import Com.mongodb.cursor;import Com.mongodb.dbobject;import Com.zjp.cache.mongogeodao;import Com.zjp.cache.point;import Org.slf4j.Logger;import Org.slf4j.loggerfactory;import Org.springframework.beans.factory.annotation.autowired;import Org.springframework.data.mongodb.core.mongotemplate;import Org.springframework.stereotype.repository;import Java.util.arraylist;import Java.util.linkedlist;import java.util.List;  /** * MongoDB Service Implementation class * * @author Babylon * @version 1.1 * @date July 12, 2016-PM 1:36:50 */@Repositorypublic class Mongodaoimpl        Implements Mongogeodao {private static Logger Logger = Loggerfactory.getlogger (Mongodaoimpl.class);     @Autowired private Mongotemplate mongotemplate; @Override public DBObject FindOne (String collection, dbobject query, dbobject fields) {return mongotemplate.get    Collection (Collection). FindOne (query, fields); } @Override PUBlic list<dbobject> Find (String collection, dbobject query, dbobject fields, dbobject by, int pagenum, int page        Size) {list<dbobject> List = new arraylist<> (); cursor cursor = mongotemplate.getcollection (collection). Find (Query, fields). Skip ((pageNum-1) * pageSize). Limit (        pageSize). sort (by);        while (Cursor.hasnext ()) {List.add (Cursor.next ()); } return List.size () > 0?    List:null; } @Override Public list<dbobject> find (String collection, dbobject query, dbobject fields, DBObject,        int limit) {list<dbobject> List = new arraylist<> ();        cursor cursor = mongotemplate.getcollection (collection). Find (Query, fields). Sort (by). Limit;        while (Cursor.hasnext ()) {List.add (Cursor.next ()); } return List.size () > 0?    List:null; } @Override public void Delete (String collection, DBObject dbobject) {mongotemplate.GetCollection (collection). Remove (DBObject); } @Override public void Save (String collection, DBObject dbobject) {Mongotemplate.getcollection (collection)    . Save (DBObject);         } @Override public void Update (String collection, dbobject query, DBObject Update, Boolean Upsert, Boolean multi) {    Mongotemplate.getcollection (collection). Update (query, update, Upsert, multi); @Override Public Long count (String collection, dbobject query) {return mongotemplate.getcollection (Collec    tion). Count (query); } @Override public list<?> distinct (string collection, string key, DBObject query) {return mongotemplate.    GetCollection (collection). Distinct (key, query); } @Override Public list<dbobject> geonear (String collection, dbobject query, point point, int limit, long max         Distance) {if (query==null) query = new Basicdbobject ();        list<dbobject> pipeLine = new arraylist<> (); Basicdbobject aggregate = new Basicdbobject ("$geoNear", New Basicdbobject ("near", New Basicdbobject ("type", "point"). Append (" Coordinates ", New double[]{118.783799, 31.979234}). Append (" Distancefield "," dist.calculated "). Append (" Query ", New Basicdbobject ()). Append (" num ", 5). Append (" MaxDistance ",). Append (" spherical ", true))        ;        Pipeline.add (aggregate);        Cursor Cursor=mongotemplate.getcollection (collection). Aggregate (PipeLine, Aggregationoptions.builder (). build ());        list<dbobject> list = new linkedlist<> ();        while (Cursor.hasnext ()) {List.add (Cursor.next ());    } return list;                                       } @Override Public list<dbobject> withincircle (String collection,string Locationfield, point Center, Long radius, dbobject fields, dbobject query, int limit) {linkedlist<object> C        Ircle = new linkedlist<> (); Set The Center coordinate circle. AddLast (New Double[]{center.getlng (), Center.getlat ()}); Set the radius.         Unit:meter Circle.addlast (radius/6378137.0);        if (query==null) query = new Basicdbobject ();        Query.put (Locationfield, New Basicdbobject ("$geoWithin", New Basicdbobject ("$centerSphere", circle));        Logger.info ("withincircle:{}", query.tostring ());    Return Mongotemplate.getcollection (collection). Find (Query, fields). Limit (limit). ToArray ();                                     } @Override Public list<dbobject> nearsphere (String collection, String Locationfield, point center, Long mindistance, long maxdistance, dbobject query, dbobject fields, int limit) {if (que         Ry==null) query = new Basicdbobject ();                             Query.put (Locationfield, New Basicdbobject ("$nearSphere", New Basicdbobject ("$geometry", New Basicdbobject ("type", "point"). Append ("CoordInates ", New Double[]{center.getlng (), Center.getlat ()})). Append (" $minDistance ", Mindistance)        . Append ("$maxDistance", MaxDistance)));        Logger.info ("nearsphere:{}", query.tostring ());    Return Mongotemplate.getcollection (collection). Find (Query, fields). Limit (limit). ToArray ();                                        } @Override Public list<dbobject> Withinpolygon (String collection, String Locationfield,            List<double[]> polygon, dbobject fields, dbobject query, int limit) {if (query==null)         query = new Basicdbobject ();        list<list<double[]>> polygons = new linkedlist<> ();        Polygons.add (Polygon);                        Query.put (Locationfield, New Basicdbobject ("$geoWithin", New Basicdbobject ("$geometry",        New Basicdbobject ("type", "Polygon"). Append ("coordinates", polygons))); Logger.info ("withinpolygon:{}", query.tostring ());    Return Mongotemplate.getcollection (collection). Find (Query, fields). Limit (limit). ToArray (); } @Override Public list<dbobject> Withinmultipolygon (String collection, String Locationfield, List<list&lt ;d ouble[]>> polygons, dbobject fields, dbobject query, int limit) {if (query==null) query = new Ba         Sicdbobject ();        list<list<list<double[]>>> List = new linkedlist<> (); for (list<double[]> polygon:polygons) {list<list<double[]>> temp = new Linkedlist<> (            );            Temp.add (Polygon);        List.add (temp);                        } query.put (Locationfield, New Basicdbobject ("$geoWithin", New Basicdbobject ("$geometry",        New Basicdbobject ("type", "Multipolygon"). Append ("coordinates", list)));        Logger.info ("withinmultipolygon:{}", query.tostring ()); Return Mongotemplate.getcolleCtion (collection). Find (Query, fields). Limit (limit). ToArray (); } @Override Public list<dbobject> Withinbox (String collection, String Locationfield, point Bottomleft, point         Upperright, dbobject fields, dbobject query, int limit) {if (query==null) query = new Basicdbobject ();        linkedlist<double[]> box = new linkedlist<> ();        Box.add (New Double[]{bottomleft.getlng (), Bottomleft.getlat ()});         Box.add (New Double[]{upperright.getlng (), Upperright.getlat ()});        Query.put (Locationfield, New Basicdbobject ("$geoWithin", New Basicdbobject ("$box", Box));        Logger.info ("withinbox:{}", query.tostring ());    Return Mongotemplate.getcollection (collection). Find (Query, fields). Limit (limit). ToArray (); } }


6. Add Data


Db.point.test.insert ({"Address": "Nanjing Lukou International Airport", "Loc": {"type": "Point", "coordinates": [118.783799,31.979234]}}) Db.poi Nt.test.insert ({"Address": "Nanjing Pukou Park", "Loc": {"type": "Point", "coordinates": [118.639523,32.070078]}}) db.point.test. Insert ({"Address": "Nanjing railway Station", "Loc": {"type": "Point", "coordinates": [118.803032,32.09248]}}) Db.point.test.insert ({"A Ddress ":" Nanjing Xinjiekou "," loc ": {" type ":" Point "," coordinates ": [118.790611,32.047616]}}) Db.point.test.insert ({" Address ": "Nanjing Zhang Fu Yuan", "loc": {"type": "Point", "coordinates": [118.790427,32.03722]}}) Db.point.test.insert ({"Address": "Nanjing Sanshan Street", "L OC ": {" type ":" Point "," coordinates ": [118.788135,32.029064]}}) Db.point.test.insert ({" Address ":" Nanjing Zhonghua Gate "," loc ": {" T Ype ":" Point "," coordinates ": [118.781161,32.013023]}) Db.point.test.insert ({" Address ":" Nanjing Ender Gate "," loc ": {" type ":" Poi NT "," coordinates ": [118.768964,31.99646]}})


7, must add index (why: https://docs.mongodb.com/manual/reference/operator/aggregation/geoNear/)

Db.point.test.ensureIndex ({loc: "2dsphere"})  

8. Invoking instances

@Autowiredprivate Mongodaoimpl Mongodao;
DBObject query = new Basicdbobject (); Point point = new Point ();p oint.setlng (118.783799);p Oint.setlat (31.979234); int limit = 5; Long maxdistance = 5000L; M list<dbobject> list = Mongodao.geonear ("point.test", query, point, limit, maxdistance); for (DBObject obj:list)   System.out.println (obj);


Spring Java MongoDB Geo Location Search service sample

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.