is it possible to center a map using geopandas?

Thanks to everyone who responded. I adapted Russell Jarvis’ solution from Set centre of geopandas map. I am sharing because the previous answer was using networkx and I used geopandas DataFrame and updated the geometry directly, returning the updated dataframe. I apologize for overlooking these, it seems that when I created the question, I typed “contextily” instead of “geopandas” and missed them!

def shift_geom(self,shift, gdataframe, gdf1, gdf2, plotQ=True):
    # this code is adapted from answer found in SO
    # will be credited here: ???
    shift -= 180
    moved_geom = []
    splitted_geom = []
    border = LineString([(shift,90),(shift,-90)])

    for row in gdataframe["geometry"]:
        splitted_geom.append(split(row, border))
    for element in splitted_geom:
        items = list(element)
        for item in items:
            minx, miny, maxx, maxy = item.bounds
            if minx >= shift:
                moved_geom.append(translate(item, xoff=-180-shift))
                moved_geom.append(translate(item, xoff=180-shift))

    # got `moved_geom` as the moved geometry            
    moved_geom_gdf = gpd.GeoDataFrame({"geometry": moved_geom})

    # can change crs here
    if plotQ:
        fig1, ax1 = plt.subplots(figsize=[8,6])
    geom1 = gdf1.geometry.values
    geom2 = gdf2.geometry.values
    moved_map_points1 = []
    moved_map_points2 = []
    lines = []

    for element in geom1:

        if float(element.x) >= shift:        
            moved_map_points1.append(translate(element, xoff=-180-shift))
            moved_map_points1.append(translate(element, xoff=180-shift))

    for element in geom2:

        if float(element.x) >= shift:        
            moved_map_points2.append(translate(element, xoff=-180-shift))
            moved_map_points2.append(translate(element, xoff=180-shift))
    gdf1 = gdf1.set_geometry(moved_map_points1)
    gdf2 = gdf2.set_geometry(moved_map_points2)
    for el in range(len(moved_map_points1)):
        lines.append(LineString([(moved_map_points1[el].x, moved_map_points1[el].y),
(moved_map_points2[el].x, moved_map_points2[el].y)]))
    gdfl = gdfl.set_geometry(lines)

    return moved_geom_gdf,gdf1,gdf2,gdfl

This results in the following map: shifted geopandas map with points linked with line

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top