• Stars
    star
    845
  • Rank 53,717 (Top 2 %)
  • Language
    PHP
  • License
    Other
  • Created over 13 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Advanced geometry operations in PHP

Build Status

geophp.net

GeoPHP is a open-source native PHP library for doing geometry operations. It is written entirely in PHP and can therefore run on shared hosts. It can read and write a wide variety of formats: WKT (including EWKT), WKB (including EWKB), GeoJSON, KML, GPX, and GeoRSS. It works with all Simple-Feature geometries (Point, LineString, Polygon, GeometryCollection etc.) and can be used to get centroids, bounding-boxes, area, and a wide variety of other useful information.

geoPHP also helpfully wraps the GEOS php extension so that applications can get a transparent performance increase when GEOS is installed on the server. When GEOS is installed, geoPHP also becomes fully compliant with the OpenGISยฎ Implementation Standard for Geographic information. With GEOS you get the full-set of openGIS functions in PHP like Union, IsWithin, Touches etc. This means that applications get a useful "core-set" of geometry operations that work in all environments, and an "extended-set"of operations for environments that have GEOS installed.

See the 'getting started' section below for references and examples of everything that geoPHP can do.

This project is currently looking for co-maintainers. If you think you can help out, please send me a message. Forks are also welcome, please issue pull requests and I will merge them into the main branch.

Getting Started

Example usage

<?php
include_once('geoPHP.inc');

// Polygon WKT example
$polygon = geoPHP::load('POLYGON((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2))','wkt');
$area = $polygon->getArea();
$centroid = $polygon->getCentroid();
$centX = $centroid->getX();
$centY = $centroid->getY();

print "This polygon has an area of ".$area." and a centroid with X=".$centX." and Y=".$centY;

// MultiPoint json example
print "<br/>";
$json = 
'{
   "type": "MultiPoint",
   "coordinates": [
       [100.0, 0.0], [101.0, 1.0]
   ]
}';

$multipoint = geoPHP::load($json, 'json');
$multipoint_points = $multipoint->getComponents();
$first_wkt = $multipoint_points[0]->out('wkt');

print "This multipoint has ".$multipoint->numGeometries()." points. The first point has a wkt representation of ".$first_wkt;

=======

More Examples

The Well Known Text (WKT) and Well Known Binary (WKB) support is ideal for integrating with MySQL's or PostGIS's spatial capability. Once you have SELECTed your data with 'AsText('geo_field')' or 'AsBinary('geo_field')', you can put it straight into geoPHP (can be wkt or wkb, but must be the same as how you extracted it from your database):

$geom = geoPHP::load($dbRow,'wkt');

You can collect multiple geometries into one (note that you must use wkt for this):

$geom = geoPHP::load("GEOMETRYCOLLECTION(".$dbString1.",".$dbString2.")",'wkt');

Calling get components returns the sub-geometries within a geometry as an array.

$geom2 = geoPHP::load("GEOMETRYCOLLECTION(LINESTRING(1 1,5 1,5 5,1 5,1 1),LINESTRING(2 2,2 3,3 3,3 2,2 2))");
$geomComponents = $geom2->getComponents();    //an array of the two linestring geometries
$linestring1 = $geomComponents[0]->getComponents();	//an array of the first linestring's point geometries
$linestring2 = $geomComponents[1]->getComponents();
echo $linestring1[0]->x() . ", " . $linestring1[0]->y();    //outputs '1, 1'

An alternative is to use the asArray() method. Using the above geometry collection of two linestrings,

$geometryArray = $geom2->asArray();
echo $geometryArray[0][0][0] . ", " . $geometryArray[0][0][1];    //outputs '1, 1'

Clearly, more complex analysis is possible.

echo $geom2->envelope()->area();

Working with PostGIS

geoPHP, through it's EWKB adapter, has good integration with postGIS. Here's an example of reading and writing postGIS geometries

<?php
include_once('geoPHP.inc');
$host =     'localhost';
$database = 'phayes';
$table =    'test';
$column =   'geom';
$user =     'phayes';
$pass =     'supersecret';

$connection = pg_connect("host=$host dbname=$database user=$user password=$pass");

// Working with PostGIS and Extended-WKB
// ----------------------------

// Using asBinary and GeomFromWKB in PostGIS
$result = pg_fetch_all(pg_query($connection, "SELECT asBinary($column) as geom FROM $table"));
foreach ($result as $item) {
  $wkb = pg_unescape_bytea($item['geom']); // Make sure to unescape the hex blob
  $geom = geoPHP::load($wkb, 'ewkb'); // We now a full geoPHP Geometry object
  
  // Let's insert it back into the database
  $insert_string = pg_escape_bytea($geom->out('ewkb'));
  pg_query($connection, "INSERT INTO $table ($column) values (GeomFromWKB('$insert_string'))");
}

// Using a direct SELECT and INSERTs in PostGIS without using wrapping functions
$result = pg_fetch_all(pg_query($connection, "SELECT $column as geom FROM $table"));
foreach ($result as $item) {
  $wkb = pack('H*',$item['geom']);   // Unpacking the hex blob
  $geom = geoPHP::load($wkb, 'ewkb'); // We now have a geoPHP Geometry
  
  // To insert directly into postGIS we need to unpack the WKB
  $unpacked = unpack('H*', $geom->out('ewkb'));
  $insert_string = $unpacked[1];
  pg_query($connection, "INSERT INTO $table ($column) values ('$insert_string')");
}

Credit

Maintainer: Patrick Hayes

Additional Contributors:

This library is open-source and dual-licensed under both the Modified BSD License and GPLv2. Either license may be used at your option.

More Repositories

1

freeport

Get a free and open tcp port that is ready to use
Go
348
star
2

sidefuzz

Fuzzer to automatically find side-channel (timing) vulnerabilities
Rust
99
star
3

hookserve

HookServe is a small golang utility for receiving github webhooks.
Go
64
star
4

permbits

Easy file permissions for golang. Easily get and set file permission bits.
Go
51
star
5

ecies-ed25519

ECIES on Twisted Edwards Curve25519 using AES-GCM and HKDF-SHA256
Rust
29
star
6

tallystick

A rust library for tallying votes
Rust
29
star
7

deadci

Dead Easy Continuous Integration and Testing
Go
21
star
8

polars_gdal

Read GDAL compatible file formats into polars / geopolars
Rust
17
star
9

rsa-fdh

RSA-FDH blind signature scheme using RSA and a Full Domain Hash
Rust
8
star
10

geojump

Drupal 7: Provides an openlayers-behavior that allows a user to type an address and go to that location the map
JavaScript
7
star
11

vuetify-survey

Build simple questionnaires and surveys declaratively
JavaScript
6
star
12

sidefuzz-targets

Fuzzing targets for SideFuzz
Rust
6
star
13

errors

Better error handling for go
Go
6
star
14

geofield_postgis

Drupal 7: PostGIS backend for geofield module
PHP
3
star
15

cryptoid

Cryptography OIDs for golang - useful for juggling ASN.1 crypto data structures
Go
3
star
16

crawlbot

A simple, efficient, and flexible webcrawler / spider for go
Go
3
star
17

fdh-rs

Full Domain Hash library for rust
Rust
3
star
18

uncaptchalous

Drupal 7: Unobtrusive form spam filter
JavaScript
3
star
19

SaganSearch

Searching for artifical messages in pi
Rust
2
star
20

mgit

git multiplexer
Go
2
star
21

mysqlchecksize

A small utility for checking disk space used by mysql databases
Go
2
star
22

go-drupal

Interface with a Drupal site using golang, execute drush commands
PHP
2
star
23

benaloh-challenge

Benaloh Challenge (aka Interactive Device Challenge)
Rust
2
star
24

decryptpem

Decrypts encrypted PEM files and blocks. Provides (optional) TTY prompt for input for password.
Go
1
star
25

cryptocourse

Course work from Coursea Crytography course
Go
1
star
26

polars_geos

use GEOS geospatial function inside polars and geopolars
Rust
1
star
27

sagent

Generate a re-usable ssh-agent for ssh key forwarding
1
star
28

fimble

Simple command-line File Integrity Monitoring
Rust
1
star
29

wonderdraft_assets

A collection of assets for wonderdraft (cartography)
1
star
30

triggerfail

fail a command with an exit status of 1 if a trigger string appears in it's output
Go
1
star
31

cloudflare2

Fork of Drupal's CloudFlare module
PHP
1
star
32

elasticentityquery

Drupal module provides an elasticsearch EntityQuery backend
PHP
1
star