A recent project: You need to query a site (known to the latitude and longitude of the site) within 500 meters of other sites. So, the first thing I think about is, for each record, go to traverse, with each point in the database to calculate distance, when the distance is less than 500 meters, think match. It does get the results, but the efficiency is extremely low, because each record is going to loop around the n data, and the time can be imagined.
So I think of a first filter out the approximate latitude and longitude range before the calculation. Let's say a square of four points, so I searched the web, accidentally, to a query about the calculation of the proximity of the site search, which uses Python to achieve this idea. So we refer to the algorithm in the original text and use Java to implement it.
The implementation principle is very similar, first calculate the rectangle around the point of four points, and then use latitude and longitude to directly match the records in the database.
Train of thought: First calculate the "500 meters near the given coordinates of the range of coordinates." Although it is a circle, we can first find the outer square of the circle, and then take the latitude and longitude of the square to search the database.
First, ask for the range boundary on both sides of the thing. In the Haversin formula to make φ1 =φ2, can be
Written in Java code is
[Java]View plain copy//First compute the latitude and longitude range of the query point <span style= "font-family: Microsoft James Black, Helvetica, Times, Arial, serif;" >lat known latitude, LNG known longitude </span> double r = 6371;//Earth radius km double DIS = 0.5;//0.5 kilometer distance double DLNG = 2*math.asin (Math.sin (dis/(2*r))/math.cos (lat*math.pi/180)); DLNG = dlng*180/math.pi;//angle to radians double dlat = dis/r; Dlat = Dlat*180/math.pi; Finally, we can get the coordinates of four points:
Left-top: (Lat + dlat, lng–dlng)
Right-top: (Lat + dlat, LNG + dlng)
Left-bottom: (Lat–dlat, LNG–DLNG)
Right-bottom: (Lat–dlat, LNG + dlng)
That's the way it goes. Filter queries
[Java] View Plain copy public list<property> findneighposition (double longitude,double Latitude) { //first compute the latitude and longitude range of the query point double r = 6371;//Earth radius km double dis = 0.5;//0.5 Kilometer distance double dlng = 2*math.asin (Math.sin (dis/(2*r))/Math.cos (latitude* math.pi/180)); dlng = dlng*180/math.pi;// Angle to radians double dlat = dis/r; dlat = dlat*180/Math.PI; double minlat =latitude-dlat; double maxlat = latitude+dlat; double minlng = longitude -dlng; double maxlng = longitude + dlng; String hql = "from property where longitude>=? And longitude =<? and latitude>=? latitude=<? and state=0 "; object[] values = {minlng,maxlng,minlat, maxlat}; list<property> list = find (hql, values); return list; }