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
Related
I am developing a travel portal website.
Presently I am working on the destination module.here I need to display the nearest cities based on the places entered.
for example,If any one enter the name bangalore,The nearest cities around bangalore city should display.
I am searching for the google api to get the nearest cities around a place.
Can anyone help me to get the best api to display the nearest cities ??
Thanks In advance
This might be an alternative for you,
Another option:
Download the cities database from http://download.geonames.org/export/dump/
Add each city as a lat/long -> City mapping to a spatial index such as an R-Tree (some DBs also have the functionality)
Use nearest-neighbour search to find the closest city for any given point
Advantages:
Does not depend on aa external server to be available
Very fast (easily does thousands of lookups per second)
Disadvantages:
Not automatically up to date
Requires extra code if you want to distinguish the case where the nearest city is dozens of miles away
May give weird results near the poles and the international date line (though there aren't any cities in those places anyway
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.
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.
In my database I have a list of places and for each I have a street name and number, postcode, city and county. Some of them have a latitude and longitude location.
And I have the geo location of the city centre for example. I would like to display only the places that are within X miles of the city centre on a google map.
Incase this would need a geo location for each of my places to work, I could perhaps set up a script to use google maps api to use geocoding to get a geo location for all my places and update the database with the lat/lng. Then I would have a database full of lat and long locations to work from.
Once all the places have a lat/lng then maybe mysql can return the within range addresses?
This is not hard once you have lat / long data, and if somebody gives you the great circle distance formula in mySQL format.
#maggie gave a good reference. How to efficiently find the closest locations nearby a given location
Indexing strategy: Keep in mind that one minute of latitude (1/60 degree) is one nautical mile, or 1.1515 statute miles (approximately) all over the world. So index your latitude column and do your search like this. (If you're in the part of the world that uses km, you can convert; sorry for the Old-British-Empire-Centric answer, but they did define the nautical mile.)
WHERE mylat BETWEEN column.lat-(myradius*1.1515) AND column.lat+(myradius*1.1515)
AND (the big distance formula) <= myradius
This will give you both decent data base indexing AND reasonably accurate distance circles.
One extra refinement: You can index longitude too. The trouble is that ground distance isn't directly related to longitude. At the equator it is one nautical mile per minute, but it gets smaller, and at the poles there are singularities. So, you can add another term to your WHERE. It gives correct results but isn't as selective as latitude indexing. But it still helps the indexing lookup, especially if you have lots of rows to sift through. So you get:
WHERE mylat BETWEEN column.lat-(myradius*1.1515) AND column.lat+(myradius*1.1515)
AND mylon BETWEEN column.lon-(myradius*1.1515) AND column.lon+(myradius*1.1515)
AND (the big distance formula) < myradius
Most likely you want to use a space-filling-curve or a spatial index to reduce your 2D problem to a 1D problem. For example you can combine the lat/long pair with a z-curve or a hilbert curve. I use for myself a hilbert curve to search for postcodes. You can find my solution at phpclasses.org ( hilbert-curve ).
So here's the issue... I have a field where users can type in their address (which will be GeoCoded via Google Maps API).
I have several addresses of widgets in my database (saved as address.. again can easily be geocoded).
What I need is for the user to type in their address and for a list of my widgets to come up based on distance from their address. I have THOUSANDS of addresses for my widgets and users have an infinite number of addresses obviously.
Any ideas?
Thanks.
SELECT latitude, longitude, SQRT( POW( 69.1 * ( latitude - 52.58 ) , 2 ) +
POW( 69.1 * ( - 1.12 - longitude ) * COS( latitude / 57.3 ) , 2 ) ) AS distance
FROM location ORDER BY distance
Click Here
They provide several ways of calculating the distance - choose what works best for you.
If you are storing the items in a MySQL DB, then here's the basis what you need
You really CAN'T use google to calculate your geo distance filtering. To do that, you would have to send them YOUR data, have them store it, and query it for you. They may offer that service, now, or in the future, but I haven't heard of it.
In order of more legal, more capable, more expensive:
A/ As SINGLE points or locations of interest are input by customers of your site, collect the geo coordiniates. Then use your own search engine and search by distance from a point. MAY be a violation of the agreement with google, but they do mention 'caching' results to take the load off their servers. (The reason is my personal guess.)
B/ Use google to do bulk geocoding, perhaps ONE AT A TIME, to a max of 5000 per day per your site's IP Address last I saw. Not even sure if that is not a violation of the use agreement.
C/ Purchase a contract with a geocoding service, and store what they geocode for you.
D/ Purchase a geocoding library and do your own geocoding.
This blog post, "Calculate Distance using Google Maps API", may be of some assistance.