### Install TkinterMapView Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Install the TkinterMapView package using pip. Use the --upgrade flag to update to the latest version. ```bash pip3 install tkintermapview ``` ```bash pip3 install tkintermapview --upgrade ``` -------------------------------- ### Set and Get Zoom Level Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Set the map's zoom level to a specific value within the valid range. The current zoom level can also be read. ```python map_widget.set_zoom(17) # street level map_widget.set_zoom(5) # country level map_widget.set_zoom(2) # world overview # Read current zoom print(map_widget.zoom) # float (may be fractional during animation) ``` -------------------------------- ### Get Current Map Center Position Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Retrieve the current center coordinates of the map view as a tuple of latitude and longitude. ```python lat, lon = map_widget.get_position() print(f"Map center: {lat:.6f}, {lon:.6f}") # Output: Map center: 48.856600, 2.352200 ``` -------------------------------- ### Create Tkinter Window and Map Widget Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Set up a basic Tkinter window and initialize the TkinterMapView widget with specified dimensions and corner radius. The widget is then placed in the center of the window. ```python # create tkinter window root_tk = tkinter.Tk() root_tk.geometry(f"{800}x{600}") root_tk.title("map_view_example.py") # create map widget map_widget = tkintermapview.TkinterMapView(root_tk, width=800, height=600, corner_radius=0) map_widget.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) ``` -------------------------------- ### Custom Tile Sources Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Switches the map's tile provider to any XYZ tile server URL. `set_overlay_tile_server` composites a second layer on top of the base tiles. Use for displaying different map styles or overlays. ```python # Switch to Google Maps satellite map_widget.set_tile_server( "https://mt0.google.com/vt/lyrs=s&hl=en&x={x}&y={y}&z={z}&s=Ga", max_zoom=22, ) # Painting-style tiles map_widget.set_tile_server("http://c.tile.stamen.com/watercolor/{z}/{x}/{y}.png") # Black-and-white toner map_widget.set_tile_server("http://a.tile.stamen.com/toner/{z}/{x}/{y}.png") # Back to OpenStreetMap default map_widget.set_tile_server("https://a.tile.openstreetmap.org/{z}/{x}/{y}.png") # Add OpenSeaMap nautical overlay on top of current base layer map_widget.set_overlay_tile_server( "http://tiles.openseamap.org/seamark//{z}/{x}/{y}.png" ) # Add OpenRailwayMap overlay map_widget.set_overlay_tile_server( "http://a.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png" ) ``` -------------------------------- ### Import Tkinter and TkinterMapView Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Import the necessary libraries for creating a Tkinter application and the TkinterMapView widget. ```python import tkinter import tkintermapview ``` -------------------------------- ### set_tile_server / set_overlay_tile_server Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Switches the map's tile provider to any XYZ tile server URL. set_overlay_tile_server composites a second layer on top of the base tiles. ```APIDOC ## set_tile_server / set_overlay_tile_server — Custom Tile Sources Switches the map's tile provider to any XYZ tile server URL containing `{x}`, `{y}`, `{z}` placeholders. Clears the image cache and redraws the map. `set_overlay_tile_server` composites a second layer (e.g., maritime or rail overlays) on top of the base tiles. ```python # Switch to Google Maps satellite map_widget.set_tile_server( "https://mt0.google.com/vt/lyrs=s&hl=en&x={x}&y={y}&z={z}&s=Ga", max_zoom=22, ) # Painting-style tiles map_widget.set_tile_server("http://c.tile.stamen.com/watercolor/{z}/{x}/{y}.png") # Black-and-white toner map_widget.set_tile_server("http://a.tile.stamen.com/toner/{z}/{x}/{y}.png") # Back to OpenStreetMap default map_widget.set_tile_server("https://a.tile.openstreetmap.org/{z}/{x}/{y}.png") # Add OpenSeaMap nautical overlay on top of current base layer map_widget.set_overlay_tile_server( "http://tiles.openseamap.org/seamark//{z}/{x}/{y}.png" ) # Add OpenRailwayMap overlay map_widget.set_overlay_tile_server( "http://a.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png" ) ``` ``` -------------------------------- ### Initialize TkinterMapView Widget Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Create a Tkinter map widget with optional rounded corners and background color. Supports offline use with a SQLite database fallback. ```python import tkinter import tkintermapview root = tkinter.Tk() root.geometry("900x700") root.title("My Map App") # Basic widget — full online mode map_widget = tkintermapview.TkinterMapView( root, width=900, height=650, corner_radius=15, # rounded corners (max 30) bg_color="#2b2b2b", # explicit background for rounded corner blending max_zoom=19, ) map_widget.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) # Widget with offline SQLite database fallback map_offline = tkintermapview.TkinterMapView( root, width=900, height=650, database_path="./tiles.db", use_database_only=False, # use DB first, fall back to network ) root.mainloop() ``` -------------------------------- ### TkinterMapView Constructor Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Initializes the TkinterMapView widget. It can be configured with dimensions, corner radius, background color, and tile server zoom limits. Offline capabilities can be enabled using a database path. ```APIDOC ## TkinterMapView — Widget Constructor Creates a Tkinter map widget as a `tkinter.Frame` subclass. The `database_path` argument enables an SQLite tile cache for offline use; `use_database_only=True` disables all network requests. Zoom defaults to 0–19 (tile-server dependent). ```python import tkinter import tkintermapview root = tkinter.Tk() root.geometry("900x700") root.title("My Map App") # Basic widget — full online mode map_widget = tkintermapview.TkinterMapView( root, width=900, height=650, corner_radius=15, # rounded corners (max 30) bg_color="#2b2b2b", # explicit background for rounded corner blending max_zoom=19, ) map_widget.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) # Widget with offline SQLite database fallback map_offline = tkintermapview.TkinterMapView( root, width=900, height=650, database_path="./tiles.db", use_database_only=False, # use DB first, fall back to network ) root.mainloop() ``` ``` -------------------------------- ### Set Tile Server Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Configures the tile server URL for the map. Supports various providers like OpenStreetMap, Google Maps, and Stamen. The max_zoom argument can limit the zoom range. ```python # example tile sever: self.map_widget.set_tile_server("https://a.tile.openstreetmap.org/{z}/{x}/{y}.png") # OpenStreetMap (default) self.map_widget.set_tile_server("https://mt0.google.com/vt/lyrs=m&hl=en&x={x}&y={y}&z={z}&s=Ga", max_zoom=22) # google normal self.map_widget.set_tile_server("https://mt0.google.com/vt/lyrs=s&hl=en&x={x}&y={y}&z={z}&s=Ga", max_zoom=22) # google satellite self.map_widget.set_tile_server("http://c.tile.stamen.com/watercolor/{z}/{x}/{y}.png") # painting style self.map_widget.set_tile_server("http://a.tile.stamen.com/toner/{z}/{x}/{y}.png") # black and white self.map_widget.set_tile_server("https://tiles.wmflabs.org/hikebike/{z}/{x}/{y}.png") # detailed hiking self.map_widget.set_tile_server("https://tiles.wmflabs.org/osm-no-labels/{z}/{x}/{y}.png") # no labels self.map_widget.set_tile_server("https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.pixelkarte-farbe/default/current/3857/{z}/{x}/{y}.jpeg") # swisstopo map # example overlay tile server self.map_widget.set_overlay_tile_server("http://tiles.openseamap.org/seamark//{z}/{x}/{y}.png") # sea-map overlay self.map_widget.set_overlay_tile_server("http://a.tiles.openrailwaymap.org/standard/{z}/{x}/{y}.png") # railway infrastructure ``` -------------------------------- ### Create Polygon with Positions Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Define a polygon on the map using a list of coordinate tuples. Customize its appearance with fill color, outline color, and border width. A command can be set to execute when the polygon is clicked. ```python def polygon_click(polygon): print(f"polygon clicked - text: {polygon.name}") polygon_1 = map_widget.set_polygon([(46.0732306, 6.0095215), ... (46.3772542, 6.4160156)], # fill_color=None, # outline_color="red", # border_width=12, command=polygon_click, name="switzerland_polygon") # methods polygon_1.remove_position(46.3772542, 6.4160156) polygon_1.add_position(0, 0, index=5) polygon_1.delete() ``` -------------------------------- ### Map Click Commands Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Configure callbacks for left-click and right-click events on the map widget. Left-clicks can trigger actions with coordinates, while right-clicks can add custom menu entries. ```APIDOC ## add_left_click_map_command ### Description Registers a callback function to be executed when the user performs a left-click on the map. ### Method `map_widget.add_left_click_map_command(command)` ### Parameters - **command** (function) - The callback function to execute. It receives coordinates (lat, lon) as an argument. ## add_right_click_menu_command ### Description Adds a new entry to the right-click context menu. This entry can either pass coordinates or not, depending on the `pass_coords` argument. ### Method `map_widget.add_right_click_menu_command(label, command, pass_coords) ### Parameters - **label** (string) - The text to display for the menu entry. - **command** (function) - The callback function to execute when the menu entry is selected. - **pass_coords** (boolean) - If True, the callback function will receive the click coordinates (lat, lon) as arguments. ``` -------------------------------- ### Add Left Click Map Command Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Registers a callback function to be executed when the map is left-clicked. The callback receives coordinates and can be used to place markers or perform other actions. ```python def on_left_click(coords): print(f"Map clicked at: {coords[0]:.5f}, {coords[1]:.5f}") map_widget.set_marker(coords[0], coords[1], text=f"{coords[0]:.3f},{coords[1]:.3f}") map_widget.add_left_click_map_command(on_left_click) ``` -------------------------------- ### Add Left-Click Map Command Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Assigns a callback function to be executed when the map is left-clicked. The function receives the decimal coordinates of the click as a tuple. ```python def left_click_event(coordinates_tuple): print("Left click event with coordinates:", coordinates_tuple) map_widget.add_left_click_map_command(left_click_event) ``` -------------------------------- ### OfflineLoader Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Enables pre-downloading of map tiles within a specified geographic bounding box and zoom range, storing them in a local SQLite database for offline use. ```APIDOC ## OfflineLoader ### Description Manages the downloading and storage of map tiles to a local SQLite database for offline map viewing. It uses a multi-threaded approach for efficient downloading. ### Initialization `loader = OfflineLoader(path, tile_server, max_zoom)` ### Parameters - **path** (string) - The file path for the SQLite database. - **tile_server** (string) - The URL template for the tile server (e.g., "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"). - **max_zoom** (int) - The maximum zoom level to be cached. ### save_offline_tiles ### Description Downloads and saves map tiles within a specified bounding box and zoom range to the configured SQLite database. ### Method `loader.save_offline_tiles(position_a, position_b, zoom_a, zoom_b)` ### Parameters - **position_a** (tuple) - The coordinates (latitude, longitude) of the first corner of the bounding box (e.g., NW corner). - **position_b** (tuple) - The coordinates (latitude, longitude) of the opposite corner of the bounding box (e.g., SE corner). - **zoom_a** (int) - The minimum zoom level to cache. - **zoom_b** (int) - The maximum zoom level to cache. ### print_loaded_sections ### Description Prints a list of all geographic regions and zoom levels that have been cached in the database. ### Method `loader.print_loaded_sections()` ``` -------------------------------- ### Mouse Event Callbacks Source: https://context7.com/tomschimansky/tkintermapview/llms.txt add_left_click_map_command registers a callback for left-click events on the map background. add_right_click_menu_command appends a custom entry to the built-in right-click context menu. ```APIDOC ## Mouse Event Callbacks — Left Click and Right-Click Menu `add_left_click_map_command` registers a callback for left-click events on the map background (not on markers). `add_right_click_menu_command` appends a custom entry to the built-in right-click context menu; pass `pass_coords=True` to receive the clicked decimal coordinates. ```python ``` -------------------------------- ### Mouse Event Callbacks Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Registers callbacks for map events. `add_left_click_map_command` handles left-clicks on the map background. `add_right_click_menu_command` adds entries to the right-click context menu, optionally receiving coordinates. ```python ``` -------------------------------- ### Utility Functions Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Provides functions for geocoding (address to coordinates and vice versa) and coordinate conversion, utilizing the geocoder library with OSM Nominatim. ```APIDOC ## convert_coordinates_to_address ### Description Performs reverse geocoding to convert latitude and longitude coordinates into a full address object. ### Method `tkintermapview.convert_coordinates_to_address(latitude, longitude)` ### Parameters - **latitude** (float) - The latitude of the location. - **longitude** (float) - The longitude of the location. ### Returns An address object with attributes like `street`, `city`, `country`, and `latlng`, or None if not found. ## convert_coordinates_to_city ### Description Converts latitude and longitude coordinates to the name of the city. ### Method `tkintermapview.convert_coordinates_to_city(latitude, longitude)` ### Parameters - **latitude** (float) - The latitude of the location. - **longitude** (float) - The longitude of the location. ### Returns The name of the city as a string, or None if not found. ## convert_coordinates_to_country ### Description Converts latitude and longitude coordinates to the name of the country. ### Method `tkintermapview.convert_coordinates_to_country(latitude, longitude)` ### Parameters - **latitude** (float) - The latitude of the location. - **longitude** (float) - The longitude of the location. ### Returns The name of the country as a string, or None if not found. ## convert_address_to_coordinates ### Description Performs forward geocoding to convert an address string into latitude and longitude coordinates. ### Method `tkintermapview.convert_address_to_coordinates(address_string)` ### Parameters - **address_string** (string) - The address to geocode. ### Returns A tuple of (latitude, longitude) if the address is found, otherwise None. ## decimal_to_osm ### Description Converts decimal latitude and longitude to OSM tile coordinates (x, y) for a given zoom level. ### Method `tkintermapview.decimal_to_osm(latitude, longitude, zoom)` ### Parameters - **latitude** (float) - The decimal latitude. - **longitude** (float) - The decimal longitude. - **zoom** (int) - The zoom level. ### Returns A tuple of (tile_x, tile_y). ## osm_to_decimal ### Description Converts OSM tile coordinates (x, y) and zoom level back to decimal latitude and longitude. ### Method `tkintermapview.osm_to_decimal(tile_x, tile_y, zoom)` ### Parameters - **tile_x** (int) - The x-coordinate of the OSM tile. - **tile_y** (int) - The y-coordinate of the OSM tile. - **zoom** (int) - The zoom level. ### Returns A tuple of (latitude, longitude). ``` -------------------------------- ### set_path Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Creates a CanvasPath connecting a list of (lat, lon) tuples with a smooth rounded line. Returns the path object. Supports color, width, click callbacks, a name string, and arbitrary .data. ```APIDOC ## set_path — Draw a Polyline Creates a `CanvasPath` connecting a list of `(lat, lon)` tuples with a smooth rounded line. Returns the path object. Supports color, width, click callbacks, a name string, and arbitrary `.data`. ```python # Draw a route between saved markers m_berlin = map_widget.set_marker(52.5163, 13.3777, text="Berlin") m_hamburg = map_widget.set_marker(53.5511, 9.9937, text="Hamburg") def on_path_click(path): print(f"Path '{path.name}' clicked") route = map_widget.set_path( [m_berlin.position, m_hamburg.position, (54.0, 10.0)], color="#e63946", width=6, name="berlin_hamburg_route", command=on_path_click, data={"distance_km": 289}, ) # Modify path after creation route.add_position(53.8, 10.5) # append point route.add_position(52.8, 9.0, index=1) # insert at index 1 route.remove_position(54.0, 10.0) route.set_position_list([(52.5163, 13.3777), (53.5511, 9.9937)]) # replace all route.delete() map_widget.delete_all_path() ``` ``` -------------------------------- ### Create Path with Positions Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Create a path connecting multiple positions on the map. The path object can be modified by adding or removing positions, or by deleting the entire path. ```python # set a path path_1 = map_widget.set_path([marker_2.position, marker_3.position, (52.57, 13.4), (52.55, 13.35)]) # methods path_1.set_position_list(new_position_list) path_1.add_position(position) path_1.remove_position(position) path_1.delete() ``` -------------------------------- ### Download Offline Map Tiles Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Uses the OfflineLoader to download map tiles within a specified geographic bounding box and zoom range, saving them to an SQLite database. This process should be run outside the GUI event loop. ```python from tkintermapview import OfflineLoader # Step 1: download tiles (run once, outside the GUI event loop) loader = OfflineLoader( path="./berlin_tiles.db", tile_server="https://a.tile.openstreetmap.org/{z}/{x}/{y}.png", max_zoom=19, ) loader.save_offline_tiles( position_a=(52.65, 13.1), # NW corner (lat_max, lon_min) position_b=(52.38, 13.8), # SE corner (lat_min, lon_max) zoom_a=1, # minimum zoom level to cache zoom_b=14, # maximum zoom level to cache ) loader.print_loaded_sections() # list all cached regions ``` -------------------------------- ### Set Marker - Place a Position Marker Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Creates and draws a CanvasPositionMarker. Supports custom icons, attached images with zoom-range visibility, click callbacks, and user data. Use for placing points of interest on the map. ```python from PIL import Image, ImageTk # Basic marker m1 = map_widget.set_marker(52.5163, 13.3777, text="Brandenburger Tor") # Fully customized marker with click callback def on_marker_click(marker): print(f"Clicked: {marker.text} at {marker.position}, data={marker.data}") icon_img = ImageTk.PhotoImage(Image.open("pin.png").resize((40, 40))) photo = tkinter.PhotoImage(file="thumbnail.png") m2 = map_widget.set_marker( 48.8584, 2.2945, text="Eiffel Tower", font="Arial 12 bold", text_color="#333333", marker_color_circle="#e63946", marker_color_outside="#457b9d", icon=icon_img, icon_anchor="s", # pin bottom sits on coordinate image=photo, # shown above marker within zoom range image_zoom_visibility=(12, float("inf")), command=on_marker_click, data={"id": 42, "category": "landmark"}, ) # Modify marker after creation m2.set_text("Tour Eiffel") m2.set_position(48.8585, 2.2946) m2.hide_image(True) # hide the attached photo m2.change_icon(icon_img) # swap icon (marker must have had icon from creation) m2.delete() # Bulk deletion map_widget.delete_all_marker() ``` -------------------------------- ### Center Map by Address String Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Geocode an address string and center the map accordingly. Automatically adjusts zoom level. Returns a marker object if `marker=True`, or `False` if the address is not found. ```python # Navigate to a landmark map_widget.set_address("Colosseo, Rome, Italy") # Navigate and place a marker; check for invalid addresses result = map_widget.set_address("Brandenburg Gate, Berlin", marker=True, text="Brandenburg Gate") if result is False: print("Address not found") else: print(f"Navigated to: {result.position}") result.set_text("Brandenburger Tor") # rename the marker later # result.delete() # remove the marker ``` -------------------------------- ### Set Position with Marker Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Set the map's position by address and simultaneously add a red marker with associated text at that location. The returned PositionMarker object can be used to modify or delete the marker. ```python # set current widget position by address marker_1 = map_widget.set_address("colosseo, rome, italy", marker=True) print(marker_1.position, marker_1.text) # get position and text marker_1.set_text("Colosseo in Rome") # set new text # marker_1.set_position(48.860381, 2.338594) # change position # marker_1.delete() ``` -------------------------------- ### Fit Map to Bounding Box Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Adjust the map's position and zoom level to make a specified geographic rectangular area fully visible. The call is deferred to allow widget dimensions to settle. ```python # Fit continental USA map_widget.fit_bounding_box( (49.384358, -124.848974), # top-left (NW corner) (24.396308, -66.885444), # bottom-right (SE corner) ) # Fit Switzerland map_widget.fit_bounding_box((47.808, 5.956), (45.818, 10.492)) ``` -------------------------------- ### set_marker Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Creates and draws a CanvasPositionMarker at the given decimal coordinates. Returns the marker object for later modification or deletion. Supports custom icons, attached images with zoom-range visibility, click callbacks, and arbitrary user data. ```APIDOC ## set_marker — Place a Position Marker Creates and draws a `CanvasPositionMarker` at the given decimal coordinates. Returns the marker object for later modification or deletion. Supports custom icons (`PIL.ImageTk.PhotoImage`), attached `tkinter.PhotoImage` images with zoom-range visibility, click callbacks, and arbitrary user data stored in `.data`. ```python from PIL import Image, ImageTk # Basic marker m1 = map_widget.set_marker(52.5163, 13.3777, text="Brandenburger Tor") # Fully customized marker with click callback def on_marker_click(marker): print(f"Clicked: {marker.text} at {marker.position}, data={marker.data}") icon_img = ImageTk.PhotoImage(Image.open("pin.png").resize((40, 40))) photo = tkinter.PhotoImage(file="thumbnail.png") m2 = map_widget.set_marker( 48.8584, 2.2945, text="Eiffel Tower", font="Arial 12 bold", text_color="#333333", marker_color_circle="#e63946", marker_color_outside="#457b9d", icon=icon_img, icon_anchor="s", # pin bottom sits on coordinate image=photo, # shown above marker within zoom range image_zoom_visibility=(12, float("inf")), command=on_marker_click, data={"id": 42, "category": "landmark"}, ) # Modify marker after creation m2.set_text("Tour Eiffel") m2.set_position(48.8585, 2.2946) m2.hide_image(True) # hide the attached photo m2.change_icon(icon_img) # swap icon (marker must have had icon from creation) m2.delete() # Bulk deletion map_widget.delete_all_marker() ``` ``` -------------------------------- ### Center Map on Coordinates with Marker Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Pan the map to a specific latitude and longitude. Optionally, place a marker at the same position with customizable text and colors. Returns the marker object if created. ```python # Pan to Paris, zoom level 14 map_widget.set_position(48.8566, 2.3522) map_widget.set_zoom(14) # Pan and drop a marker in one call marker = map_widget.set_position( 48.8566, 2.3522, marker=True, text="Paris", text_color="#ffffff", marker_color_circle="#e63946", marker_color_outside="#457b9d", ) print(marker.position) # (48.8566, 2.3522) print(marker.text) # "Paris" ``` -------------------------------- ### Convert Coordinates to Country Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Converts decimal coordinates to a country name using the geocoder library with the OSM provider. ```python country = tkintermapview.convert_coordinates_to_city(51.5122057, -0.0994014) # country: "United Kingdom" ``` -------------------------------- ### Use Offline Tile Database in TkinterMapView Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Constructs a TkinterMapView widget that exclusively uses a pre-downloaded SQLite database for map tiles. Set `use_database_only=True` and provide the `database_path`. ```python import tkinter import tkintermapview root = tkinter.Tk() map_widget = tkintermapview.TkinterMapView( root, width=800, height=600, database_path="./berlin_tiles.db", use_database_only=True, # never make network requests max_zoom=14, # match the zoom range that was cached ) map_widget.pack(fill="both", expand=True) map_widget.set_address("Berlin, Germany") root.mainloop() ``` -------------------------------- ### Add Right Click Menu Command with Coordinates Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Adds a custom option to the right-click context menu that passes click coordinates to the callback function. Useful for actions like dropping a pin at the click location. ```python def drop_pin(coords): map_widget.set_marker(coords[0], coords[1], text="Pinned") map_widget.add_right_click_menu_command( label="Drop Pin", command=drop_pin, pass_coords=True, ) ``` -------------------------------- ### Create and Modify Position Markers Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Set position markers on the map, optionally with text. The returned marker object can be used to modify its position, text, icon, or visibility, or to delete it. ```python # set a position marker marker_2 = map_widget.set_marker(52.516268, 13.377695, text="Brandenburger Tor") marker_3 = map_widget.set_marker(52.55, 13.4, text="52.55, 13.4") # methods marker_3.set_position(...) marker_3.set_text(...) marker_3.change_icon(new_icon) marker_3.hide_image(True) # or False marker_3.delete() ``` -------------------------------- ### Convert Address to Coordinates Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Converts an address string to decimal coordinates. Returns None if the address is not found. Uses the geocoder library with the OSM provider. ```python address = tkintermapview.convert_address_to_coordinates("London") # address: (51.5073219, -0.1276474) ``` -------------------------------- ### Add Right-Click Menu Command Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Adds a custom command to the right-click context menu on the map. If pass_coords is True, the clicked coordinates are passed to the command function. ```python def add_marker_event(coords): print("Add marker:", coords) new_marker = map_widget.set_marker(coords[0], coords[1], text="new marker") map_widget.add_right_click_menu_command(label="Add Marker", command=add_marker_event, pass_coords=True) ``` -------------------------------- ### OSM Tile Coordinate Conversion Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Provides low-level functions for converting between decimal geographic coordinates and OpenStreetMap tile coordinates at a specified zoom level. ```python import tkintermapview # Low-level OSM tile coordinate conversion tile_x, tile_y = tkintermapview.decimal_to_osm(48.8566, 2.3522, zoom=14) lat, lon = tkintermapview.osm_to_decimal(tile_x, tile_y, zoom=14) ``` -------------------------------- ### Set Path - Draw a Polyline Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Connects a list of (lat, lon) tuples with a smooth rounded line. Supports color, width, click callbacks, name, and data. Use for drawing routes or lines on the map. ```python # Draw a route between saved markers m_berlin = map_widget.set_marker(52.5163, 13.3777, text="Berlin") m_hamburg = map_widget.set_marker(53.5511, 9.9937, text="Hamburg") def on_path_click(path): print(f"Path '{path.name}' clicked") route = map_widget.set_path( [m_berlin.position, m_hamburg.position, (54.0, 10.0)], color="#e63946", width=6, name="berlin_hamburg_route", command=on_path_click, data={"distance_km": 289}, ) # Modify path after creation route.add_position(53.8, 10.5) # append point route.add_position(52.8, 9.0, index=1) # insert at index 1 route.remove_position(54.0, 10.0) route.set_position_list([(52.5163, 13.3777), (53.5511, 9.9937)]) # replace all route.delete() map_widget.delete_all_path() ``` -------------------------------- ### Convert Coordinates to City Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Converts decimal coordinates to a city name using the geocoder library with the OSM provider. ```python city = tkintermapview.convert_coordinates_to_city(51.5122057, -0.0994014) # city: "City of London" ``` -------------------------------- ### Convert Coordinates to Address Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Converts decimal coordinates to an address object using the geocoder library with the OSM provider. The address object contains detailed location information. ```python adr = tkintermapview.convert_coordinates_to_address(51.5122057, -0.0994014) print(adr.street, adr.housenumber, adr.postal, adr.city, adr.state, adr.country, adr.latlng) # Output: Knightrider Street None EC4 City of London England United Kingdom [51.512284050000005, -0.09981746110011651] ``` -------------------------------- ### set_polygon Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Creates a CanvasPolygon from a list of (lat, lon) coordinate tuples. Supports fill color, outline color, border width, click callbacks, a name, and .data. Returns the polygon object. ```APIDOC ## set_polygon — Draw a Filled Polygon Creates a `CanvasPolygon` from a list of `(lat, lon)` coordinate tuples. Supports fill color (use `None` for transparent), outline color, border width, click callbacks, a name, and `.data`. Returns the polygon object. ```python def on_polygon_click(polygon): print(f"Polygon '{polygon.name}' clicked, data: {polygon.data}") switzerland = map_widget.set_polygon( [ (47.808, 5.956), (47.808, 10.492), (45.818, 10.492), (45.818, 5.956), ], fill_color="gray90", # use None for no fill outline_color="#e63946", border_width=3, name="switzerland", command=on_polygon_click, data={"country": "CH"}, ) # Modify after creation switzerland.add_position(46.5, 8.0, index=2) switzerland.remove_position(47.808, 5.956) switzerland.delete() map_widget.delete_all_polygon() ``` ``` -------------------------------- ### Fit Map to Bounding Box Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Adjust the map's view to encompass a geographical bounding box defined by two coordinate pairs (top-left and bottom-right). ```python map_widget.fit_bounding_box((, ), (, )) ``` -------------------------------- ### set_address Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Geocodes a given address string using OpenStreetMap Nominatim and centers the map accordingly. The zoom level is automatically adjusted based on the geocoding result. Supports placing a marker and returns `False` if the address is not found. ```APIDOC ## set_address — Center Map by Address String Geocodes the address string using OpenStreetMap Nominatim and centers the map. The zoom level is automatically calculated from the result's bounding box. Returns a `CanvasPositionMarker` if `marker=True`, or `False` if the address was not found. ```python # Navigate to a landmark map_widget.set_address("Colosseo, Rome, Italy") # Navigate and place a marker; check for invalid addresses result = map_widget.set_address("Brandenburg Gate, Berlin", marker=True, text="Brandenburg Gate") if result is False: print("Address not found") else: print(f"Navigated to: {result.position}") result.set_text("Brandenburger Tor") # rename the marker later # result.delete() # remove the marker ``` ``` -------------------------------- ### Set Polygon - Draw a Filled Polygon Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Creates a CanvasPolygon from a list of (lat, lon) coordinate tuples. Supports fill color, outline color, border width, click callbacks, name, and data. Use for defining areas on the map. ```python def on_polygon_click(polygon): print(f"Polygon '{polygon.name}' clicked, data: {polygon.data}") switzerland = map_widget.set_polygon( [ (47.808, 5.956), (47.808, 10.492), (45.818, 10.492), (45.818, 5.956), ], fill_color="gray90", # use None for no fill outline_color="#e63946", border_width=3, name="switzerland", command=on_polygon_click, data={"country": "CH"}, ) # Modify after creation switzerland.add_position(46.5, 8.0, index=2) switzerland.remove_position(47.808, 5.956) switzerland.delete() map_widget.delete_all_polygon() ``` -------------------------------- ### Set Map Position by Address Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Set the map's focus to a location specified by an address string. The widget uses the OpenStreetMap Nominatim service for geocoding. ```python # set current widget position by address map_widget.set_address("colosseo, rome, italy") ``` -------------------------------- ### Delete Individual Map Objects Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Demonstrates how to remove individual map objects like markers, paths, and polygons. Objects can be deleted either by calling their own `.delete()` method or using the widget's helper methods. ```python marker = map_widget.set_marker(52.5, 13.4, text="Temp") path = map_widget.set_path([(52.5, 13.4), (53.5, 10.0)]) poly = map_widget.set_polygon([(52.5, 13.4), (52.5, 14.0), (53.0, 13.7)]) # Delete individual objects map_widget.delete(marker) # via widget helper path.delete() # directly on object poly.delete() # directly on object ``` -------------------------------- ### set_position Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Centers the map view on the given latitude and longitude coordinates. Optionally, a marker can be placed at the specified position with customizable appearance. Returns the marker object if created, otherwise None. ```APIDOC ## set_position — Center Map on Decimal Coordinates Centers the map view on the given latitude/longitude. Pass `marker=True` to simultaneously place a marker at that position; all marker keyword arguments (see `set_marker`) are forwarded. Returns a `CanvasPositionMarker` when `marker=True`, otherwise `None`. ```python # Pan to Paris, zoom level 14 map_widget.set_position(48.8566, 2.3522) map_widget.set_zoom(14) # Pan and drop a marker in one call marker = map_widget.set_position( 48.8566, 2.3522, marker=True, text="Paris", text_color="#ffffff", marker_color_circle="#e63946", marker_color_outside="#457b9d", ) print(marker.position) # (48.8566, 2.3522) print(marker.text) # "Paris" ``` ``` -------------------------------- ### Convert Address to Coordinates Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Performs forward geocoding to convert a human-readable address string into geographic coordinates (latitude, longitude). Returns None if the address is not found. Network calls are synchronous. ```python import tkintermapview # Forward geocode: address string → (lat, lon) tuple, or None if not found coords = tkintermapview.convert_address_to_coordinates("Eiffel Tower, Paris") if coords: print(coords) # (48.8584, 2.2945) map_widget.set_position(*coords, marker=True, text="Eiffel Tower") else: print("Not found") ``` -------------------------------- ### Convert Coordinates to Address and City Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Uses the geocoder library to convert geographic coordinates into human-readable address components or city names. Network calls are synchronous and should be run in a thread. ```python import tkintermapview # Reverse geocode: coordinates → full address object addr = tkintermapview.convert_coordinates_to_address(51.5074, -0.1278) print(addr.street) # "Victoria Embankment" print(addr.city) # "City of London" print(addr.country) # "United Kingdom" print(addr.latlng) # [51.507..., -0.127...] # Coordinates → city name city = tkintermapview.convert_coordinates_to_city(48.8566, 2.3522) print(city) # "Paris" ``` -------------------------------- ### Add Right Click Menu Command without Coordinates Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Adds a custom option to the right-click context menu where the callback function does not receive click coordinates. Suitable for actions that affect the entire map, like zooming. ```python def zoom_in_max(): map_widget.set_zoom(19) map_widget.add_right_click_menu_command( label="Max Zoom", command=zoom_in_max, pass_coords=False, ) ``` -------------------------------- ### Bulk Delete All Map Objects Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Provides methods to efficiently remove all map objects of a specific type (markers, paths, or polygons) from the widget simultaneously. ```python # Bulk delete all objects of each type map_widget.delete_all_marker() map_widget.delete_all_path() map_widget.delete_all_polygon() ``` -------------------------------- ### Set Map Position and Zoom Source: https://github.com/tomschimansky/tkintermapview/blob/main/README.md Set the initial geographical position and zoom level of the map widget using decimal coordinates. Zoom levels range from 0 (lowest) to 19 (highest). ```python # set current widget position and zoom map_widget.set_position(48.860381, 2.338594) # Paris, France map_widget.set_zoom(15) ``` -------------------------------- ### set_zoom Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Sets the current zoom level of the map. The zoom level is constrained by the minimum and maximum zoom values supported by the tile server. The current zoom level can also be read. ```APIDOC ## set_zoom — Set Zoom Level Sets the current zoom level. Valid range is `min_zoom` (automatically computed so the map fills the widget) to `max_zoom` (default 19, or as specified per tile server). Scroll-wheel zoom preserves the pointer position. ```python map_widget.set_zoom(17) # street level map_widget.set_zoom(5) # country level map_widget.set_zoom(2) # world overview # Read current zoom print(map_widget.zoom) # float (may be fractional during animation) ``` ``` -------------------------------- ### get_position Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Retrieves the current geographical coordinates of the map's center. The coordinates are returned as a tuple containing latitude and longitude. ```APIDOC ## get_position — Read Current Map Center Returns the current center of the map widget as a `(latitude, longitude)` decimal tuple. ```python lat, lon = map_widget.get_position() print(f"Map center: {lat:.6f}, {lon:.6f}") # Output: Map center: 48.856600, 2.352200 ``` ``` -------------------------------- ### Convert Coordinates to Country Name Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Converts geographic coordinates into the name of the country. This is a synchronous network call and should be executed in a separate thread to prevent GUI freezing. ```python import tkintermapview # Coordinates → country name country = tkintermapview.convert_coordinates_to_country(35.6762, 139.6503) print(country) # "Japan" ``` -------------------------------- ### Deleting Map Objects Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Provides methods to remove individual map objects (markers, paths, polygons) directly or in bulk using widget helper functions. ```APIDOC ## delete ### Description Removes a specific map object (marker, path, or polygon) from the map. This can be called directly on the object or via the widget's helper method. ### Method `map_widget.delete(map_object)` or `map_object.delete()` ### Parameters - **map_object** - The marker, path, or polygon object to delete. ## delete_all_marker ### Description Removes all markers currently displayed on the map. ### Method `map_widget.delete_all_marker()` ## delete_all_path ### Description Removes all paths currently displayed on the map. ### Method `map_widget.delete_all_path()` ## delete_all_polygon ### Description Removes all polygons currently displayed on the map. ### Method `map_widget.delete_all_polygon()` ``` -------------------------------- ### fit_bounding_box Source: https://context7.com/tomschimansky/tkintermapview/llms.txt Adjusts the map's view (position and zoom level) to encompass a specified geographic bounding box. The bounding box is defined by its north-west and south-east corner coordinates. ```APIDOC ## fit_bounding_box — Zoom to Fit a Geographic Box Adjusts both position and zoom level so that the rectangle defined by `position_top_left` (north-west corner) and `position_bottom_right` (south-east corner) is fully visible at the highest possible zoom. The call is deferred by 100 ms to allow widget dimensions to settle. ```python # Fit continental USA map_widget.fit_bounding_box( (49.384358, -124.848974), # top-left (NW corner) (24.396308, -66.885444), # bottom-right (SE corner) ) # Fit Switzerland map_widget.fit_bounding_box((47.808, 5.956), (45.818, 10.492)) ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.