crossbind
GitHub
← Tüm kütüphaneler

PROJ

Koordinat referans sistemi dönüşümleri.

Kurulum

Tarayıcılarda çalışır; Node.js ve edge çalışma ortamları da aynı paketi kullanır. Derlendiği hedefler: wasm32, tek ve çok iş parçacıklı.

shell
npm install @crossbind/port-proj-wasm@beta
crossbind.config.js
import projWasm from '@crossbind/port-proj-wasm/crossbind.config.js';
 
export default {
dependencies: [projWasm],
paths: { config: import.meta.url },
};
main.js
import { initNative, proj_context_create } from '@crossbind/port-proj/proj.h';
 
await initNative();

crossbind'ın kendisi paketleyici eklentinizle gelir; Paketleyici eklentileri sayfasında Vite, Webpack, Rspack, Rsbuild, Rollup, esbuild, Bun ve Next.js var.

QGIS'in ve PostGIS'in arkasındaki koordinat motoru tarayıcınızda

PROJ; GDAL, QGIS, PostGIS ve pyproj'un koordinatları referans sistemleri arasında dönüştürmek için çağırdığı kütüphanedir. Bu uygulamalar crossbind ile derlenmiş PROJ 9.9.0 sürümünü proj.db içindeki EPSG kayıt deposuyla çalıştırır: bozduklarıyla birlikte çizilen herhangi bir projeksiyonlu CRS, EPSG koduna ve PROJ'un bildiği her dönüşüm yoluna kadar izlenen bir .prj, bir de sabit pusula yönünü koruyan rotanın yanında en kısa uçuş rotası. PROJ'un 10 megabaytlık veritabanı proj.db, indirmenin çoğunu oluşturur. İlk çalıştırma bir kez 16 MB WebAssembly indirir; bu sayfadaki her uygulama onu paylaşır ve hiçbir şey yüklenmez.

UYGULAMA 01

Bir harita projeksiyonunun neyi gerdiğini görün

Bir dünya haritası ya da EPSG veya ESRI koduyla, WKT ya da PROJ string'iyle herhangi bir projeksiyonlu CRS seçin. PROJ, CRS'in tanımlandığı alan üzerinde enlem-boylam ağını ve yerde hepsi aynı boyutta olan dairelerden bir ızgarayı çizer; böylece dairelerin aldığı şekiller projeksiyonun neyi gerdiğini gösterir. O noktadaki bozulmayı ölçmek için haritaya tıklayın.

Daireler jeodezik dairelerdir: her noktası elipsoit üzerinde merkezden aynı uzaklıkta olan, PROJ'un geodesic.h dosyasından gelen daireler. Bir kod, kullanım alanını EPSG ya da ESRI kayıt deposundan getirir; bir PROJ string'i kullanım alanı taşımaz, bu yüzden bütün dünya çizilir.

MIT lisanslı PROJ 9.9.0 sürümünü çalıştırır: kaynak · lisans · derleme tarifi
Enlem-boylam ağını ve dairelerini görmek için bir projeksiyon çizin.
KODU GÖSTER
src/support/map_projection.h
// src/support/map_projection.h (excerpt)
// From the CRS's own geographic CRS to its map coordinates, so drawing never
// shifts datums, then longitude and easting first whatever the axis order.
const Object geographic = proj.own(proj_crs_get_geodetic_crs(proj.get(), crs.get()), "...");
const Object operation = proj.own(proj_create_crs_to_crs_from_pj(proj.get(), geographic.get(),
crs.get(), nullptr, nullptr), "...");
pipeline = proj.own(proj_normalize_for_visualization(proj.get(), operation.get()), "...");
 
// Scale factors at a point, from PROJ's derivatives of the projection.
out = proj_factors(crs.get(), proj_coord(lon * kRadiansPerDegree, lat * kRadiansPerDegree, 0, 0));
main.js
const m = await initNative();
const atlas = await new m.ProjectionAtlas();
const map = JSON.parse(await atlas.draw('EPSG:8857')); // Equal Earth
// map.graticule, map.outline, map.circles: runs of x, y in metres
const [x, y] = JSON.parse(await atlas.project(30, 40)); // 2549249.49, 4921020.06
 
await atlas.draw('EPSG:3395'); // World Mercator
const at60 = JSON.parse(await atlas.distortion(0, 60));
// at60.areal: 3.97992, so areas at 60°N are drawn four times too big
UYGULAMA 02

Bir .prj dosyasının ne olduğunu ve PROJ'un onu dönüştürebileceği her yolu bulun

Bir shapefile'ın .prj dosyası hiçbir EPSG kodu belirtmez. Bir tane ya da herhangi bir WKT, PROJJSON, PROJ string'i veya kod yapıştırın; PROJ onu EPSG kayıt deposunun kendi kopyasıyla eşleştirir: kodu, CRS'in geçerli olduğu yeri, eksen sırasını, aynı CRS'i dört biçimde ve ikinci bir CRS'e giden her dönüşüm yolunu doğruluğuyla birlikte. JavaScript portu proj4js yalnızca proj4.defs() ile tanımladığınız CRS'leri ve önceden tanımladığı birkaç tanesini bilir; bu yüzden bir .prj'yi eşleştirebileceği bir kayıt deposu yoktur.

YA DA KAYIT DEPOSUNDA AD VEYA KODLA ARAYIN
MIT lisanslı PROJ 9.9.0 sürümünü çalıştırır: kaynak · lisans · derleme tarifi
Kodunu, geçerli olduğu yeri, eksenlerini ve başka bir CRS'e giden her yolu görmek için bir CRS tanımlayın.
KODU GÖSTER
src/native/crs_detective.h
// src/native/crs_detective.h (excerpt)
PJ_OPERATION_FACTORY_CONTEXT* factory = proj_create_operation_factory_context(proj.get(), nullptr);
proj_operation_factory_context_set_spatial_criterion(proj.get(), factory,
PROJ_SPATIAL_CRITERION_PARTIAL_INTERSECTION);
// IGNORED lists every path as if all grids were installed;
// DISCARD_OPERATION_IF_MISSING_GRID lists what this build can run.
proj_operation_factory_context_set_grid_availability_use(proj.get(), factory, grids);
PJ_OBJ_LIST* found = proj_create_operations(proj.get(), from, to, factory);
 
// A .prj names no code: proj_identify matches it against the registry.
PJ_OBJ_LIST* matches = proj_identify(proj.get(), crs, nullptr, nullptr, &confidence);
main.js
const m = await initNative();
const detective = await new m.CrsDetective();
const crs = JSON.parse(await detective.inspect(prjText));
// crs.identified[0]: EPSG:32635, confidence 100
// crs.area, from EPSG:32635: 24°E to 30°E, 0° to 84°N
 
const paths = JSON.parse(await detective.operations('EPSG:4267', 'EPSG:4269'));
// paths.known: 10 operations, 9 of them need a grid this build does not ship
// paths.chosen.name: 'NAD27 to WGS 84 (6) + Inverse of NAD83 to WGS 84 (1)'
UYGULAMA 03

Uçuşlar haritada neden kavis çizer

İki şehir arasındaki en kısa rota, elipsoit üzerinde bir jeodeziktir. Mercator'da kutba doğru kıvrılır; oradaki düz çizgi ise tek bir pusula yönünü koruyan rotadır ve o daha uzundur. İki şehir seçin: PROJ iki rotayı da WGS 84 elipsoidi üzerinde ölçer ve üç haritada çizer.

En kısa rota, PROJ'un geodesic.h olarak taşıdığı Charles Karney algoritması geod_inverse'ten gelir. Sabit yönlü rota, yani loksodrom, iki şehir arasında elipsoidal Mercator üzerindeki düz çizgidir; PROJ onu nokta nokta ters projeksiyonla geri çevirir.

MIT lisanslı PROJ 9.9.0 sürümünü çalıştırır: kaynak · lisans · derleme tarifi
En kısa rotayı ve sabit yönlü rotayı çizmek için iki şehir seçin.
KODU GÖSTER
src/native/flight_paths.h
// src/native/flight_paths.h and src/support/map_projection.h (excerpts)
// The shortest route: points along the geodesic, from geodesic.h.
geod_inverseline(&route, &ellipsoid, lat1, lon1, lat2, lon2, 0);
geod_position(&route, route.s13 * index / points, &lat, &lon, nullptr);
 
// The constant heading: a straight line on ellipsoidal Mercator (EPSG:3395),
// which is conformal, unprojected back to longitude and latitude.
x2 = x1 + std::remainder(x2 - x1, world); // the short way round
heading = std::fmod(std::atan2(x2 - x1, y2 - y1) / projapp::kRadiansPerDegree + 360, 360.0);
mercator.unproject(x1 + t * (x2 - x1), y1 + t * (y2 - y1), lon, lat);
main.js
const m = await initNative();
const flights = await new m.FlightPaths();
const route = JSON.parse(await flights.route(41.0082, 28.9784, 40.6413, -73.7781));
// Istanbul to New York JFK: route.geodesic.meters 8080310.14,
// route.rhumb.meters 8668353.46 at a heading of 269.73°
 
const map = JSON.parse(await flights.draw('EPSG:3395', 41.0082, 28.9784, 40.6413, -73.7781));
// map.geodesic and map.rhumb: runs of x, y on World Mercator

Örnekler

Her biri küçük bir C++ başlık dosyası ve onu çağıran JavaScript; site derlenirken yazdırdıklarıyla birlikte. Yalnızca JavaScript sekmesi aynısını PROJ kütüphanesinin kendi başlık dosyalarıyla, C++ dosyası olmadan yapar. Sonuncusu WASI için derlenmiş eksiksiz bir C++ programıdır.

Bir koordinatı iki CRS arasında dönüştürün

PROJ'un en çok kullanılan parçası: proj_create_crs_to_crs iki koordinat referans sistemi arasındaki işlemi seçer, proj_normalize_for_visualization boylamı başa alır, proj_trans da onu ileri ya da geri çalıştırır.

src/native/transformer.h
#pragma once
 
#include <proj.h>
 
#include <cmath>
#include <cstdio>
#include <stdexcept>
#include <string>
 
// Converts coordinates between two coordinate reference systems given as EPSG or ESRI codes, WKT,
// PROJJSON or PROJ strings. Axis order is normalised to longitude or easting first, so EPSG:4326
// takes (longitude, latitude) although EPSG defines it latitude first.
class Transformer {
public:
Transformer(const std::string& source, const std::string& target) : context(proj_context_create()) {
proj_log_func(context, &error, remember);
PJ* chosen = proj_create_crs_to_crs(context, source.c_str(), target.c_str(), nullptr);
if (chosen) {
name = proj_get_name(chosen);
transformation = proj_normalize_for_visualization(context, chosen);
proj_destroy(chosen);
}
if (!transformation) {
const std::string reason = error.empty() ? proj_context_errno_string(context, proj_context_errno(context)) : error;
proj_context_destroy(context);
throw std::runtime_error(reason);
}
}
 
~Transformer() {
proj_destroy(transformation);
proj_context_destroy(context);
}
 
Transformer(const Transformer&) = delete;
Transformer& operator=(const Transformer&) = delete;
 
// Both return the point as a JSON array, [x, y].
std::string forward(double x, double y) { return apply(PJ_FWD, x, y); }
std::string inverse(double x, double y) { return apply(PJ_INV, x, y); }
 
// The operation PROJ picked, e.g. "UTM zone 35N".
std::string operation() const { return name; }
 
private:
std::string apply(PJ_DIRECTION direction, double x, double y) {
proj_errno_reset(transformation);
const PJ_COORD out = proj_trans(transformation, direction, proj_coord(x, y, 0, HUGE_VAL));
if (out.xy.x == HUGE_VAL) throw std::runtime_error(proj_context_errno_string(context, proj_errno(transformation)));
char json[64];
std::snprintf(json, sizeof json, "[%.17g,%.17g]", out.xy.x, out.xy.y);
return json;
}
 
// PROJ reports why a definition failed through its log, e.g. "crs not found: EPSG:99999".
static void remember(void* error, int level, const char* message) {
if (level == PJ_LOG_ERROR) *static_cast<std::string*>(error) = message;
}
 
PJ_CONTEXT* context;
PJ* transformation = nullptr;
std::string name;
std::string error;
};
main.js
import { initNative, Transformer } from './native/transformer.h';
 
await initNative();
const toUtm = await new Transformer('EPSG:4326', 'EPSG:32635'); // WGS 84 to UTM zone 35N
console.log(await toUtm.operation());
const [easting, northing] = JSON.parse(await toUtm.forward(28.9784, 41.0082)); // Istanbul, longitude first
console.log(easting.toFixed(2), northing.toFixed(2));
const [longitude, latitude] = JSON.parse(await toUtm.inverse(easting, northing));
console.log(longitude.toFixed(6), latitude.toFixed(6));
const toWebMap = await new Transformer('EPSG:4326', 'EPSG:3857'); // WGS 84 to Web Mercator
console.log(await toWebMap.operation());
const [x, y] = JSON.parse(await toWebMap.forward(28.9784, 41.0082));
console.log(x.toFixed(2), y.toFixed(2));
ÇIKTISIilk çalıştırma 16 MB indirir
UTM zone 35N
666370.51 4541552.49
28.978400 41.008200
Popular Visualisation Pseudo-Mercator
3225860.73 5013551.24

Bir CRS'i WKT, .prj, PROJJSON ya da PROJ string'i olarak yazın

proj_create bir CRS'i bir EPSG kodundan ya da herhangi bir tanımdan okur; proj_as_wkt, WKT2'yi ya da bir shapefile'ın .prj dosyasının tuttuğu ESRI WKT'yi, proj_as_projjson PROJJSON'u, proj_as_proj_string de adları ve kullanım alanını atan kısa PROJ string'ini yazar.

src/native/crs_formats.h
#pragma once
 
#include <proj.h>
 
#include <stdexcept>
#include <string>
 
// Reads a CRS from any definition PROJ accepts and writes it out in the formats other software
// reads: WKT2 (ISO 19162, what GDAL and QGIS write), WKT1 the way ESRI writes it (the text of a
// shapefile's .prj), PROJJSON, and the PROJ string.
class CrsFormats {
public:
explicit CrsFormats(const std::string& definition) : context(proj_context_create()) {
proj_log_func(context, &error, remember);
crs = proj_create(context, definition.c_str());
if (!crs || !proj_is_crs(crs)) {
const std::string reason = crs ? definition + " is not a CRS" : error.empty() ? "PROJ cannot read " + definition : error;
proj_destroy(crs);
proj_context_destroy(context);
throw std::runtime_error(reason);
}
}
 
~CrsFormats() {
proj_destroy(crs);
proj_context_destroy(context);
}
 
CrsFormats(const CrsFormats&) = delete;
CrsFormats& operator=(const CrsFormats&) = delete;
 
// "EPSG:32635 WGS 84 / UTM zone 35N"; just the name when the definition carries no code.
std::string label() const {
const char* authority = proj_get_id_auth_name(crs, 0);
const char* code = proj_get_id_code(crs, 0);
const std::string name = proj_get_name(crs);
return authority && code ? std::string(authority) + ":" + code + " " + name : name;
}
 
std::string wkt() { return text(proj_as_wkt(context, crs, PJ_WKT2_2019, nullptr)); }
std::string esriWkt() { return text(proj_as_wkt(context, crs, PJ_WKT1_ESRI, nullptr)); }
std::string projJson() { return text(proj_as_projjson(context, crs, nullptr)); }
// A PROJ string keeps the maths and drops the metadata, such as the name and the area of use.
std::string projString() { return text(proj_as_proj_string(context, crs, PJ_PROJ_5, nullptr)); }
 
private:
// The exporters return text owned by the CRS object, so it is copied at once.
std::string text(const char* exported) const {
if (!exported) throw std::runtime_error(error.empty() ? "PROJ cannot write this CRS in that format" : error);
return exported;
}
 
static void remember(void* error, int level, const char* message) {
if (level == PJ_LOG_ERROR) *static_cast<std::string*>(error) = message;
}
 
PJ_CONTEXT* context;
PJ* crs = nullptr;
std::string error;
};
main.js
import { initNative, CrsFormats } from './native/crs_formats.h';
 
await initNative();
const utm = await new CrsFormats('EPSG:32635');
console.log(await utm.label());
console.log(await utm.projString());
console.log((await utm.wkt()).split('\n')[0]); // the first line of WKT2
console.log(await utm.esriWkt()); // the text of a shapefile's .prj
const json = JSON.parse(await utm.projJson());
console.log(json.type, json.conversion.method.name, json.conversion.parameters.map((parameter) => parameter.value).join(' '));
ÇIKTISIilk çalıştırma 16 MB indirir
EPSG:32635 WGS 84 / UTM zone 35N
+proj=utm +zone=35 +datum=WGS84 +units=m +no_defs +type=crs
PROJCRS["WGS 84 / UTM zone 35N",
PROJCS["WGS_1984_UTM_Zone_35N",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",27.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]
ProjectedCRS Transverse Mercator 0 27 0.9996 500000 0

Bir CRS'in nerede geçerli olduğunu ve eksenlerinin sırasını okuyun

proj_get_area_of_use, EPSG'nin bir CRS'i tanımladığı bölgeyi derece cinsinden bir sınırlayıcı kutu ve bir açıklama olarak verir. proj_crs_get_coordinate_system ve proj_cs_get_axis_info eksen sırasını verir: EPSG:4326 için önce enlem, Polonya'nın ızgarası için önce kuzey koordinatı.

src/native/crs_usage.h
#pragma once
 
#include <proj.h>
 
#include <cstdio>
#include <stdexcept>
#include <string>
 
// Where a CRS may be used and the order of its axes, both from PROJ's copy of the EPSG registry.
// Axis order is the classic trap: EPSG:4326 is latitude first, and so are many national grids.
class CrsUsage {
public:
explicit CrsUsage(const std::string& definition) : context(proj_context_create()) {
proj_log_func(context, &error, remember);
crs = proj_create(context, definition.c_str());
if (!crs || !proj_is_crs(crs)) {
const std::string reason = crs ? definition + " is not a CRS" : error.empty() ? "PROJ cannot read " + definition : error;
proj_destroy(crs);
proj_context_destroy(context);
throw std::runtime_error(reason);
}
}
 
~CrsUsage() {
proj_destroy(crs);
proj_context_destroy(context);
}
 
CrsUsage(const CrsUsage&) = delete;
CrsUsage& operator=(const CrsUsage&) = delete;
 
// [west, south, east, north, "description"], in degrees.
std::string areaOfUse() {
double west, south, east, north;
const char* name = nullptr;
if (!proj_get_area_of_use(context, crs, &west, &south, &east, &north, &name)) throw std::runtime_error("this CRS has no area of use");
char box[128];
std::snprintf(box, sizeof box, "[%.10g,%.10g,%.10g,%.10g,", west, south, east, north);
return box + quote(name) + "]";
}
 
// [["Easting","E","east","metre"], ...]: name, abbreviation, direction and unit of each axis,
// in the order coordinates are written.
std::string axes() {
PJ* system = proj_crs_get_coordinate_system(context, crs);
if (!system) throw std::runtime_error("this CRS has no coordinate system");
std::string json = "[";
for (int index = 0; index < proj_cs_get_axis_count(context, system); index += 1) {
const char* name = nullptr;
const char* abbreviation = nullptr;
const char* direction = nullptr;
const char* unit = nullptr;
proj_cs_get_axis_info(context, system, index, &name, &abbreviation, &direction, nullptr, &unit, nullptr, nullptr);
json += std::string(index ? ",[" : "[") + quote(name) + "," + quote(abbreviation) + "," + quote(direction) + "," + quote(unit) + "]";
}
proj_destroy(system);
return json + "]";
}
 
private:
static std::string quote(const char* text) {
std::string out = "\"";
for (const char* at = text ? text : ""; *at; at += 1) {
if (*at == '"' || *at == '\\') out += '\\';
out += *at;
}
return out + "\"";
}
 
static void remember(void* error, int level, const char* message) {
if (level == PJ_LOG_ERROR) *static_cast<std::string*>(error) = message;
}
 
PJ_CONTEXT* context;
PJ* crs = nullptr;
std::string error;
};
main.js
import { initNative, CrsUsage } from './native/crs_usage.h';
 
await initNative();
for (const code of ['EPSG:4326', 'EPSG:2180', 'EPSG:2056']) {
const crs = await new CrsUsage(code);
const axes = JSON.parse(await crs.axes()).map(([, abbreviation, direction, unit]) => `${abbreviation} ${direction} (${unit})`);
const [west, south, east, north, description] = JSON.parse(await crs.areaOfUse());
console.log(`${code}: ${axes.join(', ')} | ${description} ${west} ${south} ${east} ${north}`);
}
ÇIKTISIilk çalıştırma 16 MB indirir
EPSG:4326: Lat north (degree), Lon east (degree) | World. -180 -90 180 90
EPSG:2180: x north (metre), y east (metre) | Poland - onshore and offshore. 14.14 49 24.15 55.93
EPSG:2056: E east (metre), N north (metre) | Liechtenstein; Switzerland. 5.95 45.81 10.5 47.81

Elipsoit üzerinde mesafeleri, yönleri ve alanları ölçün

geod_inverse, WGS 84 elipsoidi üzerinde iki nokta arasındaki en kısa yolu ve yönlerini, geod_direct bir yön ve mesafenin nereye vardığını, geod_polygonarea da bir poligonun alanını verir. Bu, PROJ'un parçası olan GeographicLib'in algoritmasıdır; ne bir CRS'e ne de proj.db'ye ihtiyaç duyar.

src/native/geodesy.h
#pragma once
 
#include <geodesic.h>
 
#include <cstdio>
#include <cstdlib>
#include <stdexcept>
#include <string>
#include <vector>
 
// Distances, headings and areas on the WGS 84 ellipsoid with geodesic.h, the C version of Charles
// Karney's GeographicLib that ships inside PROJ. Angles are in degrees, headings clockwise from north.
class Geodesy {
public:
// [meters, azimuth1, azimuth2]: the length of the shortest route between two points, and the
// heading at its start and at its end.
static std::string inverse(double lat1, double lon1, double lat2, double lon2) {
double meters, azimuth1, azimuth2;
geod_inverse(&wgs84(), lat1, lon1, lat2, lon2, &meters, &azimuth1, &azimuth2);
return json(meters, azimuth1, azimuth2);
}
 
// [lat, lon, azimuth]: where you arrive after `meters` from a point on a heading, and the
// heading you arrive with.
static std::string direct(double lat, double lon, double azimuth, double meters) {
double lat2, lon2, azimuth2;
geod_direct(&wgs84(), lat, lon, azimuth, meters, &lat2, &lon2, &azimuth2);
return json(lat2, lon2, azimuth2);
}
 
// [m2, perimeter] of a polygon whose corners are latitude, longitude pairs in any text, such
// as JSON: [[lat, lon], [lat, lon], ...]. Counter-clockwise corners give a positive area.
static std::string area(const std::string& corners) {
const std::vector<double> numbers = numbersIn(corners);
if (numbers.size() < 6 || numbers.size() % 2) throw std::invalid_argument("a polygon needs at least three latitude, longitude pairs");
std::vector<double> lats, lons;
for (size_t index = 0; index < numbers.size(); index += 2) {
lats.push_back(numbers[index]);
lons.push_back(numbers[index + 1]);
}
double m2, perimeter;
geod_polygonarea(&wgs84(), lats.data(), lons.data(), static_cast<int>(lats.size()), &m2, &perimeter);
char text[64];
std::snprintf(text, sizeof text, "[%.17g,%.17g]", m2, perimeter);
return text;
}
 
private:
static const geod_geodesic& wgs84() {
static const geod_geodesic ellipsoid = [] {
geod_geodesic g;
geod_init(&g, 6378137, 1 / 298.257223563);
return g;
}();
return ellipsoid;
}
 
static std::string json(double a, double b, double c) {
char text[96];
std::snprintf(text, sizeof text, "[%.17g,%.17g,%.17g]", a, b, c);
return text;
}
 
static std::vector<double> numbersIn(const std::string& text) {
std::vector<double> numbers;
const char* at = text.c_str();
while (*at) {
char* end = nullptr;
const double value = std::strtod(at, &end);
if (end == at) {
at += 1;
} else {
numbers.push_back(value);
at = end;
}
}
return numbers;
}
};
main.js
import { initNative, Geodesy } from './native/geodesy.h';
 
await initNative();
const compass = (azimuth) => ((azimuth + 360) % 360).toFixed(2);
const [meters, departure, arrival] = JSON.parse(await Geodesy.inverse(41.0082, 28.9784, 40.6413, -73.7781)); // Istanbul to New York JFK
console.log(`${(meters / 1000).toFixed(3)} km, leaving on ${compass(departure)}°, arriving on ${compass(arrival)}°`);
const [lat, lon] = JSON.parse(await Geodesy.direct(41.0082, 28.9784, departure, meters / 2));
console.log(`halfway at ${lat.toFixed(4)}, ${lon.toFixed(4)}`); // far north of both cities
const triangle = [[25.7617, -80.1918], [18.4655, -66.1057], [32.3078, -64.7505]]; // Miami, San Juan, Bermuda
const [m2, perimeter] = JSON.parse(await Geodesy.area(JSON.stringify(triangle)));
console.log(`${(m2 / 1e6).toFixed(1)} km², perimeter ${(perimeter / 1000).toFixed(1)} km`);
ÇIKTISIilk çalıştırma 16 MB indirir
8080.310 km, leaving on 309.12°, arriving on 230.50°
halfway at 54.1948, -22.5976
1145170.4 km², perimeter 4868.1 km

Bir .prj dosyasının EPSG kodunu ve bir noktanın UTM dilimini bulun

Bir shapefile'ın .prj dosyası hiçbir EPSG kodu belirtmez. proj_identify onu kayıt deposuyla eşleştirir; bir PROJ string'inde olduğu gibi adlar eksik olduğunda düşen bir güvenle. proj_get_crs_info_list_from_database, kullanım alanı bir noktayı içeren CRS'leri listeler.

src/native/crs_lookup.h
#pragma once
 
#include <proj.h>
 
#include <stdexcept>
#include <string>
 
// Finds CRSs in PROJ's copy of the EPSG registry: the code that a .prj file or any WKT describes,
// and the projected CRSs that may be used at a point.
class CrsLookup {
public:
// [["EPSG:32635","WGS 84 / UTM zone 35N",100], ...]: code, name and confidence, best match
// first. The confidence is 100 when the definition matches an EPSG entry exactly, names
// included, and lower as details are missing or differ.
static std::string identify(const std::string& definition) {
Session proj;
PJ* crs = proj.create(definition);
int* confidence = nullptr;
PJ_OBJ_LIST* matches = proj_identify(proj.context, crs, "EPSG", nullptr, &confidence);
std::string json = "[";
for (int index = 0; matches && index < proj_list_get_count(matches); index += 1) {
PJ* match = proj_list_get(proj.context, matches, index);
json += std::string(index ? ",[" : "[") + entry(proj_get_id_auth_name(match, 0), proj_get_id_code(match, 0), proj_get_name(match)) + "," +
std::to_string(confidence[index]) + "]";
proj_destroy(match);
}
proj_int_list_destroy(confidence);
proj_list_destroy(matches);
proj_destroy(crs);
return json + "]";
}
 
// [["EPSG:32635","WGS 84 / UTM zone 35N"], ...]: the projected CRSs whose area of use
// contains the point and whose name contains `words`, deprecated ones left out.
static std::string projectedAt(double lat, double lon, const std::string& words) {
Session proj;
PROJ_CRS_LIST_PARAMETERS* filter = proj_get_crs_list_parameters_create();
const PJ_TYPE projected = PJ_TYPE_PROJECTED_CRS;
filter->types = &projected;
filter->typesCount = 1;
filter->bbox_valid = 1;
filter->west_lon_degree = filter->east_lon_degree = lon;
filter->south_lat_degree = filter->north_lat_degree = lat;
filter->crs_area_of_use_contains_bbox = 1;
int count = 0;
PROJ_CRS_INFO** found = proj_get_crs_info_list_from_database(proj.context, "EPSG", filter, &count);
std::string json = "[";
for (int index = 0; index < count; index += 1) {
const PROJ_CRS_INFO* crs = found[index];
if (std::string(crs->name).find(words) == std::string::npos) continue;
json += std::string(json.size() > 1 ? ",[" : "[") + entry(crs->auth_name, crs->code, crs->name) + "]";
}
proj_crs_info_list_destroy(found);
proj_get_crs_list_parameters_destroy(filter);
return json + "]";
}
 
private:
// One PROJ context per call; it also keeps the last error PROJ logged.
struct Session {
PJ_CONTEXT* context = proj_context_create();
std::string error;
 
Session() { proj_log_func(context, &error, remember); }
~Session() { proj_context_destroy(context); }
Session(const Session&) = delete;
Session& operator=(const Session&) = delete;
 
PJ* create(const std::string& definition) {
PJ* crs = proj_create(context, definition.c_str());
if (crs && proj_is_crs(crs)) return crs;
proj_destroy(crs);
throw std::runtime_error(error.empty() ? "PROJ cannot read this CRS definition" : error);
}
 
static void remember(void* error, int level, const char* message) {
if (level == PJ_LOG_ERROR) *static_cast<std::string*>(error) = message;
}
};
 
// "EPSG:32635","WGS 84 / UTM zone 35N"
static std::string entry(const char* authority, const char* code, const char* name) {
const std::string id = authority && code ? std::string(authority) + ":" + code : "";
return quote(id.c_str()) + "," + quote(name);
}
 
static std::string quote(const char* text) {
std::string out = "\"";
for (const char* at = text ? text : ""; *at; at += 1) {
if (*at == '"' || *at == '\\') out += '\\';
out += *at;
}
return out + "\"";
}
};
main.js
import { initNative, CrsLookup } from './native/crs_lookup.h';
 
await initNative();
const prj =
'PROJCS["WGS_1984_UTM_Zone_35N",GEOGCS["GCS_WGS_1984",DATUM["D_WGS_1984",SPHEROID["WGS_1984",6378137.0,298.257223563]],PRIMEM["Greenwich",0.0],UNIT["Degree",0.0174532925199433]],PROJECTION["Transverse_Mercator"],PARAMETER["False_Easting",500000.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",27.0],PARAMETER["Scale_Factor",0.9996],PARAMETER["Latitude_Of_Origin",0.0],UNIT["Meter",1.0]]';
for (const definition of [prj, '+proj=utm +zone=35 +datum=WGS84 +units=m +no_defs +type=crs']) {
const [[code, name, confidence]] = JSON.parse(await CrsLookup.identify(definition)); // the best match
console.log(`${code} ${name}, confidence ${confidence}`);
}
for (const [place, lat, lon] of [['Istanbul', 41.0082, 28.9784], ['Sydney', -33.8688, 151.2093]]) {
const [[code, name]] = JSON.parse(await CrsLookup.projectedAt(lat, lon, 'WGS 84 / UTM zone'));
console.log(`${place}: ${code} ${name}`);
}
ÇIKTISIilk çalıştırma 16 MB indirir
EPSG:32635 WGS 84 / UTM zone 35N, confidence 100
EPSG:32635 WGS 84 / UTM zone 35N, confidence 70
Istanbul: EPSG:32635 WGS 84 / UTM zone 35N
Sydney: EPSG:32756 WGS 84 / UTM zone 56S

Bir PROJ komut satırı aracı

WASI'de JavaScript binding'leri yoktur: program, kütüphaneyi bağlayan, tek bir .wasm olarak derlenen ve wasmtime ile çalıştırılan bir main()'dir. Bu program, derlemenin dist/data/proj içine kopyaladığı PROJ veritabanını, proj.db'yi okur; PROJ_DATA değişkeni de PROJ'a onun nerede olduğunu söyler. Bir CRS'i tanımlar ve GPS konumlarını, EPSG'nin 1 m doğruluk verdiği Helmert dönüşümüyle İsviçre LV95 ızgara koordinatlarına çevirir.

crossbind.config.js
import projWasi from '@crossbind/port-proj-wasi/crossbind.config.js';
 
export default {
general: { name: 'proj-tool' },
dependencies: [projWasi],
// The program and the proj.db it reads land in dist/.
paths: { config: import.meta.url, output: 'dist' },
};
src/native/main.cpp
// A command-line PROJ for WASI: describes a CRS from proj.db, or transforms the points of a file.
// proj-tool info <crs>
// proj-tool <source crs> <target crs> <points file>
// A points file has one "x y label" per line, longitude or easting first whatever the CRS's axis order.
#include <proj.h>
 
#include <cmath>
#include <cstdio>
#include <fstream>
#include <sstream>
#include <string>
 
namespace {
 
void report(void*, int level, const char* message) {
if (level == PJ_LOG_ERROR) std::fprintf(stderr, "proj: %s\n", message);
}
 
int info(PJ_CONTEXT* context, const char* definition) {
PJ* crs = proj_create(context, definition);
if (!crs) return 1;
std::printf("%s\n", proj_get_name(crs));
double west, south, east, north;
const char* area = nullptr;
if (proj_get_area_of_use(context, crs, &west, &south, &east, &north, &area)) std::printf("area: %g %g %g %g, %s\n", west, south, east, north, area);
PJ* system = proj_crs_get_coordinate_system(context, crs);
std::printf("axes:");
for (int index = 0; system && index < proj_cs_get_axis_count(context, system); index += 1) {
const char* abbreviation = nullptr;
const char* direction = nullptr;
proj_cs_get_axis_info(context, system, index, nullptr, &abbreviation, &direction, nullptr, nullptr, nullptr, nullptr);
std::printf("%s %s %s", index ? "," : "", abbreviation, direction);
}
std::printf("\n");
proj_destroy(system);
proj_destroy(crs);
return 0;
}
 
int transform(PJ_CONTEXT* context, const char* source, const char* target, const char* path) {
std::ifstream file(path);
if (!file) {
std::fprintf(stderr, "cannot open %s\n", path);
return 1;
}
PJ* chosen = proj_create_crs_to_crs(context, source, target, nullptr);
if (!chosen) return 1;
std::printf("%s\n", proj_get_name(chosen));
PJ* transformation = proj_normalize_for_visualization(context, chosen);
proj_destroy(chosen);
if (!transformation) return 1;
std::string line;
while (std::getline(file, line)) {
std::istringstream fields(line);
double x, y;
if (!(fields >> x >> y)) continue;
std::string label;
std::getline(fields >> std::ws, label);
const PJ_COORD out = proj_trans(transformation, PJ_FWD, proj_coord(x, y, 0, HUGE_VAL));
if (out.xy.x == HUGE_VAL) {
std::printf("%s: %s\n", label.c_str(), proj_context_errno_string(context, proj_errno(transformation)));
} else {
std::printf("%s: %.2f %.2f\n", label.c_str(), out.xy.x, out.xy.y);
}
}
proj_destroy(transformation);
return 0;
}
 
} // namespace
 
int main(int argc, char** argv) {
PJ_CONTEXT* context = proj_context_create();
proj_log_func(context, nullptr, report);
const std::string command = argc >= 2 ? argv[1] : "";
int code = 2;
if (command == "info" && argc == 3) {
code = info(context, argv[2]);
} else if (command != "info" && argc == 4) {
code = transform(context, argv[1], argv[2], argv[3]);
} else {
std::fprintf(stderr, "usage: proj-tool info <crs>\n proj-tool <source crs> <target crs> <points file>\n");
}
proj_context_destroy(context);
return code;
}
shell
npx crossbind build -p wasi -e wasi -b release
wasmtime run --dir=. --env PROJ_DATA=dist/data/proj dist/proj-tool-wasi-wasm32-st-release.wasm info EPSG:2056
wasmtime run --dir=. --env PROJ_DATA=dist/data/proj dist/proj-tool-wasi-wasm32-st-release.wasm EPSG:4326 EPSG:2056 points.txt
output
CH1903+ / LV95
area: 5.95 45.81 10.5 47.81, Liechtenstein; Switzerland.
axes: E east, N north
Inverse of CH1903+ to WGS 84 (1) + Swiss Oblique Mercator 1995
Zurich: 2683196.61 1248035.31
Bern: 2600408.64 1199501.66
Geneva: 2500986.15 1118138.65
Matterhorn: 2617047.96 1091660.42
Rehberin tüm sayfalarında ve bölümlerinde aramak için yazın.
↑↓ gezinin↵ açınesc kapatın