Google Maps RouteBoxer in PHP
If you've used Google Maps API to plot a route, and then tried to find locations near that route, you'll likely have come across their RouteBoxer utility, included in the V3 utility library. Either that, or you're using a database with OpenGIS spatial capabilities, like PostgreSQL.
Essentially, RouteBoxer lays a grid over your route (which will typically come from the Google Maps DirectionsService), figures out which grid cells overlap the route, and then merges the cells until you're left with the least number of cells, or boxes, covering your route. These can then be used to query a database for locations that fall within these boxes.
The second distinction is an important one. Especially if your route is long and/or complex, and especially, especially, if your browser is IE. Some browsers may give up and throw a "script unresponsive" dialog after 10 seconds of crunching the grid cells, looking for those that cover your route. Even worse, IE will give up much sooner, because it has an additional limitation of 5,000,000 instructions, which you'll burn through quickly, looping over a massive grid. Again, this will depend of the length, angle, and complexity of your route, and the size of grid you've specified for RouteBoxer.
So, what to do, if you absolutely must provide your client a solution to allow routing across a continent, finding nearby locations along the way, and not throw that pesky "unresponsive script" dialog or, worse, grind the browser to a halt? Use a spatial database! Ok, so what if the client doesn't have one, and isn't about to change their production environment? Move RouteBoxer server-side! That's what I did.
Update May 27, 2013: I finally moved this code to Github - jkoreska/RouteboxerPHP
So, without further delay, here is RouteBoxer, transcribed into PHP: RouteBoxerPHP.zip
The archive includes:
- RouteBoxer.class.php - the transcribed code, including minimal implementations of LatLng and LatLngBounds in PHP.
- routeboxer.php - some php code to accept raw, POSTed JSON of the route_overview LatLng array.
- routeboxer.html - a demo page that gets directions and POSTs the route_overview array, then draws the resulting boxes over the route.
- json2.min.js - an excellent utility lib from Douglas Crockford himself to JSON-encode the route_overview array.
That should be all you need to get going. Please note that the code was transcribed verbatim, with no effort to optimize it. My hope is to find time to improve the efficiency of the PHP code, like, for instance, not instantiating massive, empty arrays, but that's for another day (or another developer?). Enjoy.