Giter Site home page Giter Site logo

geophpwithfeatures's Introduction

geophp.net

The GeoPHP project has stated that it intends to restrict their project to pure geometry data. In other words, no features data such as what you might find in a GPX file.

GeoPHPwithFeatures is a fork of the popular GeoPHP project that adds features metadata to geometries.

The primary purpose of this fork is to add support for GPX file features data and convert that to and from GeoJSON making it easier to handle the kinds of features data you might find in a GPS generated GPX file and render that on a LeafLet map. I needed this capability for the next version of the maps on my site: miles-by-motorcycle.com

The other adaptors (KML, etc) simply ignore the metadata as of this writing.

GPX files with extension metadata can be read and written. They can also be converted to the GeoJSON format where geometries with metadata are converted to GeoJSON Features objects with a properties property that includes a verbatim copy of the GPX meta data extensions. The GeoJSON spec has no opinions on how the properties property is formatted so I've chosen to simply mimic the metadata structure found in GPX files keeping all the extension names the same (e.g. Garmin's gpxx:RouteExtension, gpxx:WaypointExtension, et al.)

Please note:

  • A properties property is included at the top level FeaturesCollection, in violation of the standard.
  • A metadata object is included in the LineString point type to represent elevation, time, and other metadata (from the GPX file) also in violation of the standard.
  • GPX trkseg's in a given trk are coalesced into a single trkseg.

For an example of a Garmin Zumo 550 generated GPX file converted to GeoJSON see the tests/input/gpx and tests/input/json directories.

A simple command line tool, bin/geo_convert.php, is included to convert files manually. You may find the xmllint and json_pp useful for formatting the output so that it is human readable. For an example try:

$ cd geoPHPwithFeatures/bin $ php geo_convert.php --input-path=../test/input/gpx/2_test.gpx --input-format=gpx --output-path=test.json --output-format=geojson

For documentation please refer to the GeoPHP project.

The only public changes are the addition of an additional "metadata" parameter to all geometry constructors in addition to setMetaData() and getMetaData(). In all cases, they simply take an arbitrary associative array. Everything else should be backwards compatible with the main GeoPHP project.

Packages:

libxerces-c-samples - needed to validate GPX files. See http://www.topografix.com/gpx_validation.asp (SAXCount)

Original GeoPHP README

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

GeoPHPwithFeatures Maintainer: Yermo Lamers https://github.com/yermo

GeoPHP 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.

geophpwithfeatures's People

Contributors

acorncom avatar amenk avatar andrewkett avatar andrewtch avatar danoh avatar dasjo avatar dbrkv avatar drupol avatar dstelljes avatar dtarc avatar ejh avatar fanquake avatar gregseb avatar lolandese avatar marcjansen avatar mishal avatar mprins avatar phayes avatar ramunasd avatar theodoreb avatar tillz avatar yermo avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

geophpwithfeatures's Issues

Store a complete Feature entry as a route waypoint

Currently, an abbreviated properties object is included as the fourth position in the route coordinates array.

{
   "features" : [
      {
         "geometry" : {
            "type" : "LineString",
            "coordinates" : [
               [
                  -77.463442,
                  39.526728,
                  null,
                  {
                     "extensions" : {
                        "gpxx_routepointextension" : [
                           [
                              "-77.463442",
                              "39.526642"
                           ],
                           [
                              "-77.463056",
                              "39.526620"
                           ],

This is proving to be inconvenient.

Modify this to store a complete Point Feature in this position to mirror a waypoint entry. The only difference between a standalone waypoint marker entry and this copy will be the presence of the gpxx_routepointextension coordinate array.

e.g.:

               "geometry" : {
                  "coordinates" : [
                     [
                        -83.92005443573,
                        35.466550939862,
                        null,
                        {
                           "name" : "Unnamed",
                           "properties" : {
                              "cmt" : "This is a comment about the Deal's Gap Start Point",
                              "name" : "Deals Gap Start" 
                              "link" : [
                                 {
                                    "href" : "http://dealsgap.com "
                                 }
                              ],
                              "desc" : "This is a test of the deals gap start waypoint",
                              "extensions" : {
                                 "gpxx_routepointextension" : [
                                    [
                                       -83.920013,
                                       35.466556
                                    ],
                                    [
                                       -83.920028,
                                       35.467197
                                    ],

Latest commit breaks GPX Export

The order of elements in GPX export is once again incorrect.

Fix it and add a test to make sure the GPX files generated validate.

Conversion of a single geometry from GPX to JSON and back again loses data.

Converting the following GPX file to geojson:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
  <metadata>
    <link href="http://www.garmin.com">
      <text>Garmin International</text>
    </link>
    <time>2013-05-27T17:23:57Z</time>
  </metadata>
  <wpt lat="35.466436" lon="-83.920083">
    <ele>573.07</ele>
    <name>Deals Gap</name>
    <sym>Waypoint</sym>
  </wpt>
</gpx>

becomes:

{
   "properties" : {
      "link" : [
         {
            "text" : "Garmin International",
            "href" : "http://www.garmin.com"
         }
      ],
      "time" : "2013-05-27T17:23:57Z"
   },
   "type" : "FeatureCollection",
   "features" : [
      {
         "properties" : {
            "name" : "Deals Gap",
            "sym" : "Waypoint",
            "elevation" : "573.07"
         },
         "geometry" : {
            "coordinates" : [
               -83.920083,
               35.466436,
               573.07,
               {
                  "elevation" : "573.07"
               }
            ],
            "type" : "Point"
         },
         "type" : "Feature"
      }
   ]
}  

Converting it back to GPX yields:

<?xml version="1.0"?>
  <metadata>
    <time>2013-05-27T17:23:57Z</time>
  </metadata>
  <wpt lat="35.466436" lon="-83.920083">
    <time>2013-05-27T17:23:57Z</time>
  </wpt>
</gpx>  

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.