我有一个基于 geojson 的多边形。如何绘制一个圆以使 geojson 适合圆内?
我尝试过谷歌,但运气不佳。
在不知道您的
.geojson
文件是什么样子的情况下,我无法为您提供更具体的解决方案。假设您的 .geojson
看起来像这样:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
0,
0
],
[
0,
4
],
[
4,
4
],
[
4,
0
],
[
0,
0
]
]
]
},
"properties": {}
},
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
2.0,
2.0
]
},
"properties": {
"radius": 2.8284271247461903
}
}
]
}
import geojson
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon as mpl_polygon, Circle as mpl_circle
# Load the GeoJSON file
with open('polygon_and_circle.geojson', 'r') as f:
geojson_data = geojson.load(f)
# Extract the coordinates of the first polygon
polygon_coordinates = np.array(geojson_data['features'][0]['geometry']['coordinates'][0])
# Calculate the bounding box of the polygon
minx, miny = np.min(polygon_coordinates, axis=0)
maxx, maxy = np.max(polygon_coordinates, axis=0)
# Calculate the center point
center_x = (minx + maxx) / 2
center_y = (miny + maxy) / 2
# Calculate the radius based on the distance from the center to the farthest vertex
radius = max(np.sqrt((maxx - center_x)**2 + (maxy - center_y)**2),
np.sqrt((minx - center_x)**2 + (maxy - center_y)**2),
np.sqrt((maxx - center_x)**2 + (miny - center_y)**2),
np.sqrt((minx - center_x)**2 + (miny - center_y)**2))
# Create the plot
fig, ax = plt.subplots()
# Plot the polygon
polygon_patch = mpl_polygon(polygon_coordinates, edgecolor='green', fill=False)
ax.add_patch(polygon_patch)
# Plot the circle
circle_patch = mpl_circle((center_x, center_y), radius, edgecolor='red', fill=False)
ax.add_patch(circle_patch)
# Set plot limits
ax.set_xlim(minx - radius, maxx + radius)
ax.set_ylim(miny - radius, maxy + radius)
# Show the plot
plt.xlabel('Longitude')
plt.ylabel('Latitude')
plt.title('Polygon with Enclosing Circle')
plt.gca().set_aspect('equal', adjustable='box')
plt.grid()
plt.show()