### Install PyGeoHash
Source: https://context7.com/wdm0006/pygeohash/llms.txt
Install the core library or with optional visualization support.
```bash
# Core library (no dependencies)
pip install pygeohash
# With visualization support (matplotlib + folium)
pip install pygeohash[viz]
```
--------------------------------
### Install PyGeoHash
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/index.md
Install the PyGeoHash library using pip. This is the basic installation.
```bash
pip install pygeohash
```
--------------------------------
### Generate Visualization Examples
Source: https://github.com/wdm0006/pygeohash/blob/master/README.md
Generate example visualization images and maps using the provided Makefile command.
```bash
make viz-examples
```
--------------------------------
### Install PyGeoHash
Source: https://github.com/wdm0006/pygeohash/blob/master/README.md
Install the library using pip. Use the [viz] extra for visualization support.
```bash
pip install pygeohash
pip install pygeohash[viz]
```
--------------------------------
### Install Visualization Dependencies
Source: https://github.com/wdm0006/pygeohash/blob/master/README.md
Install the necessary dependencies for PyGeoHash visualization features using make.
```bash
make install-viz
```
--------------------------------
### Validate Inputs at Function Start
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/types.md
Illustrates the best practice of validating all inputs immediately at the start of a function using assertion functions to ensure data integrity.
```python
from pygeohash import assert_valid_geohash, assert_valid_latitude, assert_valid_longitude
def process_location(geohash: str, lat: float, lon: float) -> None:
# Validate all inputs immediately at function start
validated_geohash = assert_valid_geohash(geohash)
validated_lat = assert_valid_latitude(lat)
validated_lon = assert_valid_longitude(lon)
# Rest of the function can assume valid data
...
```
--------------------------------
### Install PyGeoHash with Visualization Support
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/index.md
Install PyGeoHash with optional visualization dependencies using pip. This enables plotting functionalities.
```bash
pip install pygeohash[viz]
```
--------------------------------
### Visualize a Geohash
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/index.md
Example of plotting a geohash using the visualization module. Requires Matplotlib and Folium to be installed.
```python
import pygeohash as pgh
from pygeohash.viz import plot_geohash
import matplotlib.pyplot as plt
# Plot a geohash
fig, ax = plot_geohash("9q8yyk", color="red", show_label=True)
plt.show()
```
--------------------------------
### NumPy and Pandas Integration Setup
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/types.md
Provides the necessary imports for using pygeohash validation functions in conjunction with NumPy and Pandas data structures.
```python
import numpy as np
import pandas as pd
from pygeohash import (
assert_valid_geohash,
assert_valid_latitude,
assert_valid_longitude,
)
```
--------------------------------
### Add Another Rectangle with Popup and Tooltip
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/_static/images/folium_grid.html
Creates another rectangle with distinct coordinates and fill color. It also includes a popup and a sticky tooltip, similar to previous examples.
```javascript
var rectangle_1d9dfab422722f301058da1aa6295280 = L.rectangle( [[37.96875, -122.958984375], [38.0126953125, -122.9150390625]], {"bubblingMouseEvents": true, "color": "blue", "dashArray": null, "dashOffset": null, "fill": true, "fillColor": "e", "fillOpacity": 0.2, "fillRule": "evenodd", "lineCap": "round", "lineJoin": "round", "noClip": false, "opacity": 1.0, "smoothFactor": 1.0, "stroke": true, "weight": 1} ).addTo(map_5208a72976812c4b284b992c95b46285);
var popup_12e53a7bf50fab5226f187155766ab96 = L.popup({ "maxWidth": "100%", });
var html_191ba135aae954b8bb629f0e65062643 = $("
Geohash: 9qb84
")
[0];
popup_12e53a7bf50fab5226f187155766ab96.setContent(html_191ba135aae954b8bb629f0e65062643);
rectangle_1d9dfab422722f301058da1aa6295280.bindPopup(popup_12e53a7bf50fab5226f187155766ab96) ;
rectangle_1d9dfab422722f301058da1aa6295280.bindTooltip(
` Geohash: 9qb84
`,
{ "sticky": true, }
);
```
--------------------------------
### Add Rectangle with Geohash Tooltip and Popup
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/_static/images/folium_grid.html
This example demonstrates creating a rectangle on the map and attaching a tooltip and a popup, both displaying a specific geohash value.
```javascript
var rectangle_f8bea041e23ed02750d91149e4463833 = L.rectangle( [[38.0126953125, -123.0029296875], [38.056640625, -122.958984375]], {"bubblingMouseEvents": true, "color": "blue", "dashArray": null, "dashOffset": null, "fill": true, "fillColor": "b", "fillOpacity": 0.2, "fillRule": "evenodd", "lineCap": "round", "lineJoin": "round", "noClip": false, "opacity": 1.0, "smoothFactor": 1.0, "stroke": true, "weight": 1} ).addTo(map_5208a72976812c4b284b992c95b46285);
var popup_a47c6c22e319fc22c698443402df2d3e = L.popup({ "maxWidth": "100%", });
var html_333b7b4114c8cbedbbed87f154d4c7f4 = $("Geohash: 9qb83
")\[0\];
popup_a47c6c22e319fc22c698443402df2d3e.setContent(html_333b7b4114c8cbedbbed87f154d4c7f4);
rectangle_f8bea041e23ed02750d91149e4463833.bindPopup(popup_a47c6c22e319fc22c698443402df2d3e) ;
rectangle_f8bea041e23ed02750d91149e4463833.bindTooltip( ` Geohash: 9qb83
`, {"sticky": true, } );
```
--------------------------------
### Create and Bind Popup/Tooltip to Another Folium Rectangle
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/_static/images/folium_grid.html
This example demonstrates creating a second Folium rectangle and binding a different popup and sticky tooltip to it. The popup content is also dynamically generated.
```javascript
var rectangle_0547cef949dfebbaec2adb382c0c8b70 = L.rectangle( [[37.880859375, -123.0908203125], [37.9248046875, -123.046875]], {"bubblingMouseEvents": true, "color": "blue", "dashArray": null, "dashOffset": null, "fill": true, "fillColor": "b", "fillOpacity": 0.2, "fillRule": "evenodd", "lineCap": "round", "lineJoin": "round", "noClip": false, "opacity": 1.0, "smoothFactor": 1.0, "stroke": true, "weight": 1} ).addTo(map_5208a72976812c4b284b992c95b46285);
var popup_a8a83d8c8eabbe1ca0a32caefc2d1793 = L.popup({ "maxWidth": "100%", });
var html_686faf6caa44987e648b84ba102e2b77 = $(\`Geohash: 9q8rx
\`)[0];
popup_a8a83d8c8eabbe1ca0a32caefc2d1793.setContent(html_686faf6caa44987e648b84ba102e2b77);
rectangle_0547cef949dfebbaec2adb382c0c8b70.bindPopup(popup_a8a83d8c8eabbe1ca0a32caefc2d1793) ;
rectangle_0547cef949dfebbaec2adb382c0c8b70.bindTooltip( ` Geohash: 9q8rx
`, { "sticky": true, } );
```
--------------------------------
### Get BoundingBox for a Geohash
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/types.md
Illustrates how to retrieve a BoundingBox named tuple, representing the geographical boundaries of a geohash.
```python
from pygeohash import BoundingBox, get_bounding_box
box: BoundingBox = get_bounding_box("9q9hwg")
print(f"Min Lat: {bbox.min_lat}, Max Lat: {bbox.max_lat}")
print(f"Min Lon: {bbox.min_lon}, Max Lon: {bbox.max_lon}")
```
--------------------------------
### Plot a Single Geohash with PyGeoHash Viz
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/examples.md
Demonstrates plotting a single geohash using the `pygeohash.viz.plot_geohash` function. Examples include plotting a basic geohash and plotting with its center point and label.
```python
import pygeohash as pgh
from pygeohash.viz import plot_geohash
import matplotlib.pyplot as plt
# Plot a single geohash
fig, ax = plot_geohash("9q8yyk", color="red", alpha=0.5)
plt.show()
# Plot with center point and label
fig, ax = plot_geohash("9q8yyk", show_center=True, show_label=True)
plt.show()
```
--------------------------------
### Get Bounding Box for a Geohash
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/examples.md
Demonstrates how to retrieve the bounding box coordinates for a given geohash string. It also shows how to check if a point lies within a bounding box or a geohash, and how to find all geohashes within a custom bounding box at specified precision levels.
```python
import pygeohash as pgh
# Get bounding box for a geohash
geohash = "9q8yy" # San Francisco area
bbox = pgh.get_bounding_box(geohash)
print(f"Bounding box for {geohash}:")
print(f" Southwest corner: ({bbox.min_lat}, {bbox.min_lon})")
print(f" Northeast corner: ({bbox.max_lat}, {bbox.max_lon})")
# Check if a point is within the bounding box
test_points = [
("Golden Gate Bridge", 37.8199, -122.4783),
("Fisherman's Wharf", 37.8080, -122.4177),
("San Jose", 37.3382, -121.8863)
]
for name, lat, lon in test_points:
is_in_box = pgh.is_point_in_box(lat, lon, bbox)
is_in_geohash = pgh.is_point_in_geohash(lat, lon, geohash)
print(f"{name} ({lat}, {lon}):")
print(f" In bounding box: {is_in_box}")
print(f" In geohash: {is_in_geohash}")
# Find all geohashes within a custom bounding box
custom_bbox = pgh.BoundingBox(
min_lat=37.75, min_lon=-122.45,
max_lat=37.78, max_lon=-122.40
)
# Get geohashes at different precision levels
for precision in [5, 6, 7]:
geohashes = pgh.geohashes_in_box(custom_bbox, precision=precision)
print(f"Precision {precision}: found {len(geohashes)} geohashes")
if precision == 5:
print(f" Geohashes: {', '.join(geohashes)}")
# Check if two bounding boxes intersect
bbox1 = pgh.get_bounding_box("9q8yyk")
bbox2 = pgh.get_bounding_box("9q8yym")
bbox3 = pgh.get_bounding_box("dr5r") # New York
print(f"Intersection of 9q8yyk and 9q8yym: {pgh.do_boxes_intersect(bbox1, bbox2)}")
print(f"Intersection of 9q8yyk and dr5r: {pgh.do_boxes_intersect(bbox1, bbox3)}")
```
--------------------------------
### Get Geohash Bounding Box
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/usage.md
Obtain the bounding box coordinates (min/max latitude and longitude) for a given geohash.
```python
import pygeohash as pgh
# Get the bounding box for a geohash
geohash = "u4pruyd"
bbox = pgh.get_bounding_box(geohash)
print(f"Bounding box for {geohash}:")
print(f" Min latitude: {bbox.min_lat}")
print(f" Min longitude: {bbox.min_lon}")
print(f" Max latitude: {bbox.max_lat}")
print(f" Max longitude: {bbox.max_lon}")
```
--------------------------------
### Add Green Rectangle with Popup and Tooltip
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/_static/images/folium_map.html
Draws a green rectangle on the map, similar to the other rectangle examples. This demonstrates adding multiple distinct geographical areas with their own labels.
```javascript
var rectangle_b178e99b245db2b65eeda731e205cf3f = L.rectangle( [[37.7764892578125, -122.431640625], [37.781982421875, -122.420654296875]], {"bubblingMouseEvents": true, "color": "green", "dashArray": null, "dashOffset": null, "fill": true, "fillColor": "green", "fillOpacity": 0.5, "fillRule": "evenodd", "lineCap": "round", "lineJoin": "round", "noClip": false, "opacity": 1.0, "smoothFactor": 1.0, "stroke": true, "weight": 2}
).addTo(map_0d3d235c610c785eca005cba6f8c8f22);
var popup_a36bfba3e88c5313f1abaf4599a6d5df = L.popup({ "maxWidth": "100%", });
var html_36527a68acf1611baca9360226863a53 = $(\`Park
\[0]
);
popup_a36bfba3e88c5313f1abaf4599a6d5df.setContent(html_36527a68acf1611baca9360226863a53);
rectangle_b178e99b245db2b65eeda731e205cf3f.bindPopup(popup_a36bfba3e88c5313f1abaf4599a6d5df) ;
rectangle_b178e99b245db2b65eeda731e205cf3f.bindTooltip(
` Geohash: 9q8yyj
`,
{ "sticky": true, }
);
```
--------------------------------
### Visualize Geohash Bounding Boxes with Matplotlib
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/examples.md
This example shows how to visualize geohash bounding boxes using Matplotlib. It plots a base geohash's bounding box and then overlays the bounding boxes of geohashes within that area at a higher precision.
```python
import pygeohash as pgh
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Define a base geohash and get its bounding box
base_geohash = "9q8yy" # San Francisco area
base_bbox = pgh.get_bounding_box(base_geohash)
# Find geohashes within this area at a higher precision
geohashes = pgh.geohashes_in_box(base_bbox, precision=6)
# Create a figure and axis
fig, ax = plt.subplots(figsize=(10, 8))
# Plot the base bounding box
base_width = base_bbox.max_lon - base_bbox.min_lon
base_height = base_bbox.max_lat - base_bbox.min_lat
base_rect = patches.Rectangle(
(base_bbox.min_lon, base_bbox.min_lat),
base_width, base_height,
linewidth=2, edgecolor='blue', facecolor='none',
label=f'Base Geohash: {base_geohash}'
)
ax.add_patch(base_rect)
# Plot each geohash's bounding box
for gh in geohashes[:10]: # Limit to first 10 for clarity
gh_bbox = pgh.get_bounding_box(gh)
width = gh_bbox.max_lon - gh_bbox.min_lon
height = gh_bbox.max_lat - gh_bbox.min_lat
rect = patches.Rectangle(
(gh_bbox.min_lon, gh_bbox.min_lat),
width, height,
linewidth=1, edgecolor='red', facecolor='red', alpha=0.2
)
ax.add_patch(rect)
# Add geohash label at center of box
center_x = gh_bbox.min_lon + width/2
center_y = gh_bbox.min_lat + height/2
ax.text(center_x, center_y, gh, ha='center', va='center', fontsize=8)
# Set plot limits and labels
ax.set_xlim(base_bbox.min_lon - 0.05, base_bbox.max_lon + 0.05)
ax.set_ylim(base_bbox.min_lat - 0.05, base_bbox.max_lat + 0.05)
ax.set_xlabel('Longitude')
ax.set_ylabel('Latitude')
ax.set_title(f'Geohashes within {base_geohash}')
ax.legend()
plt.tight_layout()
plt.show()
```
--------------------------------
### Add Blue Rectangle with Popup and Tooltip
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/_static/images/folium_map.html
Adds a blue rectangle to the map, similar to the red rectangle example. This allows for distinguishing different areas with distinct colors and associated popups/tooltips.
```javascript
var rectangle_afdbe48a6e5d48b831f8ba032c83e5e0 = L.rectangle( [[37.7764892578125, -122.420654296875], [37.781982421875, -122.40966796875]], {"bubblingMouseEvents": true, "color": "blue", "dashArray": null, "dashOffset": null, "fill": true, "fillColor": "blue", "fillOpacity": 0.5, "fillRule": "evenodd", "lineCap": "round", "lineJoin": "round", "noClip": false, "opacity": 1.0, "smoothFactor": 1.0, "stroke": true, "weight": 2}
).addTo(map_0d3d235c610c785eca005cba6f8c8f22);
var popup_2ba39a2e6b7c5e90fc6b161fd3734b70 = L.popup({ "maxWidth": "100%", });
var html_8cab1f77ca605f49c04c7840ea179890 = $(\`Work
\[0]
);
popup_2ba39a2e6b7c5e90fc6b161fd3734b70.setContent(html_8cab1f77ca605f49c04c7840ea179890);
rectangle_afdbe48a6e5d48b831f8ba032c83e5e0.bindPopup(popup_2ba39a2e6b7c5e90fc6b161fd3734b70) ;
rectangle_afdbe48a6e5d48b831f8ba032c83e5e0.bindTooltip(
` Geohash: 9q8yym
`,
{ "sticky": true, }
);
```
--------------------------------
### GeohashArray for NumPy Integration
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/types.md
Demonstrates the use of GeohashArray, a NumPy array specifically typed for geohash strings. Example shows creating a GeohashArray from encoded latitude and longitude coordinates.
```python
import numpy as np
from pygeohash import GeohashArray, encode
# Create a grid of coordinates
lats = np.array([37.7749, 37.7750, 37.7751])
lons = np.array([-122.4194, -122.4195, -122.4196])
# Convert to geohashes
geohashes: GeohashArray = np.array([
encode(lat, lon) for lat, lon in zip(lats, lons)
])
```
--------------------------------
### Encode and Decode Coordinates
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/examples.md
Convert latitude and longitude coordinates to geohashes with varying precision, and decode geohashes back to coordinates. Also shows how to get exact decoding with error margins.
```python
import pygeohash as pgh
# Define some locations
locations = {
"San Francisco": (37.7749, -122.4194),
"New York": (40.7128, -74.0060),
"Tokyo": (35.6762, 139.6503),
"Sydney": (-33.8688, 151.2093),
"Rio de Janeiro": (-22.9068, -43.1729)
}
# Encode each location with different precision levels
for name, (lat, lng) in locations.items():
print(f"\n{name}:")
for precision in [4, 6, 8, 10]:
geohash = pgh.encode(lat, lng, precision=precision)
print(f" Precision {precision}: {geohash}")
# Decode a geohash back to coordinates
geohash = "9q8yyk8yuv" # San Francisco with precision 10
location = pgh.decode(geohash)
print(f"\nDecoded {geohash}: ({location.latitude}, {location.longitude})")
# Get exact decoding with error margins
exact = pgh.decode_exactly(geohash)
print(f"Error margins: ±{exact.latitude_error}° latitude, ±{exact.longitude_error}° longitude")
```
--------------------------------
### Run Standard Test Suite
Source: https://github.com/wdm0006/pygeohash/blob/master/README.md
Execute the standard test suite for PyGeoHash to verify its functionality and accuracy.
```bash
make test
```
--------------------------------
### Run Tests with Coverage
Source: https://github.com/wdm0006/pygeohash/blob/master/README.md
Run the PyGeoHash test suite and generate a coverage report.
```bash
make test-cov
```
--------------------------------
### Initialize Leaflet Map and Add Tile Layer
Source: https://github.com/wdm0006/pygeohash/blob/master/examples/images/tech_companies.html
Sets up the basic map container, initializes the Leaflet map with specific CRS and view settings, and adds an OpenStreetMap tile layer. This is the foundational step for any Leaflet map.
```javascript
var map_e4f6cfdfaf1d16a6017a6c6145477959 = L.map( "map_e4f6cfdfaf1d16a6017a6c6145477959", { center: [37.01568603515625, -121.0968017578125], crs: L.CRS.EPSG3857, ...{ "zoom": 10, "zoomControl": true, "preferCanvas": false, } } ); var tile_layer_8027b855c2746150527386b793dafdb0 = L.tileLayer( "https://tile.openstreetmap.org/{z}/{x}/{y}.png", { "minZoom": 0, "maxZoom": 19, "maxNativeZoom": 19, "noWrap": false, "attribution": "\u0026copy; \u003ca href=\"https://www.openstreetmap.org/copyright\"\u003eOpenStreetMap\u003c/a\u003e contributors", "subdomains": "abc", "detectRetina": false, "tms": false, "opacity": 1, } ); tile_layer_8027b855c2746150527386b793dafdb0.addTo(map_e4f6cfdfaf1d16a6017a6c6145477959);
```
--------------------------------
### Get Adjacent Geohash
Source: https://github.com/wdm0006/pygeohash/blob/master/README.md
Find the geohash of an adjacent cell in a specified direction (e.g., 'right', 'left', 'top', 'bottom').
```python
import pygeohash as pgh
# Get adjacent geohash
adjacent = pgh.get_adjacent(geohash='kd3ybyu', direction='right')
print(adjacent) # 'kd3ybyv'
```
--------------------------------
### Get Geohash Bounding Box
Source: https://context7.com/wdm0006/pygeohash/llms.txt
Retrieves the geographic extent of a geohash cell as a BoundingBox named tuple. Cell size decreases with higher precision.
```python
import pygeohash as pgh
box = pgh.get_bounding_box('9q8yyk')
print(bbox)
# BoundingBox(min_lat=37.7471..., min_lon=-122.4194...,
# max_lat=37.7526..., max_lon=-122.4139...)
# Access individual sides
print(f"Width : {bbox.max_lon - bbox.min_lon:.6f}°")
print(f"Height: {bbox.max_lat - bbox.min_lat:.6f}°")
# Compare cell sizes at different precisions
for prec in [3, 5, 7, 9]:
gh = pgh.encode(37.7749, -122.4194, precision=prec)
bb = pgh.get_bounding_box(gh)
lat_km = (bb.max_lat - bb.min_lat) * 111 # ~111 km per degree latitude
print(f"Precision {prec}: ~{lat_km:.2f} km tall")
```
--------------------------------
### Define Bounding Box and Find Geohashes
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/usage.md
Demonstrates how to define a bounding box and find all geohashes that intersect with it at specified precisions.
```python
import pygeohash as pgh
# Define a bounding box
bbox = pgh.BoundingBox(min_lat=40.0, min_lon=-74.0, max_lat=40.1, max_lon=-73.9)
# Find geohashes that intersect with the box
geohashes = pgh.geohashes_in_box(bbox, precision=5)
print(f"Found {len(geohashes)} geohashes at precision 5")
print(geohashes)
# Try with a different precision
geohashes_p6 = pgh.geohashes_in_box(bbox, precision=6)
print(f"Found {len(geohashes_p6)} geohashes at precision 6")
```
--------------------------------
### Log to a file with PyGeoHash
Source: https://context7.com/wdm0006/pygeohash/llms.txt
Configure PyGeoHash to log messages to a file. Ensure to remove existing handlers before adding a new file handler.
```python
import logging
pgh.remove_all_handlers()
pgh.add_file_handler('pygeohash.log', level=logging.INFO)
pgh.set_log_level(logging.INFO)
```
```python
# Reset to silent
pgh.remove_all_handlers()
```
--------------------------------
### Create and Use LatLong Type
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/types.md
Demonstrates how to create and access data from the LatLong named tuple, representing a latitude/longitude coordinate pair.
```python
from pygeohash import LatLong
location: LatLong = LatLong(latitude=37.7749, longitude=-122.4194)
print(f"Latitude: {location.latitude}, Longitude: {location.longitude}")
```
--------------------------------
### Get Adjacent Geohashes
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/examples.md
Retrieve the geohash of an adjacent cell in any of the four cardinal directions (top, right, bottom, left). This is useful for creating grids or searching neighboring areas.
```python
import pygeohash as pgh
# Get adjacent geohashes in all four directions
geohash = "9q8yyk" # San Francisco
adjacent_top = pgh.get_adjacent(geohash, 'top')
adjacent_right = pgh.get_adjacent(geohash, 'right')
adjacent_bottom = pgh.get_adjacent(geohash, 'bottom')
adjacent_left = pgh.get_adjacent(geohash, 'left')
print(f"Original: {geohash}")
print(f"Top: {adjacent_top}")
print(f"Right: {adjacent_right}")
print(f"Bottom: {adjacent_bottom}")
print(f"Left: {adjacent_left}")
# Create a simple 3x3 grid of geohashes
def create_simple_grid(center_geohash):
grid = [
[None, None, None],
[None, center_geohash, None],
[None, None, None]
]
# Fill in the grid
# Top row
grid[0][1] = pgh.get_adjacent(center_geohash, 'top')
grid[0][0] = pgh.get_adjacent(grid[0][1], 'left')
grid[0][2] = pgh.get_adjacent(grid[0][1], 'right')
# Middle row
grid[1][0] = pgh.get_adjacent(center_geohash, 'left')
grid[1][2] = pgh.get_adjacent(center_geohash, 'right')
# Bottom row
grid[2][1] = pgh.get_adjacent(center_geohash, 'bottom')
grid[2][0] = pgh.get_adjacent(grid[2][1], 'left')
grid[2][2] = pgh.get_adjacent(grid[2][1], 'right')
return grid
# Create and print the grid
grid = create_simple_grid(geohash)
print("\nGeohash Grid:")
for row in grid:
print(" ".join(row))
```
--------------------------------
### Configure PyGeoHash Library Logging
Source: https://context7.com/wdm0006/pygeohash/llms.txt
Enable and configure logging for the PyGeoHash library. By default, it uses a silent `NullHandler`. Handlers can be added for stream (stdout) or file output at specified log levels.
```python
import logging
import pygeohash as pgh
# Enable DEBUG output to stdout
pgh.add_stream_handler(level=logging.DEBUG)
pgh.set_log_level(logging.DEBUG)
# Now every encode/decode/distance call logs its steps
gh = pgh.encode(37.7749, -122.4194, precision=6)
# Output:
# 2024-01-01 12:00:00 - pygeohash.geohash - DEBUG - Encoding coordinates: lat=37.774900, lon=-122.419400 with precision 6
# 2024-01-01 12:00:00 - pygeohash.geohash - DEBUG - Encoded to geohash: 9q8yy9
```
--------------------------------
### Geospatial Querying with Bounding Boxes
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/usage.md
Illustrates how to use bounding boxes for efficient geospatial querying by filtering a list of locations. It shows two methods: direct point-in-box checking and geohash-based filtering.
```python
import pygeohash as pgh
# Sample database of locations with their coordinates
locations = [
{"id": 1, "name": "Central Park", "lat": 40.785091, "lon": -73.968285},
{"id": 2, "name": "Empire State Building", "lat": 40.748817, "lon": -73.985428},
{"id": 3, "name": "Statue of Liberty", "lat": 40.689247, "lon": -74.044502},
{"id": 4, "name": "Times Square", "lat": 40.758896, "lon": -73.985130},
{"id": 5, "name": "Brooklyn Bridge", "lat": 40.706086, "lon": -73.996864},
]
# Define a search area (bounding box)
search_area = pgh.BoundingBox(
min_lat=40.7, min_lon=-74.0,
max_lat=40.8, max_lon=-73.9
)
# Find locations within the search area
results = []
for location in locations:
if pgh.is_point_in_box(location["lat"], location["lon"], search_area):
results.append(location)
print(f"Found {len(results)} locations within the search area:")
for location in results:
print(f" - {location['name']}")
# Alternative approach using geohashes
# First, find all geohashes in the search area at precision 5
geohashes_in_area = pgh.geohashes_in_box(search_area, precision=5)
# Pre-compute geohashes for all locations
for location in locations:
location["geohash"] = pgh.encode(location["lat"], location["lon"], precision=5)
# Find locations with matching geohashes
geohash_results = [
location for location in locations
if location["geohash"] in geohashes_in_area
]
print(f"Found {len(geohash_results)} locations using geohash matching:")
for location in geohash_results:
print(f" - {location['name']} (geohash: {location['geohash']})")
```
--------------------------------
### Add Third Rectangle with Customization
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/_static/images/folium_grid.html
Demonstrates adding another rectangle with specific coordinates and a different fill color. Includes a popup and a sticky tooltip.
```javascript
var rectangle_ff7592d4968f420230097309d49003f9 = L.rectangle( [[38.056640625, -123.0908203125], [38.1005859375, -123.046875]], {"bubblingMouseEvents": true, "color": "blue", "dashArray": null, "dashOffset": null, "fill": true, "fillColor": "b", "fillOpacity": 0.2, "fillRule": "evenodd", "lineCap": "round", "lineJoin": "round", "noClip": false, "opacity": 1.0, "smoothFactor": 1.0, "stroke": true, "weight": 1} ).addTo(map_5208a72976812c4b284b992c95b46285);
var popup_a17238770ac0bcaf3139b6d1ef7815b7 = L.popup({ "maxWidth": "100%", });
var html_650e15b8e928d5105e1f1788a081881b = $("Geohash: 9qb2x
")
[0];
popup_a17238770ac0bcaf3139b6d1ef7815b7.setContent(html_650e15b8e928d5105e1f1788a081881b);
rectangle_ff7592d4968f420230097309d49003f9.bindPopup(popup_a17238770ac0bcaf3139b6d1ef7815b7) ;
rectangle_ff7592d4968f420230097309d49003f9.bindTooltip(
` Geohash: 9qb2x
`,
{ "sticky": true, }
);
```
--------------------------------
### Get Geohashes within a Bounding Box
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/api.md
Use `geohashes_in_box` to find all geohashes within a specified bounding box for a given precision. The number of returned geohashes varies with the box size and precision.
```python
>>> box = BoundingBox(57.64, 10.40, 57.65, 10.41)
>>> geohashes_in_box(box, precision=5)
['u4pru', 'u4prv']
```
--------------------------------
### Get Geohash Bounding Box
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/api.md
Determines the geographical bounding box for a given geohash. The precision of the bounding box coordinates is dependent on the length of the geohash; longer geohashes yield more precise boxes.
```python
>>> get_bounding_box("u4pruyd")
BoundingBox(min_lat=57.649, min_lon=10.407, max_lat=57.649, max_lon=10.407)
```
--------------------------------
### Type Hinting with Validated Types
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/types.md
Demonstrates how to use type hints with validated types (Geohash, Latitude, Longitude) to indicate that function arguments are expected to be pre-validated.
```python
from pygeohash import Geohash, Latitude, Longitude
def calculate_distance(
geohash1: Geohash,
lat: Latitude,
lon: Longitude,
) -> float:
# Function can assume inputs are already validated
...
```
--------------------------------
### Create and Bind Popup/Tooltip to Rectangle
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/_static/images/folium_grid.html
Illustrates the creation of a rectangle with specific geographical bounds and visual styles, followed by binding a popup and a tooltip containing geohash data.
```javascript
var rectangle_a115c98127b519f0ea228772ae6f00f6 = L.rectangle( [[38.056640625, -123.0029296875], [38.1005859375, -122.958984375]], {"bubblingMouseEvents": true, "color": "blue", "dashArray": null, "dashOffset": null, "fill": true, "fillColor": "u", "fillOpacity": 0.2, "fillRule": "evenodd", "lineCap": "round", "lineJoin": "round", "noClip": false, "opacity": 1.0, "smoothFactor": 1.0, "stroke": true, "weight": 1} ).addTo(map_5208a72976812c4b284b992c95b46285);
var popup_c7cf57fb4cbd7547cc9a19fd0e6ddf55 = L.popup({ "maxWidth": "100%", });
var html_9ab756a2fe78ef593649b06fd4a6786d = $("Geohash: 9qb89
")\[0\];
popup_c7cf57fb4cbd7547cc9a19fd0e6ddf55.setContent(html_9ab756a2fe78ef593649b06fd4a6786d);
rectangle_a115c98127b519f0ea228772ae6f00f6.bindPopup(popup_c7cf57fb4cbd7547cc9a19fd0e6ddf55) ;
rectangle_a115c98127b519f0ea228772ae6f00f6.bindTooltip( ` Geohash: 9qb89
`, { "sticky": true, } );
```
--------------------------------
### GeohashCollection Type Alias
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/types.md
Defines a type alias for a generic iterable of geohash strings, useful for functions that accept various collection types of geohashes. Example shows calculating the mean geohash from a collection.
```python
from pygeohash import GeohashCollection, mean
def calculate_center(geohashes: GeohashCollection) -> str:
return mean(geohashes)
```
--------------------------------
### Get Adjacent Geohash
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/api.md
Calculates the geohash in a specified cardinal direction (top, bottom, left, right) relative to the input geohash. A ValueError may occur if the geohash is too short (e.g., near the poles).
```python
>>> get_adjacent("u4pruyd", "top")
'u4pruyf'
```
--------------------------------
### Create a Geohash Grid with Folium
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/examples.md
Generate an interactive map displaying a geohash grid using `folium_map` and `add_geohash_grid`. The grid's precision and opacity can be configured.
```python
import pygeohash as pgh
from pygeohash.viz import folium_map
# Create a map
m = folium_map(center_geohash="9q8y", zoom_start=12)
# Add a geohash grid at precision 5
m.add_geohash_grid(precision=5, fill_opacity=0.2)
# Save the map to an HTML file
m.save("folium_grid.html")
```
--------------------------------
### Get Adjacent Geohash
Source: https://context7.com/wdm0006/pygeohash/llms.txt
Finds the geohash cell immediately adjacent in a specified cardinal direction ('top', 'bottom', 'left', 'right'). Handles border crossing and raises ValueError for zero-length input near poles.
```python
import pygeohash as pgh
geohash = '9q8yyk'
# Single step in each cardinal direction
top = pgh.get_adjacent(geohash, 'top')
bottom = pgh.get_adjacent(geohash, 'bottom')
left = pgh.get_adjacent(geohash, 'left')
right = pgh.get_adjacent(geohash, 'right')
print(f"Original : {geohash}")
print(f"Top : {top}") # 9q8yys
print(f"Bottom : {bottom}") # 9q8yyh
print(f"Left : {left}") # 9q8yy7
print(f"Right : {right}") # 9q8yym
# Build a 3×3 ring of neighbors
center = '9q8yyk'
grid = {}
for direction in ['top', 'bottom', 'left', 'right']:
grid[direction] = pgh.get_adjacent(center, direction)
# Chain adjacency: walk north 3 cells
cell = center
for _ in range(3):
cell = pgh.get_adjacent(cell, 'top')
print(f"3 cells north: {cell}") # 9q8yyu
```
--------------------------------
### set_log_level, add_stream_handler, add_file_handler
Source: https://context7.com/wdm0006/pygeohash/llms.txt
Configures the logging level and handlers for the PyGeoHash library.
```APIDOC
## set_log_level / add_stream_handler / add_file_handler
### Description
Configure library logging. PyGeoHash uses a `NullHandler` by default (silent). Enable logging by attaching a handler. All internal operations emit `DEBUG`-level messages.
### Parameters
- **level** (`int`): The logging level (e.g., `logging.DEBUG`, `logging.INFO`).
### Example
```python
import logging
import pygeohash as pgh
pgh.add_stream_handler(level=logging.DEBUG)
pgh.set_log_level(logging.DEBUG)
gh = pgh.encode(37.7749, -122.4194, precision=6)
```
```
--------------------------------
### Initialize Folium Map and Tile Layer
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/_static/images/folium_grid.html
Initializes a Folium map centered at a specific location and adds an OpenStreetMap tile layer. This is the foundational step for displaying map data.
```javascript
var map_5208a72976812c4b284b992c95b46285 = L.map( "map_5208a72976812c4b284b992c95b46285", { center: [38.0, -123.0], crs: L.CRS.EPSG3857, ...{ "zoom": 12, "zoomControl": true, "preferCanvas": false, } } ); var tile_layer_336e5e5f96e4705835845741fda3a9ab = L.tileLayer( "https://tile.openstreetmap.org/{z}/{x}/{y}.png", { "minZoom": 0, "maxZoom": 19, "maxNativeZoom": 19, "noWrap": false, "attribution": "\u0026copy; \u003ca href=\"https://www.openstreetmap.org/copyright\"\u003eOpenStreetMap\u003c/a\u003e contributors", "subdomains": "abc", "detectRetina": false, "tms": false, "opacity": 1, } ); tile_layer_336e5e5f96e4705835845741fda3a9ab.addTo(map_5208a72976812c4b284b992c95b46285);
```
--------------------------------
### Initialize Folium Map
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/_static/images/folium_map.html
Initializes a Folium map with specified center coordinates and CRS. Use this to set up the base map for further customization.
```javascript
var map_0d3d235c610c785eca005cba6f8c8f22 = L.map( "map_0d3d235c610c785eca005cba6f8c8f22", { center: [37.77, -122.4], crs: L.CRS.EPSG3857, ...{ "zoom": 15, "zoomControl": true, "preferCanvas": false, } } );
```
--------------------------------
### Create Interactive Maps with Folium
Source: https://github.com/wdm0006/pygeohash/blob/master/docs/source/usage.md
Integrate PyGeoHash with Folium to create interactive maps. Add individual geohashes, grids, and save to HTML.
```python
import pygeohash as pgh
from pygeohash.viz import folium_map
# Create a map centered on a location
m = folium_map(center=(37.7749, -122.4194), zoom_start=12)
# Add geohashes to the map
geohash = pgh.encode(37.7749, -122.4194, precision=6)
m.add_geohash(geohash, color="red", popup="San Francisco")
# Add a grid of geohashes at precision 5
m.add_geohash_grid(precision=5, fill_opacity=0.2)
# Save the map to an HTML file
m.save("map.html")
```