Obtain coordinates of a Polygon / Multi-polygon around a point in python [duplicate]

2024/9/21 5:36:31

I am using plotlys scattermapbox to draw a polygon around a point object. I'd like to draw a polygon that covers 'x' mile radius from a POI.

I found this that is helpful: https://plotly.com/python/filled-area-on-mapbox/. However, in my case I need to dynamically define the polygon and obtain it's corresponding coordinates.

How do I render and fill a polygon around a center point? Can I use mapbox to get the polygon geometry? We define polygon geometry as x miles from the center.

For reference: https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#fill

Original question here: Draw a polygon around point in scattermapbox using python

Answer
  • using this helper https://github.com/Turbo87/utm to transform between GPS (WSG84 / EPSG:4326) and UTM
  • you expressed that POI circle/polygon radius as a distance x miles hence need to work with UTM projections to express radius as a distances
  • have used UK hospitals as sample POI data. Without significant zoom levels circles will not display as they are only 1 mile radius. It will be simple to plug in any other dataframe with latitude and longitude columns
  • used a scatter mapbox as sample plot, then added layer that are POI circles/polygons
import shapely.geometry
import utm
import pandas as pd
import geopandas as gpd
import requests, io, json
import plotly.express as px# need to use UTM to express radius as a distance. UTM is zoned, so if GPS coords are very widely distributed
# distance will be incorrect.  zone is estimated from first GPS coordinate
# returns geopandas dataframe re-projected to GPS co-ordinates
# radius is expressed in metres
def circles(lonlat, radius=10 ** 4):utm_coords = utm.from_latlon(lonlat[:, 1], lonlat[:, 0])utmcrs = gpd.GeoDataFrame(geometry=[shapely.geometry.Point(lonlat[0, 0], lonlat[0, 1])], crs="EPSG:4326").estimate_utm_crs()return gpd.GeoDataFrame(geometry=[shapely.geometry.Point(easting, northing).buffer(radius)for easting, northing in zip(utm_coords[0], utm_coords[1])],crs=utmcrs,).to_crs("EPSG:4326")# get some public addressess - hospitals.  data that can be scattered
dfhos = pd.read_csv(io.StringIO(requests.get("http://media.nhschoices.nhs.uk/data/foi/Hospital.csv").text),sep="¬",engine="python",)# generate circles of diameter 1 mile, which is 1609.34 metres
gdf = circles(dfhos.head(20).loc[:, ["Longitude", "Latitude"]].values, radius=1609.34)fig = (px.scatter_mapbox(dfhos.head(20),lat="Latitude",lon="Longitude",color="Sector",hover_data=["OrganisationName", "Postcode"],).update_traces(marker={"size": 10}).update_layout(mapbox={"style": "open-street-map","zoom": 9,"center":{"lat":gdf.loc[0,"geometry"].centroid.y, "lon":gdf.loc[0,"geometry"].centroid.x},"layers": [{"source": json.loads(gdf.geometry.to_json()),"below": "traces","type": "line","color": "purple","line": {"width": 1.5},}],},margin={"l": 0, "r": 0, "t": 0, "b": 0},)
)
fig.show()

enter image description here

https://en.xdnf.cn/q/119987.html

Related Q&A

PyCuda Error in Execution

This is my pycuda code for rotation.I have installed the latest cuda drivers and I use a nvidia gpu with cuda support.I have also installed the cuda toolkit and pycuda drivers.Still I get this strange …

Python code to Download Specific JSON key value data through REST API calls

I am trying to write a code in python which download only specific key value in the Calls. So the solution might beDownloading the Raw data and later removing the unwanted through regex or 2)Applying s…

How to measure pairwise distances between two sets of points?

I have two datasets (csv files). Both of them contains latitudes-longitudes of two sets (220 and 4400) of points. Now I want to measure pairwise distances (miles) between these two sets of points (220 …

Interactively Re-color Bars in Matplotlib Bar Chart using Confidence Intervals

Trying to shade the bars in this chart based on the confidence that a selected y-value (represented by the red line) lies within a confidence interval. See recolorBars() method in the class example bel…

Unlock password protected Workbook using VBA or Python

I have a workbook name m.xlsx, but its password protected and Ive forgotten the password. How can I open it or un-protect it?The following code does not work:Unprotect workbook without password I need…

How do I make a variable detect if it is greater than or less than another one?

I am currently learning Python, and I decided to build a small "Guess the Number" type of game. I am using the random feature, and trying to make it so it will detect if the users input is eq…

Python Regular Expression from File

I want to extract lines following some sequence from a file. E.g. a file contains many lines and I want line in sequencejourney (a,b) from station south chennai to station punjab chandigarh journey (c,…

Changing the words keeping its meaning intact [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…

How to create index for a SQLite3 database using SQLAlchemy?

I have multiple SQLite3 databases for which the models are not available. def index_db(name, tempdb):print(f{name.ljust(padding)} Indexing file: {tempdb})if tempdb.endswith(primary.sqlite):conn = sqlit…

Implementing ast.literal_eval on a numpy array

With the following expression, you can convert a string to a python dict.>>> import ast >>> a = ast.literal_eval("{muffin : lolz, foo : kitty}") >>> a {muffin: lolz…