How to retrieve nearest data from mysql using GPS coordinates? [duplicate] - php

This question already has answers here:
PHP MySql and geolocation
(3 answers)
Closed 9 years ago.
I am using this SQL query to get data that is nearest to GPS coordinates.
SELECT geo_latitude, geo_longitude, geo_name, geo_country_code AS country,
(DEGREES(
ACOS(
SIN(RADIANS(47.470779)) * SIN(RADIANS(geo_latitude)) +
COS(RADIANS(47.470779)) * COS(RADIANS(geo_latitude)) *
COS(RADIANS(-87.890699 - geo_longitude))
)
) * 60 * 1.1515)
AS distance FROM `MyDatabase`.`allCountries` ORDER BY distance ASC LIMIT 20 ;
This query retrieves all the data irrespective of the distance. I would like it to display the data only within a radius of 10 miles. How can i achieve this?

There's two ways I've found. One way is to do a direct SQL query with a whole lot of math in the 'where' section, much like you've tagged for your AS distance section of the SQL. Essentially - conceptually - 'where distance < 10'
However, I've found that slows down my request ... so what I've done in addition is to pull out the square instead of the circle from the database. Simply put: figure out the 'ten miles west/north/east/south' coords, then put in WHERE geo_latitude < X1 AND geo_latitude > x2 AND geo_longitude < x3 AND geo_longitude > x4 to put a hard limit on what I get back. Then, if you really need to be that precise, cut off the corners by only displaying if( result.distance < 10 ){
Or to put it another way:
x1 = Coords + 10 miles north
x2 = Coords + 10 miles south
x3 = Coords + 10 miles east
x4 = Coords + 10 miles west
by whatever means you're using to indicate '10 miles north', and then use that to pull out a 'square' of 10-miles north, south, west, and east from the center point. As long as your geo_latitude and geo_longitude columns are indexed, this should be a fast database call.

Related

Calculate distance from current Latitude and Longitude with different Latitude and Longitude in one kilometer [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have problem I think but I can not find the ideal solution. I am storing different restaurant locations latitude and longitude in Mysql table. I want to find a restaurant around 1 km radial distance from current location of user using latitude and longitude so how to do this. I have to show all restaurants which are in 1 km radius from user current location latitude and longitude.
This is the formula of distances using longitude and latitude
a = sin²(Δφ/2) + cos φ1 ⋅ cos φ2 ⋅ sin²(Δλ/2)
c = 2 * atan2( √a, √(1−a) )
d = R * c
//Where φ represent the latitudes, and λ represent the longitudes.
Reference: https://www.sisense.com/blog/latitude-longitude-distance-calculation-explained/
Also you can check this page for using javascript.
https://www.movable-type.co.uk/scripts/latlong.html
Remember that latitude and longitude originally are writed on degrees, I think you first need to know how much distance represents 1º, on some books and websites it says that 1º is about 111km depending how near is the spot from the equator line, so (more or less):
1º - 111km, also 1º equals 60'
then 1' should be 1.85km, and 1' equals 60"
then 1" is more or less 0.03km
so 32.4324" is about 1km
Now... basically you need to now the limits of a square based on the initial location, for this just add/substract 32.4324" to latitude and longitude, so give it a try.. lets go to las vegas (use google maps)
36.1699412,-115.1398296
This locations is on a sexagesimal notation son lets convert 32.4324".. its simply... just divide it on 3600 and that is 0.009009009, this is the value you must add/subtract to/from latitude/longitude
north bound, after add: 36.1789502
south bound, after substract: 36.1609322
east bound, after add: -115.1308206
west bound, after substract: -115.1488386
now on gmaps try to locate these bounds for ex (north bound: 36.1789502,-115.1398296) you will see is just above original location, you can also measure distance from original location up to 1km and that is more or less near to the north bound you just calculated.
so now, just query your database and filter it where latitude is between north bound(36.1609322) and south bound(36.1789502), and also longitude is between west bound(-115.1488386) and east bound(-115.1308206) and that should do the work. So the magic is just to add/substract 0.009009009 to any location point.

MYSQL - fastest way to get points around coords [duplicate]

This question already has answers here:
MySQL Great Circle Distance (Haversine formula)
(9 answers)
Closed 6 years ago.
I'm trying to get points around "me" by location and it's pretty simple :
select * from X where ((SQRT(POW(69.1 * (a.lat - 49.201441 ), 2) +
POW(69.1 * (16.161299 - a.lng) * COS(a.lat / 57.3), 2))) <='1') LIMIT 5
*
my location = 49.201441;16.161299
distance = 1 (mile)
This query returns me 5 points around "me" at a distance of 1 mile. This is rly fast, but just when my table have a ... I don't know, maybe 5000 rows.
I'm using this query on 200 000 rows table, and it's very slow! Maybe .. 2-7 sec and even if the limit is 1 = no difference.
Can someone explain it to me and help me? Thanks a lot guys!
BTW: If my query does not contains this part of query = it takes maybe 0.0008s... so second part of query is correct.
I have used this for finding people near you.
table name: user_location
id|username|latitude|longitude
i am not sure that the distances is for a mile, but what this does is takes the users lat minus each persons from the database. If the users lat and long are within 1 it will be put into the results.
The biggest problem is 1 isn't equal to 1 mile. it is closer to 10miles i believe (it was a while ago and might not be 10 miles i can't remember), but you can always change this. Another problem is that you basically always have to update people's locations. Which isn't that bad, but if you have a slow server with a lot of users it can slow you down.
It is fast and works... Not the best solution, but might work for you. For me it atleast showed a nice surrounding area.
$query = "SELECT * FROM `user_location` WHERE (".$user_lat." - latitude) <= 1 AND (".$user_lon." - longitude) <= 1 LIMIT 100";
I tested this with 10,000 lines and it was just under 3 seconds with 254 people near me. (randomly generated content)

Calculating a distances using eastings and northings UK (ordnance survey)

I have downloaded the ordnance survey which contains the postcode eastings and northings of all UK postcodes and I would like to perform a mySQL query which calculates and shows the results of a given distance.
Firstly I need to match up all records in properties to the postcode table to show each properties easting and northing joined into the results.
I then need to calculate the distance between the given postcode and each property record and display only the ones which fall within the given distance.
I have found lots of examples for using long/lat but I cannot seem to find any good examples for using the ordance survey easting and northing system. According to the ordenance survey guide I should be getting an answer in metres for using the full 6 digits.
I am also getting this error:
errorErrormessage: BIGINT UNSIGNED value is out of range in '(((mjm.pc.Eastings - 436421) ^ 2) + ((mjm.pc.Northings - 291786) ^ 2))'
When trying to test the query:
$query = "
SELECT * , SQRT( (pc.Eastings - {$e1})^2 + (pc.Northings - {$n1})^2) AS distance
FROM properties p, postcodes pc
WHERE concat( p.POSTCODE1, p.POSTCODE2 )= pc.Postcode HAVING distance <= 10
LIMIT 0 , 30
";
Can someone help me understand what I need to do to make this work please?
^ is the XOR operator, not the square. Can you try this?
SQRT( POW(pc.Eastings - {$e1}, 2) +
POW(pc.Northings - {$n1}, 2)) as distance

Mysql Group ''close'' float ( lat / long )

Background /
Currently right now we have a 100 or so Lat/Lng wich get mapped onto google maps. The aim is to show the hot spot location of these by selecting from the database La/Lo values that are within a few meters of each other.
The group values will then be used to find the central point and draw a circle on the map of the hot spot.
Current setup /
Currently the datase we are requesting from has just id(int),La(float),Lo(float)
Concept /
What i ''think'' is needed is this
Select * from table
Group by (
( La + 0.30 && La - 0.30) && ( Lo + 0.30 && Lo - 0.30)
)
First off, the earth is not a square so to get accurate distances you will need to use a haversine function (look it up), however, for distances of a few metres , maybe accuracy doesn't matter.
Second, the distance between degrees of lattitude varies between 110.574 and 111.694 km and for degrees of longitude between 111.32 and 0.0 km (yes 0.0km at the poles). In any case 0.3 is somewhere between 0 and 35,000 m - not exactly "a few" unless your hotspots are at the north and/or south poles.
Third, ignoring the bad geography, the SQL statement you are groping for will require a cross join and sorting on calculated distances and will be very slow even for a small data set - you need to look at using whatever support mysql has for native geography types. I know SQL Server has them and I suspect MySQL does too.
Edit
It does, see this question.

PHP: How to create a Geo-Fence(bounding Box) using the Distance from a set of Coords

How would i create the points of a Geo-Fence(bounding box) using lat and lon and a distance.
I have the lat and lon of the center point
I have the geofence distance.
What would the logic be to create the geo-fence around these multiple points?
thanks for any help.
1 Convert center lat / lon to cartesian (x,y) in units meter.
Then you do all geometry as you have learned in school:
2 Create one corner point of the square, using polar coordinates formula
phi = 45 * TO_RADIANS;
corner.x = tcenter.x + r * sin(phi);
corner.y = tcenter.y + r * cos(phi);
where r is the length in meter of the half diagonal of your bounding box square
do the same for the other points by using phi =(90*i + 45), i= 0..3
3 transform corners (x/y) back to lat/lon using the inverse transformation
If you have a lat/lon point and a distance and you want to find other lat/lon points, this is called a bearing-range problem. See the section Destination point given distance and bearing from start point at the website http://www.movable-type.co.uk/scripts/latlong.html
If you want the box (fence) parallel to the equator, then a bearing for the north-east corner of your box will be 45 degrees (don't forget to convert to radians before using the equations). Then add 90 degrees to get the next corner point until you have done all 4 points.

Categories