Learn how to build location-based website pages using HubDB.
Find the visitor
Build a database
Create a simple listing page
<body>
tag, using the table ID you noted above.Filter to a single listing
set table_id...
line here and in all other code samples on this page.row_id
which is the unique ID of this row. Note the use of request.query
to make sure any existing query string parameters are preserved on the current URL.Now we’ll add the details:{% if request.query_dict['row_id'] %}
) determines whether to show the details or skip down to the block to show the listing. It will look something like this:Determine the visitor
if
statement. In the default case, it asks the visitor to share their location. If they accept, it redirects the page with lat
and lon
query parameters. The second time the page loads, it shows the list, now with a third column that is the calculated distance from the provided location.Since row.location
just returns the restaurant’s coordinates, HubSpot uses the geo_distance
filter to calculate the distance. It takes the visitor’s latitude, longitude and the units of the distance. The units default to meters (“M”), but also accept kilometers (“KM”), miles (“MI”), and feet (“FT”). Lastly, HubSpot round the number a bit to make it more readable.Sort the list
hubdb_table_rows
function. Change this section as follows:geo_distance
ordering function which ends up looking like orderBy=geo_distance(42.37,-71.076)
. To sort the list in reverse order, with the restaurants the furthest away first, you can prepend a -
(minus sign) to geo_distance
.Filter by distance
geo_distance
as a query filter.geo_distance(location,42.37,-71.076,mi)__lt=1.0
The geo_distance
query filter takes four arguments. First is the location column that you want to filter by. The next three parameters are latitude, longitude, and distance units. After the geo_distance
operator, specify the filter operator, “less than” or “lt”. Finally, after the equal sign is the value to compare with the result of the function.Add a map
elif request.query_dict['lat']
) with this:geo_distance
function which can be used to filter, order, and calculate the distance. This simple page could be enhanced by adding a toggle between the listing and map view, a map and more info on the details page, and perhaps a link to each restaurant’s website.If the visitor’s browser cannot determine their location, or they want to look for places in a different area, you can allow them to search for a location using the Google Maps Geocoding API.