show restaurants within 100 miles - php

I have a master zip code table tbl_zipcode with all latitude and longitude values. Also a restaurant table with restaurant list with zip codes.
Now I want to show the restaurants within 100 miles from user location i.e. from session user. How can I write a function which returns all the restaurants within 100 miles?
Any help is appreciated!!
Thanks.

So basically you have the longitude and latitude of the user and of all the restaurants..
check haversine formula
this is helpful: http://www.movable-type.co.uk/scripts/latlong.html
To implement the formula is pretty simple

Determine all of the ZIP codes in a 100 mile radius from where you want to start (which is the current ZIP code based on the position of the session user), and include all Restaurants with those ZIP codes.

You need to device a way to calculate the distance between the user to those zip code's lat long.
Source: http://www.movable-type.co.uk/scripts/latlong.html

First thing would be to get the lat/long values of the current user's zip code.
SELECT latitude,longitude FROM tbl_zipcode WHERE zipcode = <USER_ZIPCODE>
Then you can use those values to calculate the distance for each coordinates pair in the database, e.g. by using this script (written in PHP so no time wasted thinking about Java functions).
But you might want to think about caching since it's a pretty heavy operation to do for each coordinates pair. Maybe you can precalculate those values and update the database each time a new restaurant comes in or so.

Related

Find data from table using radius check in geomatry column

I have table "vehicle_location" and "coordinates" column in table datatype is geomatry
and in my controller i am getting lat and long and radius in request so i want to find vehicle location data using radius
Have a look at the formula explained on Wikipedia: https://en.wikipedia.org/wiki/Great-circle_distance
You'll find someone asking about the same question here: Measuring the distance between two coordinates in PHP
Ideally, it would be good to be able to reduce the calculation of distances to only cars that are not to far from your location. So typically, I would start by an SQL query that only returns the vehicules which have latitude and longitude values in the nearby, according to the given radius.
Then, in a second step, you can calculate all the distances between these cars and your position, with the algorithm (which takes some calculation time) and sort them after.
The ideal thing to do is to try and do the calculation directly in SQL if possible, so that you can sort them and filter them with the radius. If it gets to complicated then do the calculation and sorting in PHP.

how to implement the query based on the places range from x minutes to xx minutes time for drive?

There are some places I can choose from. I want to choose one to be my source place, and select driving time cost is less than 30 minutes. So there are maybe some places I can drive there cost less than 30 minutes will be showed.
So, what is the best way I should to save all these places data and query them on specific conditions?
Before I asking this question, I've tried to save all these places latitude and longitude. Whenever a new place has been saved to the database, I will request HERE map routing API to calculate distances and drive time between the new one with all old places info in a database, then save them in the distance table.
When a user wants to query places like the above example. I will join places table and distance table to query like:
SELECT place.id, place.name from place join distance on place_id = place.id where distance cost_time < 30;
There are some problem make me upset. If the number of old places is too big(actually it will), the time hanging after saving a place to the database will be much more.
So, I know I used a bad method to implement my goal. But I don't know how can I do, can someone help me with this problem?
last but not least, forget my poor English, if something is unclear, I'll try my best to describe it. Thank you.
You probably need to build a connected graph and compute the distances to other points on the fly.
When a new point is added, compute its distance with the X nearest neighbours only and store them in a database.
Then, you can use a algorithm like Dijkstra to find all the points at less than 30 units from your source.
You will lose some precision, as the cost to drive from A to C, then C to B will be usually greater then the direct path from A to B. And the time you saved on adding a new point, you will "lost" it to do the computation of the Dijkstra algorithm.

How to Query Mysql based on GPS latitude and longitude columns based on relative distance

In an app I'm building, One of the features i'd like users to be able to discover people around them easily. I'm using the GPS to get the latitude and longitude, then storing that information in the mysql db along with the other user information under a column for latitude and another with the longitude. What's would the best practice be to do a query that looks at the person whos making the query's information...and then have it find the closest possible relatable lat and longitude then start there and limit it to 24 results? And furthermore, how would I remember where it stopped so I could allow another query to start where it left off and return more getting further and further away
Basically, to generalize how can I do a mysql query that starts as close as it can to 2 latitude and longitude points that I supply and then have it grab the next 24 sorted by closest to furthest?
I feel like its going to be hard to do because its being based on 2 columns. Is there a way I should/could be combining the GPS values into 1 column so it will be easy to find relative distance?
Maybe I could somehow get the zip code (but then that might cause non US problems). I'm not sure. I'm stuck.
Just search for "Haversine Formula" here on Stackoverflow and you will find several related questions.
As #cdonner mentioned, there are a number of resources for the Haversine formula which you use to transform lat and long into distance. You would pass in a distance variable based on how your formula is set up, usually based on miles and run your query starting at the closest radius. Using a php loop, you can simply increase the distance and re-run the query until you get the desired number of results. And do check out that google link re #Maleck13 as well, very helpful.

Locate nearest major city

I'm working on a website that allows users to find our nearest Motel location (There are 26 of them across the US). I have a list of cities where they are located at.
I want to display the nearest location when a user goes on our front page. For example if a user comes from Newark, NJ, he will be shown images from our NYC motel and if a user comes from San Jose, CA he will be shown San Francisco images.
What's the best way to do this? Does anyone know any examples out there on the web that shows what I'm trying to do? Is this even possible?
I saw Groupon and LivingSocial using this so I thought why dont I give it a shot. :)
If you're using apache, you can give geoip a try.
http://www.maxmind.com/app/mod_geoip
You'd first need to store the latitude/longitude coordinates of your motels in a database - use google maps, it won't take too long with 26.
Then get the visitor location, using something like IP2Location - http://www.ip2location.com/developers.aspx
Then calculate the distance between the visitor and each of your motels - http://sebastian-bauer.ws/en/2010/12/12/geo-koordinaten-mysql-funktion-zur-berechnung-des-abstands.html (it is in English...)
You could give Geolite city a try. It is free (with an attribution clause) or can alternatively be bought. That reduces the "find closest city to user's IP address" problem to "find the closest city to a known city".
The same company offers a city database, which among other things contains longitude/latitude. That should do the trick.
You can get the nearest city to an IP address using the free data on MaxMind.com (I beleive you can pay for more accurate databases). If you can get the lat/long for the city and compare it to the lat/long for each of your motels you win :)
What you want is to store the lat/lng coordinates of the motels and then let the user type his location into the browser most likely a zipcode and then you want to use the harvesine formule to calc the distance between the user and the motel to display nearby motels. Or you can use a IP to geo coordinate service like IP2location to get the users location.
I used this code to calculate distance of a googlemaps latitude and longitude from a table of addresses.
Geocode was a function that returned an array of latitude and longitude from google maps api given an address string, in the case below a zip. The table of your locations would have to include lat and lng columns. In this example i used decimal(8,5) types but you could also use a point column type.
$starting_location = geocode($zip);
$distance = '(3959 * acos(cos(radians('.$starting_location['latitude'].')) * cos(radians(lat)) * cos(radians(lng) - radians('.$starting_location['longitude'].')) + sin(radians('.$starting_location['latitude'].')) * sin(radians(lat))))';
$location_row = query('SELECT location_id,addr,addr2,city,state,zip,phonenumber,'.$distance.' AS distance FROM location_info WHERE '.$distance.' is not null ORDER BY distance LIMIT 1');
Correct me if I am linking to another's answer incorrectly, but I think I got my direction from this question: Fastest Way to Find Distance Between Two Lat/Long Points

Fastest way (and most optimized) to calculate and sort users by ascending order of zip code distance

I have a system which will return all users from the database and order the results by lowest distance from a reference zip code.
For example: User will come on the site, enter zip code and it will return him all other users who are nearest to his zip (ascending order)
How am i doing this now and why is it a problem ?
The system contains more than 30 million users and their zipcodes. I am retreiving all the users in a particular state and city (narrows the dataset down to about 10,000).
This is where the problem actually happens. Now, all the result sent by mysql (10,000) rows to PHP are sent to a zipcode calculator library which calculates this distance between the base zip code and user's zip code - 10,000 times. Then orders the result by the zip code nearest.
As you can see, this is very badly optimized code. And the 10,000 records are looped through twice. Not to mention the amount of RAM each httpd process takes just transferring data to and fro mysql.
What I would like to ask the gurus in here that is there anyway to optimize this ?
I have a few ideas of my own, but i'm not sure how efficient they are.
Try to do all the zipcode calculation and ordering in mysql itself and return the paginated number of rows.
For this, i will need to move the distance between zipcode calculation logic to a stored procedure. This way I am preventing the processing of 10,000 records in PHP. However, there is still a problem. I would not need to calculate distance for zip codes which have already been calculated (for 2 users having the same zip code).
Secondly, how do i order rows in mysql using a stored procedure ?
What do you guys think ? Is this a good way ? Can i expect a performance boost using this ?
Do you have any other suggestions ?
I know this question is huge, and i really appreciate the time you have taken to read till the end. I would really like to hear your thoughts about this.
As I'm not overly familiar with PHP or MySQL, I can only give some basic tips but they should help. This also assumes you have no direct way of interfacing with the zip library from MySQL.
First, as it's doubtful that you have 10k zip codes in a city, take your existing query and do something like
SELECT DISTINCT ZipCode FROM Users WHERE ...
This will probably return a few dozen zip codes max, and no duplicates. Run this through your zip code library. That library itself is probably a source of slowness, as it has to look up the zip codes, and do a bunch of fancy trig to get actual distance. Take the results of this, and insert it into a temp table with just the zip code and the distance.
Once done with that list, have another query that gets the rest of the user data you want, and JOIN into the the temp table on zip code to get your distance.
This should give you quite a large speedup. You can do whatever paging you need in the second query after the results have been calculated. And no more looping through 10k rows.
I suggest that you narrow the latitude and longitude ranges before you compute the accurate distance for filtering and sorting purposes.
What I mean is if you do a full table scan and compute distances for all zip codes in the database relative to your reference point, it will be very slow.
Instead, filter zipcode by proximity. I mean if you have latitude 10 and longitude 20, first compute the maximum angular range for the proximity you want. Lets say you want a proximity range of 10 miles. That may translate into 0.15 degrees. So you need to filter you zip codes first latitude between 10-0.15 and 10+0.15 and longitude between 20-0.15 and 20+0.15 .
Only after that you include the accurate distance clause in your SQL query condition. That will be much faster because you no longer do full scan and you can eventually use range indexes on longitude and latitude fields.
To translate miles into degrees find the narrow range, keep in mind that the Earth has , approximately 25,000 miles of perimeter, divide 25000 by 360 degrees which gives 70 miles per degree. If you want a range of 10 miles, your range in degrees will be at most 0.15 degrees.
Keep in mind that these calculations are not accurate (the Earth is not exactly well rounded) but that is not important. What is important is that you find a degree range value that is higher than the really accurate value.
If you can get the latitude and longitude for all zipcodes into MySQL, or have an easy way of fetching the lat/long for your base zipcode and feeding it into your MySQL query, then you can order your 10k users by distance inside MySQL. There is a very similar question and answer here which gives you the correct math for the distance function. You may also want to investigate Mysql spatial extensions which would let you insert and index your lat/longs as 2D POINT data.

Categories