gpt-4.1-mini-2025-04-14· OpenAI
from WildChat-4.8M (AI2)
how to get cartesian coordinates (in wgs-84 ellipsoid) of a shapely linestring?
- User
how to get cartesian coordinates (in wgs-84 ellipsoid) of a shapely linestring?
- Assistant
To get Cartesian coordinates (ECEF - Earth-Centered, Earth-Fixed coordinates) from a Shapely
LineStringdefined in geographic coordinates (latitude, longitude, usually in WGS-84), you need to:- Extract the geographic coordinates (longitude, latitude, optionally altitude) from the
LineString. - Convert each geographic coordinate to Cartesian coordinates in the WGS-84 ellipsoid.
Step-by-step:
1. Prerequisites: libraries
shapelyfor theLineStringpyprojfor coordinate transformation (converting geodetic to geocentric)
If you don't have
pyprojinstalled:bashpip install pyproj shapely2. Example code
pythonfrom shapely.geometry import LineString from pyproj import Transformer # Example LineString: list of (lon, lat) coordinates in degrees line = LineString([ (-122.4194, 37.7749), # San Francisco (lon, lat) (-118.2437, 34.0522), # Los Angeles (-117.1611, 32.7157) # San Diego ]) # Create a transformer to convert from WGS84 geodetic to ECEF (cartesian) transformer = Transformer.from_crs("epsg:4326", "epsg:4978", always_xy=True) # Extract lon, lat from LineString coords and transform each point cartesian_coords = [transformer.transform(lon, lat) for lon, lat in line.coords] print("Cartesian coordinates (X, Y, Z) in meters:") for c in cartesian_coords: print(c)Explanation:
- WGS-84 geodetic: EPSG:4326, with coordinates as (longitude, latitude, altitude). Altitude defaults to 0 if not given.
- WGS-84 ECEF Cartesian: EPSG:4978.
Transformer.from_crs("EPSG:4326", "EPSG:4978")sets up the conversion from lon/lat/alt to X/Y/Z on WGS-84 ellipsoid.always_xy=Trueensures coordinates are interpreted as (lon, lat), which matches Shapely's coordinate order.
Notes:
- Extract the geographic coordinates (longitude, latitude, optionally altitude) from the