Geocoding a very long list - php

I have a database table filled with addresses, the table is over 4,000 records long
I am wondering the best way to get the addresses compare it with a search field and sort them by distance from the search field location? GoogleAPI documentation says the requests are limited to like 25,000 per day does that mean I can only do 7 searches per day?

In my opinion - yes. Google is smart about calculating distance between 2 LatLng's, because gives you distance using streets and roads, not distance in a straight line between 2 points (which would be easy to calculate in php).
Saving LatLng's of those 4000 addresses wouldn't do you any good, because you still need to ask google about the distance from a user's address to each of them. You can't calculate that yourself even if you have all the LatLng's (you need the map).
I guess you could save each user input, and save that address with 4000 distances to each location... but that would only be useful for a user returning to the site for the 2nd time.
...
Ok, I have this idea:
Do store the LatLng's of each of the 4000 locations.
Store distances between all 4000 locations (so that if you pick one, you could get the list of the all the others, ordered by distance).
When you get the address from a user, convert it to a LatLng, and use simple mathematics to find the closest location in a straight line.
Using the list of distances to all the other locations from database, ask google to get the accuall distance to that location, and about 10-20 to locations closest to it; for the rest use the distances from the closest from the database.
This way you'd get the first 10-20 accurate distances to the closest locations from user input, and the rest would be pulled from the database - they would actually be distances from the closest location to the other locations.

I believe that since the addresses don't change that much, you can cache the latitude/longitude somewhere and refer to those instead of making repeated requests. Please elaborate if there are other mitigating conditions, of course.

Related

Combining SQL results into groups based on column value

I have a table with over 2 million rows. One of the values is an address. Some rows have a common address. I am using php.
On my website, I want the user to put in their zip code, and I will return all results within that zip code. I would then use Google to Geolocate them on a map. The problem is that since Google charges by the query, I can't be wasting time and money requesting coordinates for an address I already have. Here is what I believe to be the correct approach:
Ask user for zip code
Run "Select * with 'Zip Code' = $user_zip" (paraphrasing)
Run a Geolocate on first address and plot on map
Check for matching addresses in result and group with the mapped result
Find next new address
Repeat 3-6 until complete
Is there a better way to approach this? I am looking for efficiency, easy way to manipulate all matching results at once, and the least amount of queries. If my way is correct, can someone please help me with the logic for numbers 3-5?
If I understand this right what you are trying to do is to render a map with markers for each record in your database that is within a certain zip area. And your challenge is that you need coordinates to render each marker. The biggest issue with your approach in terms of wasting resources is that you do not store the coordinates of each address in your database. I would suggest you to:
1 - Alter the endpoint (or script or whatever) that creates these records in your db to fetch the coordinates and store them in the database.
2 - Run a one time migration to fetch coordinates for each record. While I understand that doing this for 2 milion rows could be "costly" with Google's Geocoding (Estimate is 1000$ for 2 milion api calls). To save the costs you could look into some of the opensource map tools.
Either way fetching coordinates during the request lifecycle is both a waste of resource and it will significantly affect speeds.

Location/Proximity search on large record set

Say I have a database table representing users with potentially millions of records (Wishful thinking). This table contains a whole bunch of information about each user including information about their location:
City
County/State etc
Country
Latitude
Longitude
Geohash based on the latitude/longitude values.
I would like to implement a feature where by a logged in user can search for other users that are nearby.
Ideally, I would like to grab say the 20 users that are geographically closest to the user, followed by the next 20, and the next 20 etc. So essentially I want to be able to order my users table by the distance from a certain point.
Approach 1
I have some previous experience with the haversine formula which I used to calculate the distance between one point and a few hundred others. This approach would be ideal on a relatively small record set but I fear it would become incredibly slow with such a large record set.
Approach 2
I've additionally done some research into geohashing and I understand how the hash is calculated and I get the theory behind how it represents a location and how precision is lost with shorter resolutions. I could of course grab the users that are located near the user's geographical area by grabbing users that have a similar beginning to their geohash (Based on a precision I specify - and potentially looking in the neighbouring regions) but that doesn't solve the problem of needing to sort by location. This approach is also not great for edge cases where 2 users may be very close to one another but lie close to the edges of 2 regions represented by the geohash.
Any ideas/suggestion towards the approach would be greatly appreciated. I'm not looking for code in particular but links to good examples and resources would be helpful.
Thanks,
Jonathon
Edit
Approach 3
After some thought I've come up with another potential solution to consider. Upon receiving each user's location information, I would store information about the location (town/city, area, country, latitude, longitude, geohash maybe) in a separate table (say locations). I would then connect the user to the location by a foreign key. This would give me a much smaller dataset to work with. To find nearby users I could then simply find other locations that are close to the user's location and then use their IDs to find other users. Perhaps some sort of caching could be then implemented by storing a list of the nearby location IDs for each location.
You can try a space filling curve. Translate the co-ordinate to a binary and interleave it. Treat it as base-4 number. You are also wrong a geohash can be used to sort also by location. Most likely use a bounding box and filter the solution and then use the harvesine formula.

jquery autocomplete for shops near location

I've got a list of shops that I have put in a javascript array. I have their addresses as well.
I'm needing to create an autocomplete which allows me to put in a city name and it displays the 3 nearest to that location. I imagine it will need to interface with google's apis some how but not sure where to start.
I've got the actual autocomplete jquery stuff working on an ajax script, but I don't know how to get things located nearest.
You need the lat/long locations of the stores, https://developers.google.com/maps/documentation/geocoding/ Then you need the lat/long location of the user, with some relatively simple mathematics you can then calculate the distance between these two points:
$distance = round((6371*3.1415926*sqrt(($lat2-$lat1)*($lat2-$lat1) +
cos($lat2/57.29578)*cos($lat1/57.29578)*($lon2-$lon1)*($lon2-$lon1))/180), 1);
If you have a large number of stores and a large number of users I advise caching these distances in a mysql table, you have to do this for each store in your database. So you create a table for each e.g. zipcode that requests this and put up a cron to remove these tables every hour or so.
So the process:
User asks for the nearest store
You get his location through google api (or your own storage)
Check if there's a table for his location
If yes, give him the results directly, if no generate the table and give him the results
Mind that google only allows a limited number of data requests. Even though this number is huge (I believe 25.000 requests per day) it may be advisable to store the lat-lon locations of your stores AND users. Would also improve the speed.
I made something similar to this, I fetched the lat/lon locations at the moment a location was inserted into the database and inserted it in a seperate per-zipcode lat/lon table.

How to quickly determine if multiple places are within users vicinity - Google Places API

I am designing a web app where I need to determine which places listed in my DB are in the users driving distance.
Here is a broad overview of the process that I am currently using -
Get users current location via Google's map api
Run through each place in my database(approx 100) checking if the place is within the users driving distance using the google places api. I return and parse the JSON file with PHP to see if any locations exist given the users coordinates.
If place is in users driving distance display top locations(limited to 20 by google places), other wise don't display
This process works fine when I am running through a handful of places, but running through 100 places is much slower, and makes 100 api calls. With Google's current limit of 100,000 calls per day, this could become an issue down the road.
So is there a better way to determine which places in my database are within a users driving distance? I do not want to keep track of addresses in my DB, I want to rely on Google for that.
Thanks.
You can use the formula found here to calculate the distance between zip codes:
http://support.sas.com/kb/5/325.html
This is not precise (door-step to door-step) but you can calculate the distance from the user's zip code to the location's zip code.
Using this method, you won't even have to hit Google's API.
I have an unconventional idea for you. This will be very, very odd when you think about it for the first time, as it does exactly the opposite order of what you will expect to do. However, you might get to see the logic.
In order to put it in action, you'll need a broad category of stuff that you want the user to see. For instance, I'm going to go with "supermarkets".
There is a wonderful API as part of google places called nearbySearch. Its true wonder is to allow you to rank places by distance. We will make use of this.
Pre-requisites
Modify your database and store the unique ID returned on nearbySearch places. This isn't against the ToS, and we'll need this
Get a list of those IDs.
The plan
When you get the user's location, query nearbySearch for your category, and loop through results with the following constraints:
If the result's ID matches something in your database, you have that result. Bonus #1: it's sorted by distance ascending! Bonus #2: you already get the lat-loc for it!
If the result's ID does not match, you can either silently skip it or use it and add it to your database. This means that you can quite literally update your database on-the-fly with little to no manual work as an added bonus.
When you have run through the request, you will have IDs that never came up in the results. Calculate the point-to-point distance of the furthest result in Google's data and you will have the max distance from your point. If this is too small, use the technique I described here to do a compounded search.
The only requirement is: you need to know roughly what you are searching for. However, consider this: your normal query cycle takes you anywhere between 1 and 100 google Queries. My method takes 1 for a 50km radius. :-)
To calculate distances, you will need Haversine's formula rather than doing a zip code lookup, by the way. This has the added advantage of being truly international.
Important caveats
This search method directly depends on the trade-off between the places you know about and the distance. If you are looking for less than 10km radii, use this method to only generate one request.
If, however, you have to do compounded searching, bear in mind that each request cycle will cost you 3N, where N is the number of queries generated on the last cycle. Therefore, if you only have 3 places in a 100km radius, it makes more sense to look up each place individually.

XML search or DB search / javascript (client side) or php (server side) calculation

Let's say your site has 200,000 unique users a day. So, your server is heavily loaded/pounded; and you do NOT have resources to buy a bigger/better server. So, you are stuck with what you have.
Now, whenever a user comes to your site, you need to do some calculation (calculate distance between user city as detected via GeoIP and some whitelist of cities, figure out the nearest city within 140 mile radius).
Would you do this calculation via PHP or via JavaScript?
First, would you precalculate all nearby cities within 140 mile radius of whitelisted cities? For eg: Whitelist city 1 can have 20 nearby cities. Or would you do on-the-fly calculation everytime?
For eg:
Whitelist = Detroit, MI
and nearby city = Kalamazoo, MI (140 miles)
Second, if pre-computed: would you store this in XML file or some MySQL table? Now, we just have to search through a table (mysql or xml no more than 1 mb in size). I am guessing this would be inefficient because client browser (JavaScript) would have to download 1mb xml and search through it. This would make page load time even slower. Using DB might be faster but then DB load increases (if 200,000 unique users are trying to load the page over the course of a day).
Maybe the best way to do would be to do precompute, store precomputed results in XML, and then use PHP to search through XML and find nearest whitelisted city to user?
If you, the site, are actually relying on the city information, then you must do the calculation on the server.
Database queries are almost always going to be faster than XML searches for sufficiently large XML files. You can optimize the query, MySQL will cache things, etc.
Pre-calculating all city-city distances would be a way to go, for sure. GeoIP doesn't only provide city names, it does give actual latitude/longitude locations as well. I'm sure that the possible list of cities changes rather constantly, too.
I would look into using the geospacial capabilities of MySQL. General over view of searching by coordinates here:
Fastest Way to Find Distance Between Two Lat/Long Points
In short what you will do is setup a database of the cities you care about, with their lat/long, and query that table based on the GeoIP provided lat/long.

Categories