1
0
Fork 0
forked from lino/radar-wp

Initial import.

This commit is contained in:
ekes 2015-02-24 16:25:12 +01:00
commit 86383280c9
428 changed files with 68738 additions and 0 deletions

1
vendor/phayes/geophp/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
/vendor

27
vendor/phayes/geophp/.travis.yml vendored Normal file
View file

@ -0,0 +1,27 @@
# docs available at http://docs.travis-ci.com/user/languages/php/
# example available at https://github.com/travis-ci/travis-ci-php-example
language: php
before_script:
- composer self-update
install:
- composer install
# TODO Install geos library -- as a matrix test
# TODO optionally set up a postgis database for testing
script: cd tests && phpunit --verbose --colors --stderr tests
# run tests on the following versions
php:
- 5.6
- 5.5
- 5.4
- 5.3
- hhvm
matrix:
fast_finish: false
allow_failures:
# php 5.3 does not support random file list as an argument to scandir
- php: 5.3

370
vendor/phayes/geophp/LICENSE vendored Normal file
View file

@ -0,0 +1,370 @@
Copyright (c) 2011, Patrick Hayes and contributors
This program is dual-licensed under both the GPL version 2 (or later) and
Modified BSD License. Either license may be used at your option.
------------------------------------------------------------------------------
Modified BSD License
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of the contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

150
vendor/phayes/geophp/README.md vendored Normal file
View file

@ -0,0 +1,150 @@
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, 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
-----------------------
* The lastest stable version can always be downloaded at: <https://github.com/downloads/phayes/geoPHP/geoPHP.tar.gz>
* Read the API Reference at: <https://github.com/phayes/geoPHP/wiki/API-Reference>
* Examples
* Using geoPHP as a GIS format converter: <http://github.com/phayes/geoPHP/wiki/Example-format-converter>
* Other Interesting Links:
* Learn about GEOS integration at: <https://github.com/phayes/geoPHP/wiki/GEOS>
Example usage
-------------------------------------------------
```php
<?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
<?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:
* GeoMemes Research (<http://www.geomemes.com>)
* HighWire Press (<http://www.highwire.org>) and GeoScienceWorld (<http://www.geoscienceworld.org>)
* Arnaud Renevier (gisconverter.php) <https://github.com/arenevier/gisconverter.php>
* Dave Tarc <https://github.com/dtarc>
* Elliott Hunston (documentation) <https://github.com/ejh>
This library is open-source and dual-licensed under both the Modified BSD License and GPLv2. Either license may be used at your option.

18
vendor/phayes/geophp/composer.json vendored Normal file
View file

@ -0,0 +1,18 @@
{
"name": "phayes/geophp",
"license": "GPL-2 or New-BSD",
"type": "library",
"description": "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, 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.",
"homepage": "https://github.com/phayes/geoPHP",
"autoload": {
"classmap": ["geoPHP.inc"]
},
"authors":[
{
"name":"Patrick Hayes"
}
],
"require-dev": {
"phpunit/phpunit": "4.1.*"
}
}

735
vendor/phayes/geophp/doc/api.html vendored Normal file
View file

@ -0,0 +1,735 @@
<div id="wiki-wrapper" class="page">
<div id="head">
<h1 class="instapaper_title">API Reference</h1>
<ul class="wiki-actions readability-extra">
<li class="gollum-minibutton">
<a href="/phayes/geoPHP/wiki/API-Reference/_history"
class="minibutton bigger action-page-history">
<span>Page History</span>
</a>
</li>
</ul>
</div>
<div id="wiki-content">
<div class="wrap">
<div id="wiki-body" class="gollum-mediawiki-content instapaper_body">
<div class="markdown-body">
<table class="toc" summary="Contents">
<tr>
<td>
<div>Table of Contents</div>
<ul>
<ul>
<li>
<a href="#wiki-geoPHP_static_class" rel="nofollow">geoPHP static class</a>
<ul>
<li>
<a href="#wiki-Example" rel="nofollow">Example</a>
</li>
<li>
<a href="#wiki-Static_Methods" rel="nofollow">Static Methods</a>
</li>
</ul>
</li>
<li>
<a href="#wiki-Adapters" rel="nofollow">Adapters</a>
<ul>
<li>
<a href="#wiki-Class_Hierarchy" rel="nofollow">Class Hierarchy</a>
</li>
<li>
<a href="#wiki-Example-2" rel="nofollow">Example</a>
</li>
<li>
<a href="#wiki-Methods" rel="nofollow">Methods</a>
</li>
</ul>
</li>
<li>
<a href="#wiki-Geometries" rel="nofollow">Geometries</a>
<ul>
<li>
<a href="#wiki-Class_Hierarchy-2" rel="nofollow">Class Hierarchy</a>
</li>
<li>
<a href="#wiki-Example-3" rel="nofollow">Example</a>
</li>
<li>
<a href="#wiki-Methods-2" rel="nofollow">Methods</a>
</li>
</ul>
</li>
</ul>
</ul>
</td>
</tr>
</table>
<h2>
<span class="mw-headline">
<a name="wiki-geoPHP_static_class" rel="nofollow">geoPHP static class</a>
</span>
</h2>
<p>geoPHP provides a static class that contains useful utility functions. All methods must
be called statically. </p>
<h3>
<span class="mw-headline">
<a name="wiki-Example" rel="nofollow">Example</a>
</span>
</h3>
<pre>$geometry = geoPHP::load('MULTILINESTRING((10 10,20 20,10 40))','wkt');</pre>
<pre>$reduced_geometry = geoPHP::geometryReduce($geometry);</pre>
<h3>
<span class="mw-headline">
<a name="wiki-Static_Methods" rel="nofollow">Static Methods</a>
</span>
</h3>
<table>
<tr>
<td>
<b>Method</b>
</td>
<td>
<b>Description</b>
</td>
<td>
<b>Returns</b>
</td>
</tr>
<tr>
<td> version </td>
<td> Provides the current geoPHP version. Useful if you need to check compatablity </td>
<td> Numeric String </td>
</tr>
<tr>
<td> load </td>
<td> Load from an adapter format (like wkt) into a geometry. The first argument is the
data, the second one is the format of the data
('wkt','wkb','json','kml','gpx','google_geocode'). All additional arguments are
passed along to the read method of the relevant adapte </td>
<td> Geometry </td>
</tr>
<tr>
<td> getAdapterMap </td>
<td> Get a list of adapters as an array keyed by the value that should be passed to
geoPHP::load </td>
<td> Array </td>
</tr>
<tr>
<td> geometryList </td>
<td> List all geometry types </td>
<td> Array </td>
</tr>
<tr>
<td> geosToGeometry </td>
<td> Given a GEOSGeometry, get a geoPHP geometry </td>
<td> Geometry </td>
</tr>
<tr>
<td> geometryReduce </td>
<td> Reduce a geometry, or an array of geometries, into their \'lowest\' available
common geometry. For example a GeometryCollection of only points will become a
MultiPoint, while a multi-point containing a single point will return a point. An
array of geometries can be passed and they will be compiled into a single geometry. </td>
<td> Geometry </td>
</tr>
<tr>
<td> geosInstalled </td>
<td> Check if the GEOS php extension is installed and working </td>
<td> Boolean </td>
</tr>
</table>
<h2>
<span class="mw-headline">
<a name="wiki-Adapters" rel="nofollow">Adapters</a>
</span>
</h2>
<p>Adapters are responsible for getting data in and out of geoPHP Geometries. Generally
you will use an adapter to load data into a geoPHP geometry, do various manipulations on
the geometry, then use another adapter to write it out to another (or the same) format.
You can also use adapters by themselves to simply do conversion from one format to
another (See <a class="internal present"
href="/phayes/geoPHP/wiki/Example-format-converter" rel="nofollow"
>example-format-converter</a> for an example of this). Adapters should be instantiated
and not called statically. </p>
<h3>
<span class="mw-headline">
<a name="wiki-Class_Hierarchy" rel="nofollow">Class Hierarchy</a>
</span>
</h3>
<ul>
<li>GeoAdapter Abtract Class<ul>
<li>WKT Enables reading and writing WKT (Well Known Text)</li>
<li>WKB Enables reading and writing WKB (Well Known Binary). This is very fast.</li>
<li>GeoJSON Enables reading and writing GeoJSON</li>
<li>KML Enables reading and writing KML (Google Earth)</li>
<li>GoogleGeocode Enables geocoding and reverse-geocoding via google geocoding
API</li>
<li>GPX Enables reading and writing GPX (from handheld GPS devices)</li>
<li>GeoRSS Enables reading and writing of GeoRSS</li>
</ul>
</li>
</ul>
<h3>
<span class="mw-headline">
<a name="wiki-Example-2" rel="nofollow">Example</a>
</span>
</h3>
<pre>$wkb_reader = new WKB();</pre>
<pre>$geometry = $wkb_reader-&gt;read('0101000000000000000000f03f000000000000f03f',TRUE);</pre>
<pre>$wkt_writer = new wkt();</pre>
<pre>$wkt = $wkt_writer-&gt;write($geometry);</pre>
<h3>
<span class="mw-headline">
<a name="wiki-Methods" rel="nofollow">Methods</a>
</span>
</h3>
<table>
<tr>
<td>
<b>Method</b>
</td>
<td>
<b>Description</b>
</td>
<td>
<b>Returns</b>
</td>
</tr>
<tr>
<td> read </td>
<td> Read in input (generally a string) and return a Geometry </td>
<td> Geometry </td>
</tr>
<tr>
<td> write </td>
<td> Write out the given geometry into the adapter formater </td>
<td> String </td>
</tr>
</table>
<h2>
<span class="mw-headline">
<a name="wiki-Geometries" rel="nofollow">Geometries</a>
</span>
</h2>
<p>Geometries form the heart of the geoPHP library. Once you have loaded your data into a
Geometry object, you have access to all the various methods detailed below for doing
conversions, transformations, and operations. While generally you would use an adapter
to get a Geometry object, they can also be built by hand. See the constructor methods in
the classes to see how to do this. GEOS-php extension needs to be installed in order to
use some of the advanced methods (detailed below). </p>
<h3>
<span class="mw-headline">
<a name="wiki-Class_Hierarchy-2" rel="nofollow">Class Hierarchy</a>
</span>
</h3>
<ul>
<li>Geometry<ul>
<li>Point</li>
<li>Collection<ul>
<li>LineString</li>
<li>Polygon</li>
<li>MultiLineString</li>
<li>MultiPoint</li>
<li>MultiPolygon</li>
<li>GeometryCollection</li>
</ul>
</li>
</ul>
</li>
</ul>
<h3>
<span class="mw-headline">
<a name="wiki-Example-3" rel="nofollow">Example</a>
</span>
</h3>
<pre>$poly1 = $geoPHP::load('POLYGON((30 10,10 20,20 40,40 40,30 10))','wkt');</pre>
<pre>$poly2 = $geoPHP::load('POLYGON((35 10,10 20,15 40,45 45,35 10),(20 30, 35 35, 30 20, 20 30))','wkt');</pre>
<pre>$combined_poly = $poly1-&gt;union($poly2);</pre>
<pre>$kml = $combined_poly-&gt;out('kml');</pre>
<h3>
<span class="mw-headline">
<a name="wiki-Methods-2" rel="nofollow">Methods</a>
</span>
</h3>
<p>
<b>Common Methods</b>
</p>
<table>
<tr>
<td>
<b>Method</b>
</td>
<td>
<b>Description</b>
</td>
<td>
<b>Returns</b>
</td>
</tr>
<tr>
<td> out </td>
<td> Outputs the geometry into the specified adapter format. Available formats are
<i>wkt</i>, <i>wkb</i>, <i>json</i>, <i>kml</i>, <i>gpx</i>, <i>google_geocode</i>
</td>
<td> String </td>
</tr>
<tr>
<td> area </td>
<td> The area of this Polygon (or GeometryCollection), as measured in the spatial
reference system of the geometry </td>
<td> Float </td>
</tr>
<tr>
<td> boundary </td>
<td> Returns the closure of the combinatorial boundary of this geometric object. </td>
<td> LinearRing </td>
</tr>
<tr>
<td> envelope </td>
<td> The minimum bounding box for this Geometry, returned as a Geometry. </td>
<td> Polygon </td>
</tr>
<tr>
<td> getBBox </td>
<td> The minimum bounding box for this Geometry, returned as an array. Also see
envelope() </td>
<td> Array </td>
</tr>
<tr>
<td> centroid </td>
<td> The mathematical centroid for this geometry as a Point. For polygons, the result
is not guaranteed to be interior. </td>
<td> Point </td>
</tr>
<tr>
<td> length </td>
<td> The length of this Curve in its associated spatial reference. </td>
<td> Float </td>
</tr>
<tr>
<td> y </td>
<td> The y-coordinate value for this Point. </td>
<td> Float </td>
</tr>
<tr>
<td> x </td>
<td> The x-coordinate value for this Point. </td>
<td> Float </td>
</tr>
<tr>
<td> numGeometries </td>
<td> The number of component geometries in this collection </td>
<td> Integer </td>
</tr>
<tr>
<td> geometryN </td>
<td> Returns the geometry N in this collection. Note that the index starts at 1. </td>
<td> Geometry </td>
</tr>
<tr>
<td> startPoint </td>
<td> The start Point of this LineString </td>
<td> Point </td>
</tr>
<tr>
<td> endPoint </td>
<td> The end Point of this LineString </td>
<td> Point </td>
</tr>
<tr>
<td> isRing </td>
<td> Returns 1 (TRUE) if this Curve is closed() and this Curve isSimple(). </td>
<td> Boolean </td>
</tr>
<tr>
<td> isClosed </td>
<td> Returns 1 (TRUE) if this Curve is closed. StartPoint() == EndPoint(). </td>
<td> Boolean </td>
</tr>
<tr>
<td> getComponents </td>
<td> Get all sub-geometry components of the geometry </td>
<td> Array of geometries </td>
</tr>
<tr>
<td> numPoints </td>
<td> The number of Points in this LineString </td>
<td> Integer </td>
</tr>
<tr>
<td> pointN </td>
<td> Returns the specified Point N in this LineString. Note that the index starts at
1. </td>
<td> Point </td>
</tr>
<tr>
<td> exteriorRing </td>
<td> Returns the exterior ring of this Polygon. </td>
<td> LineString </td>
</tr>
<tr>
<td> numInteriorRings </td>
<td> Returns the number of interior rings in this Polygon. </td>
<td> Integer </td>
</tr>
<tr>
<td> interiorRingN </td>
<td> Returns the Nth interior ring for this Polygon as a LineString. Note that the
index starts at 1. </td>
<td> LineString </td>
</tr>
<tr>
<td> dimension </td>
<td> The inherent dimension of this geometric object. In non-homogeneous collections,
this will return the largest topological dimension of the contained objects. </td>
<td> Integer </td>
</tr>
<tr>
<td> geometryType </td>
<td> Returns the name of the instantiable subtype of Geometry of which this geometric
object is an instantiable member. The name of the subtype of Geometry is returned as
a string. </td>
<td> String </td>
</tr>
<tr>
<td> SRID </td>
<td> Returns the Spatial Reference System ID for this geometric object. </td>
<td> integer </td>
</tr>
<tr>
<td> setSRID </td>
<td> Set the Spatial Reference System ID for this geometric object. </td>
<td> NULL </td>
</tr>
<tr>
<td> asArray </td>
<td> Get the given geometry as an array of components (recursive) </td>
<td> Array </td>
</tr>
<tr>
<td> getGeoInterface </td>
<td> Get the geometryType and Coordinates as an array </td>
<td> Array </td>
</tr>
</table>
<p>
<b>Aliases</b>
</p>
<table>
<tr>
<td>
<b>Method</b>
</td>
<td>
<b>Description</b>
</td>
<td>
<b>Returns</b>
</td>
</tr>
<tr>
<td> getCentroid </td>
<td> Alias for centroid() </td>
<td> Point </td>
</tr>
<tr>
<td> getArea </td>
<td> Alias for area() </td>
<td> Float </td>
</tr>
<tr>
<td> getX </td>
<td> Alias for x() </td>
<td> Float </td>
</tr>
<tr>
<td> getY </td>
<td> Alias for y() </td>
<td> Float </td>
</tr>
<tr>
<td> getGeos </td>
<td> Alias for geos() </td>
<td> GEOSGeometry </td>
</tr>
<tr>
<td> getGeomType </td>
<td> Alias for geometryType() </td>
<td> String </td>
</tr>
<tr>
<td> getSRID </td>
<td> Alias for SRID() </td>
<td> Integer </td>
</tr>
<tr>
<td> asText </td>
<td> Alias for <i>$this-&gt;out('wkt')</i>
</td>
<td> String </td>
</tr>
<tr>
<td> asBinary </td>
<td> Alias for <i>$this-&gt;out('wkb')</i>
</td>
<td> String </td>
</tr>
</table>
<p>
<b>Advanced Methods</b>
</p>
<p>The <a class="internal present" href="/phayes/geoPHP/wiki/GEOS" rel="nofollow">GEOS-php
extension</a> needs to be installed for these functions to be available </p>
<table>
<tr>
<td>
<b>Method</b>
</td>
<td>
<b>Description</b>
</td>
<td>
<b>Returns</b>
</td>
</tr>
<tr>
<td> geos </td>
<td> Return a GEOSGeometry object representing this geometry </td>
<td> GEOSGeometry </td>
</tr>
<tr>
<td> setGeos </td>
<td> Set a GEOSGeometry object representing this geometry </td>
<td> NULL </td>
</tr>
<tr>
<td> pointOnSurface </td>
<td> A Point guaranteed to be within a polygon </td>
<td> Point </td>
</tr>
<tr>
<td> equals </td>
<td> Returns 1 (TRUE) if this geometry is “spatially equal” to another Geometry </td>
<td> Boolean </td>
</tr>
<tr>
<td> equalsExact </td>
<td> Returns 1 (TRUE) if this gemometric object is exactly the same as another object,
including the ordering of component parts </td>
<td> Boolean </td>
</tr>
<tr>
<td> relate </td>
<td> Returns 1 (TRUE) if this geometric object is spatially related to anotherGeometry
by testing for intersections between the interior, boundary and exterior of the two
geometric objects as specified by the values in the intersectionPatternMatrix. This
returns FALSE if all the tested intersections are empty except exterior (this)
intersect exterior (another). </td>
<td> Boolean </td>
</tr>
<tr>
<td> checkValidity </td>
<td> Boolean </td>
</tr>
<tr>
<td> isSimple </td>
<td> Returns 1 (TRUE) if this geometry does not pass through the same point in space
more than once </td>
<td> Boolean </td>
</tr>
<tr>
<td> project </td>
<td> Project the geometry from from one SRID to another </td>
<td> Geometry </td>
</tr>
<tr>
<td> buffer </td>
<td> Returns a geometric object that represents all Points whose distance from this
geometric object is less than or equal to distance. Calculations are in the spatial
reference system of this geometric object. Because of the limitations of linear
interpolation, there will often be some relatively small error in this distance, but
it should be near the resolution of the coordinates used. </td>
<td> Geometry </td>
</tr>
<tr>
<td> intersection </td>
<td> Returns a geometric object that represents the Point set intersection of this
geometric object with anotherGeometry. See <a
href="http://en.wikipedia.org/wiki/Intersection_(set_theory)" rel="nofollow"
>http://en.wikipedia.org/wiki/Intersection_(set_theory)</a>
</td>
<td> Geometry </td>
</tr>
<tr>
<td> convexHull </td>
<td> Returns a geometric object that represents the convex hull of this geometric
object. See <a href="http://en.wikipedia.org/wiki/Convex_hull" rel="nofollow"
>http://en.wikipedia.org/wiki/Convex_hull</a>
</td>
<td> Geometry </td>
</tr>
<tr>
<td> difference </td>
<td> Returns a geometric object that represents the Point set difference of this
geometric object with anotherGeometry. </td>
<td> Geometry </td>
</tr>
<tr>
<td> symDifference </td>
<td> Returns a geometric object that represents the Point set symmetric difference of
this geometric object with another Geometry. See <a
href="http://en.wikipedia.org/wiki/Symmetric_difference" rel="nofollow"
>http://en.wikipedia.org/wiki/Symmetric_difference</a>
</td>
<td> Geometry </td>
</tr>
<tr>
<td> union </td>
<td> Returns a geometric object that represents the Point set union of this geometric
object with anotherGeometry. See <a
href="http://en.wikipedia.org/wiki/Union_(set_theory)" rel="nofollow"
>http://en.wikipedia.org/wiki/Union_(set_theory)</a>
</td>
<td> Geometry </td>
</tr>
<tr>
<td> simplify </td>
<td> Simplify the geometry </td>
<td> Geometry </td>
</tr>
<tr>
<td> disjoint </td>
<td> Returns 1 (TRUE) if this geometric object is “spatially disjoint” from another
Geometry. </td>
<td> Boolean </td>
</tr>
<tr>
<td> touches </td>
<td> Returns 1 (TRUE) if this geometric object “spatially touches” another Geometry. </td>
<td> Boolean </td>
</tr>
<tr>
<td> intersects </td>
<td> Returns 1 (TRUE) if this geometric object “spatially intersects” another
Geometry. </td>
<td> Boolean </td>
</tr>
<tr>
<td> crosses </td>
<td> Returns 1 (TRUE) if this geometric object “spatially crosses? another Geometry. </td>
<td> Boolean </td>
</tr>
<tr>
<td> within </td>
<td> Returns 1 (TRUE) if this geometric object is “spatially within” another Geometry. </td>
<td> Boolean </td>
</tr>
<tr>
<td> contains </td>
<td> Returns 1 (TRUE) if this geometric object “spatially contains” another Geometry. </td>
<td> Boolean </td>
</tr>
<tr>
<td> overlaps </td>
<td> Returns 1 (TRUE) if this geometric object “spatially overlaps” another Geometry. </td>
<td> Boolean </td>
</tr>
<tr>
<td> covers </td>
<td> Alias for contains() </td>
<td> Boolean </td>
</tr>
<tr>
<td> coveredBy </td>
<td> Alias for within() </td>
<td> Boolean </td>
</tr>
<tr>
<td> distance </td>
<td> Returns the shortest distance between any two Points in the two geometric objects
as calculated in the spatial reference system of this geometric object. Because the
geometries are closed, it is possible to find a point on each geometric object
involved, such that the distance between these 2 points is the returned distance
between their geometric objects. </td>
<td> Float </td>
</tr>
<tr>
<td> hausdorffDistance </td>
<td> See <a href="http://en.wikipedia.org/wiki/Hausdorff_distance" rel="nofollow"
>http://en.wikipedia.org/wiki/Hausdorff_distance</a>
</td>
<td> Float </td>
</tr>
</table>
<p>
<b>Placeholders</b>
</p>
<p>These methods are part of the specification, but are not really supported by geoPHP. </p>
<table>
<tr>
<td>
<b>Method</b>
</td>
<td>
<b>Description</b>
</td>
<td>
<b>Returns</b>
</td>
</tr>
<tr>
<td> hasZ </td>
<td> returns FALSE. geoPHP does not support Z values at the moment. </td>
<td> Boolean </td>
</tr>
<tr>
<td> is3D </td>
<td> returns FALSE. geoPHP does not support 3D geometries at the moment. </td>
<td> Boolean </td>
</tr>
<tr>
<td> isMeasured </td>
<td> returns FALSE. geoPHP does not yet support M values </td>
<td> Boolean </td>
</tr>
<tr>
<td> isEmpty </td>
<td> returns FALSE. geoPHP does not yet support empty geometries </td>
<td> Boolean </td>
</tr>
<tr>
<td> coordinateDimension </td>
<td> returns 2. geoPHP only supports 2-dimentional space </td>
<td> Integer </td>
</tr>
<tr>
<td> z </td>
<td> returns NULL. geoPHP does not support Z values at the moment </td>
<td> NULL </td>
</tr>
<tr>
<td> m </td>
<td> returns NULL. geoPHP does not support M values </td>
<td> NULL </td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>

301
vendor/phayes/geophp/geoPHP.inc vendored Normal file
View file

@ -0,0 +1,301 @@
<?php
/*
* (c) Patrick Hayes
*
* This code is open-source and licenced under the Modified BSD License.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
// Adapters
include_once("lib/adapters/GeoAdapter.class.php"); // Abtract class
include_once("lib/adapters/GeoJSON.class.php");
include_once("lib/adapters/WKT.class.php");
include_once("lib/adapters/EWKT.class.php");
include_once("lib/adapters/WKB.class.php");
include_once("lib/adapters/EWKB.class.php");
include_once("lib/adapters/KML.class.php");
include_once("lib/adapters/GPX.class.php");
include_once("lib/adapters/GeoRSS.class.php");
include_once("lib/adapters/GoogleGeocode.class.php");
include_once("lib/adapters/GeoHash.class.php");
// Geometries
include_once("lib/geometry/Geometry.class.php"); // Abtract class
include_once("lib/geometry/Point.class.php");
include_once("lib/geometry/Collection.class.php"); // Abtract class
include_once("lib/geometry/LineString.class.php");
include_once("lib/geometry/MultiPoint.class.php");
include_once("lib/geometry/Polygon.class.php");
include_once("lib/geometry/MultiLineString.class.php");
include_once("lib/geometry/MultiPolygon.class.php");
include_once("lib/geometry/GeometryCollection.class.php");
class geoPHP
{
static function version() {
return '1.2';
}
// geoPHP::load($data, $type, $other_args);
// if $data is an array, all passed in values will be combined into a single geometry
static function load() {
$args = func_get_args();
$data = array_shift($args);
$type = array_shift($args);
$type_map = geoPHP::getAdapterMap();
// Auto-detect type if needed
if (!$type) {
// If the user is trying to load a Geometry from a Geometry... Just pass it back
if (is_object($data)) {
if ($data instanceOf Geometry) return $data;
}
$detected = geoPHP::detectFormat($data);
if (!$detected) {
return FALSE;
}
$format = explode(':', $detected);
$type = array_shift($format);
$args = $format;
}
$processor_type = $type_map[$type];
if (!$processor_type) {
throw new exception('geoPHP could not find an adapter of type '.htmlentities($type));
exit;
}
$processor = new $processor_type();
// Data is not an array, just pass it normally
if (!is_array($data)) {
$result = call_user_func_array(array($processor, "read"), array_merge(array($data), $args));
}
// Data is an array, combine all passed in items into a single geomtetry
else {
$geoms = array();
foreach ($data as $item) {
$geoms[] = call_user_func_array(array($processor, "read"), array_merge(array($item), $args));
}
$result = geoPHP::geometryReduce($geoms);
}
return $result;
}
static function getAdapterMap() {
return array (
'wkt' => 'WKT',
'ewkt' => 'EWKT',
'wkb' => 'WKB',
'ewkb' => 'EWKB',
'json' => 'GeoJSON',
'geojson' => 'GeoJSON',
'kml' => 'KML',
'gpx' => 'GPX',
'georss' => 'GeoRSS',
'google_geocode' => 'GoogleGeocode',
'geohash' => 'GeoHash',
);
}
static function geometryList() {
return array(
'point' => 'Point',
'linestring' => 'LineString',
'polygon' => 'Polygon',
'multipoint' => 'MultiPoint',
'multilinestring' => 'MultiLineString',
'multipolygon' => 'MultiPolygon',
'geometrycollection' => 'GeometryCollection',
);
}
static function geosInstalled($force = NULL) {
static $geos_installed = NULL;
if ($force !== NULL) $geos_installed = $force;
if ($geos_installed !== NULL) {
return $geos_installed;
}
$geos_installed = class_exists('GEOSGeometry');
return $geos_installed;
}
static function geosToGeometry($geos) {
if (!geoPHP::geosInstalled()) {
return NULL;
}
$wkb_writer = new GEOSWKBWriter();
$wkb = $wkb_writer->writeHEX($geos);
$geometry = geoPHP::load($wkb, 'wkb', TRUE);
if ($geometry) {
$geometry->setGeos($geos);
return $geometry;
}
}
// Reduce a geometry, or an array of geometries, into their 'lowest' available common geometry.
// For example a GeometryCollection of only points will become a MultiPoint
// A multi-point containing a single point will return a point.
// An array of geometries can be passed and they will be compiled into a single geometry
static function geometryReduce($geometry) {
// If it's an array of one, then just parse the one
if (is_array($geometry)) {
if (empty($geometry)) return FALSE;
if (count($geometry) == 1) return geoPHP::geometryReduce(array_shift($geometry));
}
// If the geometry cannot even theoretically be reduced more, then pass it back
if (gettype($geometry) == 'object') {
$passbacks = array('Point','LineString','Polygon');
if (in_array($geometry->geometryType(),$passbacks)) {
return $geometry;
}
}
// If it is a mutlti-geometry, check to see if it just has one member
// If it does, then pass the member, if not, then just pass back the geometry
if (gettype($geometry) == 'object') {
$simple_collections = array('MultiPoint','MultiLineString','MultiPolygon');
if (in_array(get_class($geometry),$passbacks)) {
$components = $geometry->getComponents();
if (count($components) == 1) {
return $components[0];
}
else {
return $geometry;
}
}
}
// So now we either have an array of geometries, a GeometryCollection, or an array of GeometryCollections
if (!is_array($geometry)) {
$geometry = array($geometry);
}
$geometries = array();
$geom_types = array();
$collections = array('MultiPoint','MultiLineString','MultiPolygon','GeometryCollection');
foreach ($geometry as $item) {
if ($item) {
if (in_array(get_class($item), $collections)) {
foreach ($item->getComponents() as $component) {
$geometries[] = $component;
$geom_types[] = $component->geometryType();
}
}
else {
$geometries[] = $item;
$geom_types[] = $item->geometryType();
}
}
}
$geom_types = array_unique($geom_types);
if (empty($geom_types)) {
return FALSE;
}
if (count($geom_types) == 1) {
if (count($geometries) == 1) {
return $geometries[0];
}
else {
$class = 'Multi'.$geom_types[0];
return new $class($geometries);
}
}
else {
return new GeometryCollection($geometries);
}
}
// Detect a format given a value. This function is meant to be SPEEDY.
// It could make a mistake in XML detection if you are mixing or using namespaces in weird ways (ie, KML inside an RSS feed)
static function detectFormat(&$input) {
$mem = fopen('php://memory', 'r+');
fwrite($mem, $input, 11); // Write 11 bytes - we can detect the vast majority of formats in the first 11 bytes
fseek($mem, 0);
$bytes = unpack("c*", fread($mem, 11));
// If bytes is empty, then we were passed empty input
if (empty($bytes)) return FALSE;
// First char is a tab, space or carriage-return. trim it and try again
if ($bytes[1] == 9 || $bytes[1] == 10 || $bytes[1] == 32) {
$ltinput = ltrim($input);
return geoPHP::detectFormat($ltinput);
}
// Detect WKB or EWKB -- first byte is 1 (little endian indicator)
if ($bytes[1] == 1) {
// If SRID byte is TRUE (1), it's EWKB
if ($bytes[5]) return 'ewkb';
else return 'wkb';
}
// Detect HEX encoded WKB or EWKB (PostGIS format) -- first byte is 48, second byte is 49 (hex '01' => first-byte = 1)
if ($bytes[1] == 48 && $bytes[2] == 49) {
// The shortest possible WKB string (LINESTRING EMPTY) is 18 hex-chars (9 encoded bytes) long
// This differentiates it from a geohash, which is always shorter than 18 characters.
if (strlen($input) >= 18) {
//@@TODO: Differentiate between EWKB and WKB -- check hex-char 10 or 11 (SRID bool indicator at encoded byte 5)
return 'ewkb:1';
}
}
// Detect GeoJSON - first char starts with {
if ($bytes[1] == 123) {
return 'json';
}
// Detect EWKT - first char is S
if ($bytes[1] == 83) {
return 'ewkt';
}
// Detect WKT - first char starts with P (80), L (76), M (77), or G (71)
$wkt_chars = array(80, 76, 77, 71);
if (in_array($bytes[1], $wkt_chars)) {
return 'wkt';
}
// Detect XML -- first char is <
if ($bytes[1] == 60) {
// grab the first 256 characters
$string = substr($input, 0, 256);
if (strpos($string, '<kml') !== FALSE) return 'kml';
if (strpos($string, '<coordinate') !== FALSE) return 'kml';
if (strpos($string, '<gpx') !== FALSE) return 'gpx';
if (strpos($string, '<georss') !== FALSE) return 'georss';
if (strpos($string, '<rss') !== FALSE) return 'georss';
if (strpos($string, '<feed') !== FALSE) return 'georss';
}
// We need an 8 byte string for geohash and unpacked WKB / WKT
fseek($mem, 0);
$string = trim(fread($mem, 8));
// Detect geohash - geohash ONLY contains lowercase chars and numerics
preg_match('/[a-z0-9]+/', $string, $matches);
if ($matches[0] == $string) {
return 'geohash';
}
// What do you get when you cross an elephant with a rhino?
// http://youtu.be/RCBn5J83Poc
return FALSE;
}
}

View file

@ -0,0 +1,96 @@
<?php
/**
* EWKB (Extended Well Known Binary) Adapter
*/
class EWKB extends WKB
{
/**
* Read WKB binary string into geometry objects
*
* @param string $wkb An Extended-WKB binary string
*
* @return Geometry
*/
public function read($wkb, $is_hex_string = FALSE) {
if ($is_hex_string) {
$wkb = pack('H*',$wkb);
}
// Open the wkb up in memory so we can examine the SRID
$mem = fopen('php://memory', 'r+');
fwrite($mem, $wkb);
fseek($mem, 0);
$base_info = unpack("corder/ctype/cz/cm/cs", fread($mem, 5));
if ($base_info['s']) {
$srid = current(unpack("Lsrid", fread($mem, 4)));
}
else {
$srid = NULL;
}
fclose($mem);
// Run the wkb through the normal WKB reader to get the geometry
$wkb_reader = new WKB();
$geom = $wkb_reader->read($wkb);
// If there is an SRID, add it to the geometry
if ($srid) {
$geom->setSRID($srid);
}
return $geom;
}
/**
* Serialize geometries into an EWKB binary string.
*
* @param Geometry $geometry
*
* @return string The Extended-WKB binary string representation of the input geometries
*/
public function write(Geometry $geometry, $write_as_hex = FALSE) {
// We always write into NDR (little endian)
$wkb = pack('c',1);
switch ($geometry->getGeomType()) {
case 'Point';
$wkb .= pack('L',1);
$wkb .= $this->writePoint($geometry);
break;
case 'LineString';
$wkb .= pack('L',2);
$wkb .= $this->writeLineString($geometry);
break;
case 'Polygon';
$wkb .= pack('L',3);
$wkb .= $this->writePolygon($geometry);
break;
case 'MultiPoint';
$wkb .= pack('L',4);
$wkb .= $this->writeMulti($geometry);
break;
case 'MultiLineString';
$wkb .= pack('L',5);
$wkb .= $this->writeMulti($geometry);
break;
case 'MultiPolygon';
$wkb .= pack('L',6);
$wkb .= $this->writeMulti($geometry);
break;
case 'GeometryCollection';
$wkb .= pack('L',7);
$wkb .= $this->writeMulti($geometry);
break;
}
if ($write_as_hex) {
$unpacked = unpack('H*',$wkb);
return $unpacked[1];
}
else {
return $wkb;
}
}
}

View file

@ -0,0 +1,27 @@
<?php
/**
* EWKT (Extended Well Known Text) Adapter
*/
class EWKT extends WKT
{
/**
* Serialize geometries into an EWKT string.
*
* @param Geometry $geometry
*
* @return string The Extended-WKT string representation of the input geometries
*/
public function write(Geometry $geometry) {
$srid = $geometry->SRID();
$wkt = '';
if ($srid) {
$wkt = 'SRID=' . $srid . ';';
$wkt .= $geometry->out('wkt');
return $wkt;
}
else {
return $geometry->out('wkt');
}
}
}

View file

@ -0,0 +1,180 @@
<?php
/*
* Copyright (c) Patrick Hayes
*
* This code is open-source and licenced under the Modified BSD License.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* PHP Geometry/GPX encoder/decoder
*/
class GPX extends GeoAdapter
{
private $namespace = FALSE;
private $nss = ''; // Name-space string. eg 'georss:'
/**
* Read GPX string into geometry objects
*
* @param string $gpx A GPX string
*
* @return Geometry|GeometryCollection
*/
public function read($gpx) {
return $this->geomFromText($gpx);
}
/**
* Serialize geometries into a GPX string.
*
* @param Geometry $geometry
*
* @return string The GPX string representation of the input geometries
*/
public function write(Geometry $geometry, $namespace = FALSE) {
if ($geometry->isEmpty()) return NULL;
if ($namespace) {
$this->namespace = $namespace;
$this->nss = $namespace.':';
}
return '<'.$this->nss.'gpx creator="geoPHP" version="1.0">'.$this->geometryToGPX($geometry).'</'.$this->nss.'gpx>';
}
public function geomFromText($text) {
// Change to lower-case and strip all CDATA
$text = strtolower($text);
$text = preg_replace('/<!\[cdata\[(.*?)\]\]>/s','',$text);
// Load into DOMDocument
$xmlobj = new DOMDocument();
@$xmlobj->loadXML($text);
if ($xmlobj === false) {
throw new Exception("Invalid GPX: ". $text);
}
$this->xmlobj = $xmlobj;
try {
$geom = $this->geomFromXML();
} catch(InvalidText $e) {
throw new Exception("Cannot Read Geometry From GPX: ". $text);
} catch(Exception $e) {
throw $e;
}
return $geom;
}
protected function geomFromXML() {
$geometries = array();
$geometries = array_merge($geometries, $this->parseWaypoints());
$geometries = array_merge($geometries, $this->parseTracks());
$geometries = array_merge($geometries, $this->parseRoutes());
if (empty($geometries)) {
throw new Exception("Invalid / Empty GPX");
}
return geoPHP::geometryReduce($geometries);
}
protected function childElements($xml, $nodename = '') {
$children = array();
foreach ($xml->childNodes as $child) {
if ($child->nodeName == $nodename) {
$children[] = $child;
}
}
return $children;
}
protected function parseWaypoints() {
$points = array();
$wpt_elements = $this->xmlobj->getElementsByTagName('wpt');
foreach ($wpt_elements as $wpt) {
$lat = $wpt->attributes->getNamedItem("lat")->nodeValue;
$lon = $wpt->attributes->getNamedItem("lon")->nodeValue;
$points[] = new Point($lon, $lat);
}
return $points;
}
protected function parseTracks() {
$lines = array();
$trk_elements = $this->xmlobj->getElementsByTagName('trk');
foreach ($trk_elements as $trk) {
$components = array();
foreach ($this->childElements($trk, 'trkseg') as $trkseg) {
foreach ($this->childElements($trkseg, 'trkpt') as $trkpt) {
$lat = $trkpt->attributes->getNamedItem("lat")->nodeValue;
$lon = $trkpt->attributes->getNamedItem("lon")->nodeValue;
$components[] = new Point($lon, $lat);
}
}
if ($components) {$lines[] = new LineString($components);}
}
return $lines;
}
protected function parseRoutes() {
$lines = array();
$rte_elements = $this->xmlobj->getElementsByTagName('rte');
foreach ($rte_elements as $rte) {
$components = array();
foreach ($this->childElements($rte, 'rtept') as $rtept) {
$lat = $rtept->attributes->getNamedItem("lat")->nodeValue;
$lon = $rtept->attributes->getNamedItem("lon")->nodeValue;
$components[] = new Point($lon, $lat);
}
$lines[] = new LineString($components);
}
return $lines;
}
protected function geometryToGPX($geom) {
$type = strtolower($geom->getGeomType());
switch ($type) {
case 'point':
return $this->pointToGPX($geom);
break;
case 'linestring':
return $this->linestringToGPX($geom);
break;
case 'polygon':
case 'multipoint':
case 'multilinestring':
case 'multipolygon':
case 'geometrycollection':
return $this->collectionToGPX($geom);
break;
}
}
private function pointToGPX($geom) {
return '<'.$this->nss.'wpt lat="'.$geom->getY().'" lon="'.$geom->getX().'" />';
}
private function linestringToGPX($geom) {
$gpx = '<'.$this->nss.'trk><'.$this->nss.'trkseg>';
foreach ($geom->getComponents() as $comp) {
$gpx .= '<'.$this->nss.'trkpt lat="'.$comp->getY().'" lon="'.$comp->getX().'" />';
}
$gpx .= '</'.$this->nss.'trkseg></'.$this->nss.'trk>';
return $gpx;
}
public function collectionToGPX($geom) {
$gpx = '';
$components = $geom->getComponents();
foreach ($geom->getComponents() as $comp) {
$gpx .= $this->geometryToGPX($comp);
}
return $gpx;
}
}

View file

@ -0,0 +1,31 @@
<?php
/*
* (c) Patrick Hayes 2011
*
* This code is open-source and licenced under the Modified BSD License.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* GeoAdapter : abstract class which represents an adapter
* for reading and writing to and from Geomtry objects
*
*/
abstract class GeoAdapter
{
/**
* Read input and return a Geomtry or GeometryCollection
*
* @return Geometry|GeometryCollection
*/
abstract public function read($input);
/**
* Write out a Geomtry or GeometryCollection in the adapter's format
*
* @return mixed
*/
abstract public function write(Geometry $geometry);
}

View file

@ -0,0 +1,249 @@
<?php
/**
* PHP Geometry GeoHash encoder/decoder.
*
* @author prinsmc
* @see http://en.wikipedia.org/wiki/Geohash
*
*/
class GeoHash extends GeoAdapter{
/**
* base32 encoding character map.
*/
private $table = "0123456789bcdefghjkmnpqrstuvwxyz";
/**
* array of neighbouring hash character maps.
*/
private $neighbours = array (
// north
'top' => array (
'even' => 'p0r21436x8zb9dcf5h7kjnmqesgutwvy',
'odd' => 'bc01fg45238967deuvhjyznpkmstqrwx'
),
// east
'right' => array (
'even' => 'bc01fg45238967deuvhjyznpkmstqrwx',
'odd' => 'p0r21436x8zb9dcf5h7kjnmqesgutwvy'
),
// west
'left' => array (
'even' => '238967debc01fg45kmstqrwxuvhjyznp',
'odd' => '14365h7k9dcfesgujnmqp0r2twvyx8zb'
),
// south
'bottom' => array (
'even' => '14365h7k9dcfesgujnmqp0r2twvyx8zb',
'odd' => '238967debc01fg45kmstqrwxuvhjyznp'
)
);
/**
* array of bordering hash character maps.
*/
private $borders = array (
// north
'top' => array (
'even' => 'prxz',
'odd' => 'bcfguvyz'
),
// east
'right' => array (
'even' => 'bcfguvyz',
'odd' => 'prxz'
),
// west
'left' => array (
'even' => '0145hjnp',
'odd' => '028b'
),
// south
'bottom' => array (
'even' => '028b',
'odd' => '0145hjnp'
)
);
/**
* Convert the geohash to a Point. The point is 2-dimensional.
* @return Point the converted geohash
* @param string $hash a geohash
* @see GeoAdapter::read()
*/
public function read($hash, $as_grid = FALSE) {
$ll = $this->decode($hash);
if (!$as_grid) {
return new Point($ll['medlon'], $ll['medlat']);
}
else {
return new Polygon(array(
new LineString(array(
new Point($ll['minlon'], $ll['maxlat']),
new Point($ll['maxlon'], $ll['maxlat']),
new Point($ll['maxlon'], $ll['minlat']),
new Point($ll['minlon'], $ll['minlat']),
new Point($ll['minlon'], $ll['maxlat']),
))
));
}
}
/**
* Convert the geometry to geohash.
* @return string the geohash or null when the $geometry is not a Point
* @param Point $geometry
* @see GeoAdapter::write()
*/
public function write(Geometry $geometry, $precision = NULL){
if ($geometry->isEmpty()) return '';
if($geometry->geometryType() === 'Point'){
return $this->encodePoint($geometry, $precision);
}
else {
// The geohash is the hash grid ID that fits the envelope
$envelope = $geometry->envelope();
$geohashes = array();
$geohash = '';
foreach ($envelope->getPoints() as $point) {
$geohashes[] = $this->encodePoint($point, 0.0000001);
}
$i = 0;
while ($i < strlen($geohashes[0])) {
$char = $geohashes[0][$i];
foreach ($geohashes as $hash) {
if ($hash[$i] != $char) {
return $geohash;
}
}
$geohash .= $char;
$i++;
}
return $geohash;
}
}
/**
* @return string geohash
* @param Point $point
* @author algorithm based on code by Alexander Songe <a@songe.me>
* @see https://github.com/asonge/php-geohash/issues/1
*/
private function encodePoint($point, $precision = NULL){
if ($precision === NULL) {
$lap = strlen($point->y())-strpos($point->y(),".");
$lop = strlen($point->x())-strpos($point->x(),".");
$precision = pow(10,-max($lap-1,$lop-1,0))/2;
}
$minlat = -90;
$maxlat = 90;
$minlon = -180;
$maxlon = 180;
$latE = 90;
$lonE = 180;
$i = 0;
$error = 180;
$hash='';
while($error>=$precision) {
$chr = 0;
for($b=4;$b>=0;--$b) {
if((1&$b) == (1&$i)) {
// even char, even bit OR odd char, odd bit...a lon
$next = ($minlon+$maxlon)/2;
if($point->x()>$next) {
$chr |= pow(2,$b);
$minlon = $next;
} else {
$maxlon = $next;
}
$lonE /= 2;
} else {
// odd char, even bit OR even char, odd bit...a lat
$next = ($minlat+$maxlat)/2;
if($point->y()>$next) {
$chr |= pow(2,$b);
$minlat = $next;
} else {
$maxlat = $next;
}
$latE /= 2;
}
}
$hash .= $this->table[$chr];
$i++;
$error = min($latE,$lonE);
}
return $hash;
}
/**
* @param string $hash a geohash
* @author algorithm based on code by Alexander Songe <a@songe.me>
* @see https://github.com/asonge/php-geohash/issues/1
*/
private function decode($hash){
$ll = array();
$minlat = -90;
$maxlat = 90;
$minlon = -180;
$maxlon = 180;
$latE = 90;
$lonE = 180;
for($i=0,$c=strlen($hash);$i<$c;$i++) {
$v = strpos($this->table,$hash[$i]);
if(1&$i) {
if(16&$v)$minlat = ($minlat+$maxlat)/2; else $maxlat = ($minlat+$maxlat)/2;
if(8&$v) $minlon = ($minlon+$maxlon)/2; else $maxlon = ($minlon+$maxlon)/2;
if(4&$v) $minlat = ($minlat+$maxlat)/2; else $maxlat = ($minlat+$maxlat)/2;
if(2&$v) $minlon = ($minlon+$maxlon)/2; else $maxlon = ($minlon+$maxlon)/2;
if(1&$v) $minlat = ($minlat+$maxlat)/2; else $maxlat = ($minlat+$maxlat)/2;
$latE /= 8;
$lonE /= 4;
} else {
if(16&$v)$minlon = ($minlon+$maxlon)/2; else $maxlon = ($minlon+$maxlon)/2;
if(8&$v) $minlat = ($minlat+$maxlat)/2; else $maxlat = ($minlat+$maxlat)/2;
if(4&$v) $minlon = ($minlon+$maxlon)/2; else $maxlon = ($minlon+$maxlon)/2;
if(2&$v) $minlat = ($minlat+$maxlat)/2; else $maxlat = ($minlat+$maxlat)/2;
if(1&$v) $minlon = ($minlon+$maxlon)/2; else $maxlon = ($minlon+$maxlon)/2;
$latE /= 4;
$lonE /= 8;
}
}
$ll['minlat'] = $minlat;
$ll['minlon'] = $minlon;
$ll['maxlat'] = $maxlat;
$ll['maxlon'] = $maxlon;
$ll['medlat'] = round(($minlat+$maxlat)/2, max(1, -round(log10($latE)))-1);
$ll['medlon'] = round(($minlon+$maxlon)/2, max(1, -round(log10($lonE)))-1);
return $ll;
}
/**
* Calculates the adjacent geohash of the geohash in the specified direction.
* This algorithm is available in various ports that seem to point back to
* geohash-js by David Troy under MIT notice.
*
*
* @see https://github.com/davetroy/geohash-js
* @see https://github.com/lyokato/objc-geohash
* @see https://github.com/lyokato/libgeohash
* @see https://github.com/masuidrive/pr_geohash
* @see https://github.com/sunng87/node-geohash
* @see https://github.com/davidmoten/geo
*
* @param string $hash the geohash (lowercase)
* @param string $direction the direction of the neighbor (top, bottom, left or right)
* @return string the geohash of the adjacent cell
*/
public function adjacent($hash, $direction){
$last = substr($hash, -1);
$type = (strlen($hash) % 2)? 'odd': 'even';
$base = substr($hash, 0, strlen($hash) - 1);
if(strpos(($this->borders[$direction][$type]), $last) !== false){
$base = $this->adjacent($base, $direction);
}
return $base.$this->table[strpos($this->neighbours[$direction][$type], $last)];
}
}

View file

@ -0,0 +1,155 @@
<?php
/**
* GeoJSON class : a geojson reader/writer.
*
* Note that it will always return a GeoJSON geometry. This
* means that if you pass it a feature, it will return the
* geometry of that feature strip everything else.
*/
class GeoJSON extends GeoAdapter
{
/**
* Given an object or a string, return a Geometry
*
* @param mixed $input The GeoJSON string or object
*
* @return object Geometry
*/
public function read($input) {
if (is_string($input)) {
$input = json_decode($input);
}
if (!is_object($input)) {
throw new Exception('Invalid JSON');
}
if (!is_string($input->type)) {
throw new Exception('Invalid JSON');
}
// Check to see if it's a FeatureCollection
if ($input->type == 'FeatureCollection') {
$geoms = array();
foreach ($input->features as $feature) {
$geoms[] = $this->read($feature);
}
return geoPHP::geometryReduce($geoms);
}
// Check to see if it's a Feature
if ($input->type == 'Feature') {
return $this->read($input->geometry);
}
// It's a geometry - process it
return $this->objToGeom($input);
}
private function objToGeom($obj) {
$type = $obj->type;
if ($type == 'GeometryCollection') {
return $this->objToGeometryCollection($obj);
}
$method = 'arrayTo' . $type;
return $this->$method($obj->coordinates);
}
private function arrayToPoint($array) {
if (!empty($array)) {
return new Point($array[0], $array[1]);
}
else {
return new Point();
}
}
private function arrayToLineString($array) {
$points = array();
foreach ($array as $comp_array) {
$points[] = $this->arrayToPoint($comp_array);
}
return new LineString($points);
}
private function arrayToPolygon($array) {
$lines = array();
foreach ($array as $comp_array) {
$lines[] = $this->arrayToLineString($comp_array);
}
return new Polygon($lines);
}
private function arrayToMultiPoint($array) {
$points = array();
foreach ($array as $comp_array) {
$points[] = $this->arrayToPoint($comp_array);
}
return new MultiPoint($points);
}
private function arrayToMultiLineString($array) {
$lines = array();
foreach ($array as $comp_array) {
$lines[] = $this->arrayToLineString($comp_array);
}
return new MultiLineString($lines);
}
private function arrayToMultiPolygon($array) {
$polys = array();
foreach ($array as $comp_array) {
$polys[] = $this->arrayToPolygon($comp_array);
}
return new MultiPolygon($polys);
}
private function objToGeometryCollection($obj) {
$geoms = array();
if (empty($obj->geometries)) {
throw new Exception('Invalid GeoJSON: GeometryCollection with no component geometries');
}
foreach ($obj->geometries as $comp_object) {
$geoms[] = $this->objToGeom($comp_object);
}
return new GeometryCollection($geoms);
}
/**
* Serializes an object into a geojson string
*
*
* @param Geometry $obj The object to serialize
*
* @return string The GeoJSON string
*/
public function write(Geometry $geometry, $return_array = FALSE) {
if ($return_array) {
return $this->getArray($geometry);
}
else {
return json_encode($this->getArray($geometry));
}
}
public function getArray($geometry) {
if ($geometry->getGeomType() == 'GeometryCollection') {
$component_array = array();
foreach ($geometry->components as $component) {
$component_array[] = array(
'type' => $component->geometryType(),
'coordinates' => $component->asArray(),
);
}
return array(
'type'=> 'GeometryCollection',
'geometries'=> $component_array,
);
}
else return array(
'type'=> $geometry->getGeomType(),
'coordinates'=> $geometry->asArray(),
);
}
}

View file

@ -0,0 +1,244 @@
<?php
/*
* Copyright (c) Patrick Hayes
*
* This code is open-source and licenced under the Modified BSD License.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* PHP Geometry/GeoRSS encoder/decoder
*/
class GeoRSS extends GeoAdapter
{
private $namespace = FALSE;
private $nss = ''; // Name-space string. eg 'georss:'
/**
* Read GeoRSS string into geometry objects
*
* @param string $georss - an XML feed containing geoRSS
*
* @return Geometry|GeometryCollection
*/
public function read($gpx) {
return $this->geomFromText($gpx);
}
/**
* Serialize geometries into a GeoRSS string.
*
* @param Geometry $geometry
*
* @return string The georss string representation of the input geometries
*/
public function write(Geometry $geometry, $namespace = FALSE) {
if ($namespace) {
$this->namespace = $namespace;
$this->nss = $namespace.':';
}
return $this->geometryToGeoRSS($geometry);
}
public function geomFromText($text) {
// Change to lower-case, strip all CDATA, and de-namespace
$text = strtolower($text);
$text = preg_replace('/<!\[cdata\[(.*?)\]\]>/s','',$text);
// Load into DOMDOcument
$xmlobj = new DOMDocument();
@$xmlobj->loadXML($text);
if ($xmlobj === false) {
throw new Exception("Invalid GeoRSS: ". $text);
}
$this->xmlobj = $xmlobj;
try {
$geom = $this->geomFromXML();
} catch(InvalidText $e) {
throw new Exception("Cannot Read Geometry From GeoRSS: ". $text);
} catch(Exception $e) {
throw $e;
}
return $geom;
}
protected function geomFromXML() {
$geometries = array();
$geometries = array_merge($geometries, $this->parsePoints());
$geometries = array_merge($geometries, $this->parseLines());
$geometries = array_merge($geometries, $this->parsePolygons());
$geometries = array_merge($geometries, $this->parseBoxes());
$geometries = array_merge($geometries, $this->parseCircles());
if (empty($geometries)) {
throw new Exception("Invalid / Empty GeoRSS");
}
return geoPHP::geometryReduce($geometries);
}
protected function getPointsFromCoords($string) {
$coords = array();
if (empty($string)) {
return $coords;
}
$latlon = explode(' ',$string);
foreach ($latlon as $key => $item) {
if (!($key % 2)) {
// It's a latitude
$lat = $item;
}
else {
// It's a longitude
$lon = $item;
$coords[] = new Point($lon, $lat);
}
}
return $coords;
}
protected function parsePoints() {
$points = array();
$pt_elements = $this->xmlobj->getElementsByTagName('point');
foreach ($pt_elements as $pt) {
if ($pt->hasChildNodes()) {
$point_array = $this->getPointsFromCoords(trim($pt->firstChild->nodeValue));
}
if (!empty($point_array)) {
$points[] = $point_array[0];
}
else {
$points[] = new Point();
}
}
return $points;
}
protected function parseLines() {
$lines = array();
$line_elements = $this->xmlobj->getElementsByTagName('line');
foreach ($line_elements as $line) {
$components = $this->getPointsFromCoords(trim($line->firstChild->nodeValue));
$lines[] = new LineString($components);
}
return $lines;
}
protected function parsePolygons() {
$polygons = array();
$poly_elements = $this->xmlobj->getElementsByTagName('polygon');
foreach ($poly_elements as $poly) {
if ($poly->hasChildNodes()) {
$points = $this->getPointsFromCoords(trim($poly->firstChild->nodeValue));
$exterior_ring = new LineString($points);
$polygons[] = new Polygon(array($exterior_ring));
}
else {
// It's an EMPTY polygon
$polygons[] = new Polygon();
}
}
return $polygons;
}
// Boxes are rendered into polygons
protected function parseBoxes() {
$polygons = array();
$box_elements = $this->xmlobj->getElementsByTagName('box');
foreach ($box_elements as $box) {
$parts = explode(' ',trim($box->firstChild->nodeValue));
$components = array(
new Point($parts[3], $parts[2]),
new Point($parts[3], $parts[0]),
new Point($parts[1], $parts[0]),
new Point($parts[1], $parts[2]),
new Point($parts[3], $parts[2]),
);
$exterior_ring = new LineString($components);
$polygons[] = new Polygon(array($exterior_ring));
}
return $polygons;
}
// Circles are rendered into points
// @@TODO: Add good support once we have circular-string geometry support
protected function parseCircles() {
$points = array();
$circle_elements = $this->xmlobj->getElementsByTagName('circle');
foreach ($circle_elements as $circle) {
$parts = explode(' ',trim($circle->firstChild->nodeValue));
$points[] = new Point($parts[1], $parts[0]);
}
return $points;
}
protected function geometryToGeoRSS($geom) {
$type = strtolower($geom->getGeomType());
switch ($type) {
case 'point':
return $this->pointToGeoRSS($geom);
break;
case 'linestring':
return $this->linestringToGeoRSS($geom);
break;
case 'polygon':
return $this->PolygonToGeoRSS($geom);
break;
case 'multipoint':
case 'multilinestring':
case 'multipolygon':
case 'geometrycollection':
return $this->collectionToGeoRSS($geom);
break;
}
return $output;
}
private function pointToGeoRSS($geom) {
$out = '<'.$this->nss.'point>';
if (!$geom->isEmpty()) {
$out .= $geom->getY().' '.$geom->getX();
}
$out .= '</'.$this->nss.'point>';
return $out;
}
private function linestringToGeoRSS($geom) {
$output = '<'.$this->nss.'line>';
foreach ($geom->getComponents() as $k => $point) {
$output .= $point->getY().' '.$point->getX();
if ($k < ($geom->numGeometries() -1)) $output .= ' ';
}
$output .= '</'.$this->nss.'line>';
return $output;
}
private function polygonToGeoRSS($geom) {
$output = '<'.$this->nss.'polygon>';
$exterior_ring = $geom->exteriorRing();
foreach ($exterior_ring->getComponents() as $k => $point) {
$output .= $point->getY().' '.$point->getX();
if ($k < ($exterior_ring->numGeometries() -1)) $output .= ' ';
}
$output .= '</'.$this->nss.'polygon>';
return $output;
}
public function collectionToGeoRSS($geom) {
$georss = '<'.$this->nss.'where>';
$components = $geom->getComponents();
foreach ($geom->getComponents() as $comp) {
$georss .= $this->geometryToGeoRSS($comp);
}
$georss .= '</'.$this->nss.'where>';
return $georss;
}
}

View file

@ -0,0 +1,158 @@
<?php
/*
* (c) Camptocamp <info@camptocamp.com>
* (c) Patrick Hayes
*
* This code is open-source and licenced under the Modified BSD License.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* PHP Google Geocoder Adapter
*
*
* @package geoPHP
* @author Patrick Hayes <patrick.d.hayes@gmail.com>
*/
class GoogleGeocode extends GeoAdapter
{
/**
* Read an address string or array geometry objects
*
* @param string - Address to geocode
* @param string - Type of Geometry to return. Can either be 'points' or 'bounds' (polygon)
* @param Geometry|bounds-array - Limit the search area to within this region. For example
* by default geocoding "Cairo" will return the location of Cairo Egypt.
* If you pass a polygon of illinois, it will return Cairo IL.
* @param return_multiple - Return all results in a multipoint or multipolygon
* @return Geometry|GeometryCollection
*/
public function read($address, $return_type = 'point', $bounds = FALSE, $return_multiple = FALSE) {
if (is_array($address)) $address = join(',', $address);
if (gettype($bounds) == 'object') {
$bounds = $bounds->getBBox();
}
if (gettype($bounds) == 'array') {
$bounds_string = '&bounds='.$bounds['miny'].','.$bounds['minx'].'|'.$bounds['maxy'].','.$bounds['maxx'];
}
else {
$bounds_string = '';
}
$url = "http://maps.googleapis.com/maps/api/geocode/json";
$url .= '?address='. urlencode($address);
$url .= $bounds_string;
$url .= '&sensor=false';
$this->result = json_decode(@file_get_contents($url));
if ($this->result->status == 'OK') {
if ($return_multiple == FALSE) {
if ($return_type == 'point') {
return $this->getPoint();
}
if ($return_type == 'bounds' || $return_type == 'polygon') {
return $this->getPolygon();
}
}
if ($return_multiple == TRUE) {
if ($return_type == 'point') {
$points = array();
foreach ($this->result->results as $delta => $item) {
$points[] = $this->getPoint($delta);
}
return new MultiPoint($points);
}
if ($return_type == 'bounds' || $return_type == 'polygon') {
$polygons = array();
foreach ($this->result->results as $delta => $item) {
$polygons[] = $this->getPolygon($delta);
}
return new MultiPolygon($polygons);
}
}
}
else {
if ($this->result->status) throw new Exception('Error in Google Geocoder: '.$this->result->status);
else throw new Exception('Unknown error in Google Geocoder');
return FALSE;
}
}
/**
* Serialize geometries into a WKT string.
*
* @param Geometry $geometry
* @param string $return_type Should be either 'string' or 'array'
*
* @return string Does a reverse geocode of the geometry
*/
public function write(Geometry $geometry, $return_type = 'string') {
$centroid = $geometry->getCentroid();
$lat = $centroid->getY();
$lon = $centroid->getX();
$url = "http://maps.googleapis.com/maps/api/geocode/json";
$url .= '?latlng='.$lat.','.$lon;
$url .= '&sensor=false';
$this->result = json_decode(@file_get_contents($url));
if ($this->result->status == 'OK') {
if ($return_type == 'string') {
return $this->result->results[0]->formatted_address;
}
if ($return_type == 'array') {
return $this->result->results[0]->address_components;
}
}
else {
if ($this->result->status) throw new Exception('Error in Google Reverse Geocoder: '.$this->result->status);
else throw new Exception('Unknown error in Google Reverse Geocoder');
return FALSE;
}
}
private function getPoint($delta = 0) {
$lat = $this->result->results[$delta]->geometry->location->lat;
$lon = $this->result->results[$delta]->geometry->location->lng;
return new Point($lon, $lat);
}
private function getPolygon($delta = 0) {
$points = array (
$this->getTopLeft($delta),
$this->getTopRight($delta),
$this->getBottomRight($delta),
$this->getBottomLeft($delta),
$this->getTopLeft($delta),
);
$outer_ring = new LineString($points);
return new Polygon(array($outer_ring));
}
private function getTopLeft($delta = 0) {
$lat = $this->result->results[$delta]->geometry->bounds->northeast->lat;
$lon = $this->result->results[$delta]->geometry->bounds->southwest->lng;
return new Point($lon, $lat);
}
private function getTopRight($delta = 0) {
$lat = $this->result->results[$delta]->geometry->bounds->northeast->lat;
$lon = $this->result->results[$delta]->geometry->bounds->northeast->lng;
return new Point($lon, $lat);
}
private function getBottomLeft($delta = 0) {
$lat = $this->result->results[$delta]->geometry->bounds->southwest->lat;
$lon = $this->result->results[$delta]->geometry->bounds->southwest->lng;
return new Point($lon, $lat);
}
private function getBottomRight($delta = 0) {
$lat = $this->result->results[$delta]->geometry->bounds->southwest->lat;
$lon = $this->result->results[$delta]->geometry->bounds->northeast->lng;
return new Point($lon, $lat);
}
}

View file

@ -0,0 +1,272 @@
<?php
/*
* Copyright (c) Patrick Hayes
* Copyright (c) 2010-2011, Arnaud Renevier
*
* This code is open-source and licenced under the Modified BSD License.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* PHP Geometry/KML encoder/decoder
*
* Mainly inspired/adapted from OpenLayers( http://www.openlayers.org )
* Openlayers/format/WKT.js
*
* @package sfMapFishPlugin
* @subpackage GeoJSON
* @author Camptocamp <info@camptocamp.com>
*/
class KML extends GeoAdapter
{
private $namespace = FALSE;
private $nss = ''; // Name-space string. eg 'georss:'
/**
* Read KML string into geometry objects
*
* @param string $kml A KML string
*
* @return Geometry|GeometryCollection
*/
public function read($kml) {
return $this->geomFromText($kml);
}
/**
* Serialize geometries into a KML string.
*
* @param Geometry $geometry
*
* @return string The KML string representation of the input geometries
*/
public function write(Geometry $geometry, $namespace = FALSE) {
if ($namespace) {
$this->namespace = $namespace;
$this->nss = $namespace.':';
}
return $this->geometryToKML($geometry);
}
public function geomFromText($text) {
// Change to lower-case and strip all CDATA
$text = mb_strtolower($text, mb_detect_encoding($text));
$text = preg_replace('/<!\[cdata\[(.*?)\]\]>/s','',$text);
// Load into DOMDocument
$xmlobj = new DOMDocument();
@$xmlobj->loadXML($text);
if ($xmlobj === false) {
throw new Exception("Invalid KML: ". $text);
}
$this->xmlobj = $xmlobj;
try {
$geom = $this->geomFromXML();
} catch(InvalidText $e) {
throw new Exception("Cannot Read Geometry From KML: ". $text);
} catch(Exception $e) {
throw $e;
}
return $geom;
}
protected function geomFromXML() {
$geometries = array();
$geom_types = geoPHP::geometryList();
$placemark_elements = $this->xmlobj->getElementsByTagName('placemark');
if ($placemark_elements->length) {
foreach ($placemark_elements as $placemark) {
foreach ($placemark->childNodes as $child) {
// Node names are all the same, except for MultiGeometry, which maps to GeometryCollection
$node_name = $child->nodeName == 'multigeometry' ? 'geometrycollection' : $child->nodeName;
if (array_key_exists($node_name, $geom_types)) {
$function = 'parse'.$geom_types[$node_name];
$geometries[] = $this->$function($child);
}
}
}
}
else {
// The document does not have a placemark, try to create a valid geometry from the root element
$node_name = $this->xmlobj->documentElement->nodeName == 'multigeometry' ? 'geometrycollection' : $this->xmlobj->documentElement->nodeName;
if (array_key_exists($node_name, $geom_types)) {
$function = 'parse'.$geom_types[$node_name];
$geometries[] = $this->$function($this->xmlobj->documentElement);
}
}
return geoPHP::geometryReduce($geometries);
}
protected function childElements($xml, $nodename = '') {
$children = array();
if ($xml->childNodes) {
foreach ($xml->childNodes as $child) {
if ($child->nodeName == $nodename) {
$children[] = $child;
}
}
}
return $children;
}
protected function parsePoint($xml) {
$coordinates = $this->_extractCoordinates($xml);
if (!empty($coordinates)) {
return new Point($coordinates[0][0],$coordinates[0][1]);
}
else {
return new Point();
}
}
protected function parseLineString($xml) {
$coordinates = $this->_extractCoordinates($xml);
$point_array = array();
foreach ($coordinates as $set) {
$point_array[] = new Point($set[0],$set[1]);
}
return new LineString($point_array);
}
protected function parsePolygon($xml) {
$components = array();
$outer_boundary_element_a = $this->childElements($xml, 'outerboundaryis');
if (empty($outer_boundary_element_a)) {
return new Polygon(); // It's an empty polygon
}
$outer_boundary_element = $outer_boundary_element_a[0];
$outer_ring_element_a = $this->childElements($outer_boundary_element, 'linearring');
$outer_ring_element = $outer_ring_element_a[0];
$components[] = $this->parseLineString($outer_ring_element);
if (count($components) != 1) {
throw new Exception("Invalid KML");
}
$inner_boundary_element_a = $this->childElements($xml, 'innerboundaryis');
if (count($inner_boundary_element_a)) {
foreach ($inner_boundary_element_a as $inner_boundary_element) {
foreach ($this->childElements($inner_boundary_element, 'linearring') as $inner_ring_element) {
$components[] = $this->parseLineString($inner_ring_element);
}
}
}
return new Polygon($components);
}
protected function parseGeometryCollection($xml) {
$components = array();
$geom_types = geoPHP::geometryList();
foreach ($xml->childNodes as $child) {
$nodeName = ($child->nodeName == 'linearring') ? 'linestring' : $child->nodeName;
if (array_key_exists($nodeName, $geom_types)) {
$function = 'parse'.$geom_types[$nodeName];
$components[] = $this->$function($child);
}
}
return new GeometryCollection($components);
}
protected function _extractCoordinates($xml) {
$coord_elements = $this->childElements($xml, 'coordinates');
$coordinates = array();
if (count($coord_elements)) {
$coord_sets = explode(' ', preg_replace('/[\r\n]+/', ' ', $coord_elements[0]->nodeValue));
foreach ($coord_sets as $set_string) {
$set_string = trim($set_string);
if ($set_string) {
$set_array = explode(',',$set_string);
if (count($set_array) >= 2) {
$coordinates[] = $set_array;
}
}
}
}
return $coordinates;
}
private function geometryToKML($geom) {
$type = strtolower($geom->getGeomType());
switch ($type) {
case 'point':
return $this->pointToKML($geom);
break;
case 'linestring':
return $this->linestringToKML($geom);
break;
case 'polygon':
return $this->polygonToKML($geom);
break;
case 'multipoint':
case 'multilinestring':
case 'multipolygon':
case 'geometrycollection':
return $this->collectionToKML($geom);
break;
}
}
private function pointToKML($geom) {
$out = '<'.$this->nss.'Point>';
if (!$geom->isEmpty()) {
$out .= '<'.$this->nss.'coordinates>'.$geom->getX().",".$geom->getY().'</'.$this->nss.'coordinates>';
}
$out .= '</'.$this->nss.'Point>';
return $out;
}
private function linestringToKML($geom, $type = FALSE) {
if (!$type) {
$type = $geom->getGeomType();
}
$str = '<'.$this->nss . $type .'>';
if (!$geom->isEmpty()) {
$str .= '<'.$this->nss.'coordinates>';
$i=0;
foreach ($geom->getComponents() as $comp) {
if ($i != 0) $str .= ' ';
$str .= $comp->getX() .','. $comp->getY();
$i++;
}
$str .= '</'.$this->nss.'coordinates>';
}
$str .= '</'. $this->nss . $type .'>';
return $str;
}
public function polygonToKML($geom) {
$components = $geom->getComponents();
$str = '';
if (!empty($components)) {
$str = '<'.$this->nss.'outerBoundaryIs>' . $this->linestringToKML($components[0], 'LinearRing') . '</'.$this->nss.'outerBoundaryIs>';
foreach (array_slice($components, 1) as $comp) {
$str .= '<'.$this->nss.'innerBoundaryIs>' . $this->linestringToKML($comp) . '</'.$this->nss.'innerBoundaryIs>';
}
}
return '<'.$this->nss.'Polygon>'. $str .'</'.$this->nss.'Polygon>';
}
public function collectionToKML($geom) {
$components = $geom->getComponents();
$str = '<'.$this->nss.'MultiGeometry>';
foreach ($geom->getComponents() as $comp) {
$sub_adapter = new KML();
$str .= $sub_adapter->write($comp);
}
return $str .'</'.$this->nss.'MultiGeometry>';
}
}

View file

@ -0,0 +1,250 @@
<?php
/*
* (c) Patrick Hayes
*
* This code is open-source and licenced under the Modified BSD License.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* PHP Geometry/WKB encoder/decoder
*
*/
class WKB extends GeoAdapter
{
private $dimension = 2;
private $z = FALSE;
private $m = FALSE;
/**
* Read WKB into geometry objects
*
* @param string $wkb
* Well-known-binary string
* @param bool $is_hex_string
* If this is a hexedecimal string that is in need of packing
*
* @return Geometry
*/
public function read($wkb, $is_hex_string = FALSE) {
if ($is_hex_string) {
$wkb = pack('H*',$wkb);
}
if (empty($wkb)) {
throw new Exception('Cannot read empty WKB geometry. Found ' . gettype($wkb));
}
$mem = fopen('php://memory', 'r+');
fwrite($mem, $wkb);
fseek($mem, 0);
$geometry = $this->getGeometry($mem);
fclose($mem);
return $geometry;
}
function getGeometry(&$mem) {
$base_info = unpack("corder/ctype/cz/cm/cs", fread($mem, 5));
if ($base_info['order'] !== 1) {
throw new Exception('Only NDR (little endian) SKB format is supported at the moment');
}
if ($base_info['z']) {
$this->dimension++;
$this->z = TRUE;
}
if ($base_info['m']) {
$this->dimension++;
$this->m = TRUE;
}
// If there is SRID information, ignore it - use EWKB Adapter to get SRID support
if ($base_info['s']) {
fread($mem, 4);
}
switch ($base_info['type']) {
case 1:
return $this->getPoint($mem);
case 2:
return $this->getLinstring($mem);
case 3:
return $this->getPolygon($mem);
case 4:
return $this->getMulti($mem,'point');
case 5:
return $this->getMulti($mem,'line');
case 6:
return $this->getMulti($mem,'polygon');
case 7:
return $this->getMulti($mem,'geometry');
}
}
function getPoint(&$mem) {
$point_coords = unpack("d*", fread($mem,$this->dimension*8));
if (!empty($point_coords)) {
return new Point($point_coords[1],$point_coords[2]);
}
else {
return new Point(); // EMPTY point
}
}
function getLinstring(&$mem) {
// Get the number of points expected in this string out of the first 4 bytes
$line_length = unpack('L',fread($mem,4));
// Return an empty linestring if there is no line-length
if (!$line_length[1]) return new LineString();
// Read the nubmer of points x2 (each point is two coords) into decimal-floats
$line_coords = unpack('d*', fread($mem,$line_length[1]*$this->dimension*8));
// We have our coords, build up the linestring
$components = array();
$i = 1;
$num_coords = count($line_coords);
while ($i <= $num_coords) {
$components[] = new Point($line_coords[$i],$line_coords[$i+1]);
$i += 2;
}
return new LineString($components);
}
function getPolygon(&$mem) {
// Get the number of linestring expected in this poly out of the first 4 bytes
$poly_length = unpack('L',fread($mem,4));
$components = array();
$i = 1;
while ($i <= $poly_length[1]) {
$components[] = $this->getLinstring($mem);
$i++;
}
return new Polygon($components);
}
function getMulti(&$mem, $type) {
// Get the number of items expected in this multi out of the first 4 bytes
$multi_length = unpack('L',fread($mem,4));
$components = array();
$i = 1;
while ($i <= $multi_length[1]) {
$components[] = $this->getGeometry($mem);
$i++;
}
switch ($type) {
case 'point':
return new MultiPoint($components);
case 'line':
return new MultiLineString($components);
case 'polygon':
return new MultiPolygon($components);
case 'geometry':
return new GeometryCollection($components);
}
}
/**
* Serialize geometries into WKB string.
*
* @param Geometry $geometry
*
* @return string The WKB string representation of the input geometries
*/
public function write(Geometry $geometry, $write_as_hex = FALSE) {
// We always write into NDR (little endian)
$wkb = pack('c',1);
switch ($geometry->getGeomType()) {
case 'Point';
$wkb .= pack('L',1);
$wkb .= $this->writePoint($geometry);
break;
case 'LineString';
$wkb .= pack('L',2);
$wkb .= $this->writeLineString($geometry);
break;
case 'Polygon';
$wkb .= pack('L',3);
$wkb .= $this->writePolygon($geometry);
break;
case 'MultiPoint';
$wkb .= pack('L',4);
$wkb .= $this->writeMulti($geometry);
break;
case 'MultiLineString';
$wkb .= pack('L',5);
$wkb .= $this->writeMulti($geometry);
break;
case 'MultiPolygon';
$wkb .= pack('L',6);
$wkb .= $this->writeMulti($geometry);
break;
case 'GeometryCollection';
$wkb .= pack('L',7);
$wkb .= $this->writeMulti($geometry);
break;
}
if ($write_as_hex) {
$unpacked = unpack('H*',$wkb);
return $unpacked[1];
}
else {
return $wkb;
}
}
function writePoint($point) {
// Set the coords
if (!$point->isEmpty()) {
$wkb = pack('dd',$point->x(), $point->y());
return $wkb;
} else {
return '';
}
}
function writeLineString($line) {
// Set the number of points in this line
$wkb = pack('L',$line->numPoints());
// Set the coords
foreach ($line->getComponents() as $point) {
$wkb .= pack('dd',$point->x(), $point->y());
}
return $wkb;
}
function writePolygon($poly) {
// Set the number of lines in this poly
$wkb = pack('L',$poly->numGeometries());
// Write the lines
foreach ($poly->getComponents() as $line) {
$wkb .= $this->writeLineString($line);
}
return $wkb;
}
function writeMulti($geometry) {
// Set the number of components
$wkb = pack('L',$geometry->numGeometries());
// Write the components
foreach ($geometry->getComponents() as $component) {
$wkb .= $this->write($component);
}
return $wkb;
}
}

View file

@ -0,0 +1,258 @@
<?php
/**
* WKT (Well Known Text) Adapter
*/
class WKT extends GeoAdapter
{
/**
* Read WKT string into geometry objects
*
* @param string $WKT A WKT string
*
* @return Geometry
*/
public function read($wkt) {
$wkt = trim($wkt);
// If it contains a ';', then it contains additional SRID data
if (strpos($wkt,';')) {
$parts = explode(';', $wkt);
$wkt = $parts[1];
$eparts = explode('=',$parts[0]);
$srid = $eparts[1];
}
else {
$srid = NULL;
}
// If geos is installed, then we take a shortcut and let it parse the WKT
if (geoPHP::geosInstalled()) {
$reader = new GEOSWKTReader();
if ($srid) {
$geom = geoPHP::geosToGeometry($reader->read($wkt));
$geom->setSRID($srid);
return $geom;
}
else {
return geoPHP::geosToGeometry($reader->read($wkt));
}
}
$wkt = str_replace(', ', ',', $wkt);
// For each geometry type, check to see if we have a match at the
// beginning of the string. If we do, then parse using that type
foreach (geoPHP::geometryList() as $geom_type) {
$wkt_geom = strtoupper($geom_type);
if (strtoupper(substr($wkt, 0, strlen($wkt_geom))) == $wkt_geom) {
$data_string = $this->getDataString($wkt);
$method = 'parse'.$geom_type;
if ($srid) {
$geom = $this->$method($data_string);
$geom->setSRID($srid);
return $geom;
}
else {
return $this->$method($data_string);
}
}
}
}
private function parsePoint($data_string) {
$data_string = $this->trimParens($data_string);
// If it's marked as empty, then return an empty point
if ($data_string == 'EMPTY') return new Point();
$parts = explode(' ',$data_string);
return new Point($parts[0], $parts[1]);
}
private function parseLineString($data_string) {
$data_string = $this->trimParens($data_string);
// If it's marked as empty, then return an empty line
if ($data_string == 'EMPTY') return new LineString();
$parts = explode(',',$data_string);
$points = array();
foreach ($parts as $part) {
$points[] = $this->parsePoint($part);
}
return new LineString($points);
}
private function parsePolygon($data_string) {
$data_string = $this->trimParens($data_string);
// If it's marked as empty, then return an empty polygon
if ($data_string == 'EMPTY') return new Polygon();
$parts = explode('),(',$data_string);
$lines = array();
foreach ($parts as $part) {
if (!$this->beginsWith($part,'(')) $part = '(' . $part;
if (!$this->endsWith($part,')')) $part = $part . ')';
$lines[] = $this->parseLineString($part);
}
return new Polygon($lines);
}
private function parseMultiPoint($data_string) {
$data_string = $this->trimParens($data_string);
// If it's marked as empty, then return an empty MutiPoint
if ($data_string == 'EMPTY') return new MultiPoint();
$parts = explode(',',$data_string);
$points = array();
foreach ($parts as $part) {
$points[] = $this->parsePoint($part);
}
return new MultiPoint($points);
}
private function parseMultiLineString($data_string) {
$data_string = $this->trimParens($data_string);
// If it's marked as empty, then return an empty multi-linestring
if ($data_string == 'EMPTY') return new MultiLineString();
$parts = explode('),(',$data_string);
$lines = array();
foreach ($parts as $part) {
// Repair the string if the explode broke it
if (!$this->beginsWith($part,'(')) $part = '(' . $part;
if (!$this->endsWith($part,')')) $part = $part . ')';
$lines[] = $this->parseLineString($part);
}
return new MultiLineString($lines);
}
private function parseMultiPolygon($data_string) {
$data_string = $this->trimParens($data_string);
// If it's marked as empty, then return an empty multi-polygon
if ($data_string == 'EMPTY') return new MultiPolygon();
$parts = explode(')),((',$data_string);
$polys = array();
foreach ($parts as $part) {
// Repair the string if the explode broke it
if (!$this->beginsWith($part,'((')) $part = '((' . $part;
if (!$this->endsWith($part,'))')) $part = $part . '))';
$polys[] = $this->parsePolygon($part);
}
return new MultiPolygon($polys);
}
private function parseGeometryCollection($data_string) {
$data_string = $this->trimParens($data_string);
// If it's marked as empty, then return an empty geom-collection
if ($data_string == 'EMPTY') return new GeometryCollection();
$geometries = array();
$matches = array();
$str = preg_replace('/,\s*([A-Za-z])/', '|$1', $data_string);
$components = explode('|', trim($str));
foreach ($components as $component) {
$geometries[] = $this->read($component);
}
return new GeometryCollection($geometries);
}
protected function getDataString($wkt) {
$first_paren = strpos($wkt, '(');
if ($first_paren !== FALSE) {
return substr($wkt, $first_paren);
} elseif (strstr($wkt,'EMPTY')) {
return 'EMPTY';
} else
return FALSE;
}
/**
* Trim the parenthesis and spaces
*/
protected function trimParens($str) {
$str = trim($str);
// We want to only strip off one set of parenthesis
if ($this->beginsWith($str, '(')) {
return substr($str,1,-1);
}
else return $str;
}
protected function beginsWith($str, $char) {
if (substr($str,0,strlen($char)) == $char) return TRUE;
else return FALSE;
}
protected function endsWith($str, $char) {
if (substr($str,(0 - strlen($char))) == $char) return TRUE;
else return FALSE;
}
/**
* Serialize geometries into a WKT string.
*
* @param Geometry $geometry
*
* @return string The WKT string representation of the input geometries
*/
public function write(Geometry $geometry) {
// If geos is installed, then we take a shortcut and let it write the WKT
if (geoPHP::geosInstalled()) {
$writer = new GEOSWKTWriter();
$writer->setTrim(TRUE);
return $writer->write($geometry->geos());
}
if ($geometry->isEmpty()) {
return strtoupper($geometry->geometryType()).' EMPTY';
}
else if ($data = $this->extractData($geometry)) {
return strtoupper($geometry->geometryType()).' ('.$data.')';
}
}
/**
* Extract geometry to a WKT string
*
* @param Geometry $geometry A Geometry object
*
* @return string
*/
public function extractData($geometry) {
$parts = array();
switch ($geometry->geometryType()) {
case 'Point':
return $geometry->getX().' '.$geometry->getY();
case 'LineString':
foreach ($geometry->getComponents() as $component) {
$parts[] = $this->extractData($component);
}
return implode(', ', $parts);
case 'Polygon':
case 'MultiPoint':
case 'MultiLineString':
case 'MultiPolygon':
foreach ($geometry->getComponents() as $component) {
$parts[] = '('.$this->extractData($component).')';
}
return implode(', ', $parts);
case 'GeometryCollection':
foreach ($geometry->getComponents() as $component) {
$parts[] = strtoupper($component->geometryType()).' ('.$this->extractData($component).')';
}
return implode(', ', $parts);
}
}
}

View file

@ -0,0 +1,294 @@
<?php
/**
* Collection: Abstract class for compound geometries
*
* A geometry is a collection if it is made up of other
* component geometries. Therefore everything but a Point
* is a Collection. For example a LingString is a collection
* of Points. A Polygon is a collection of LineStrings etc.
*/
abstract class Collection extends Geometry
{
public $components = array();
/**
* Constructor: Checks and sets component geometries
*
* @param array $components array of geometries
*/
public function __construct($components = array()) {
if (!is_array($components)) {
throw new Exception("Component geometries must be passed as an array");
}
foreach ($components as $component) {
if ($component instanceof Geometry) {
$this->components[] = $component;
}
else {
throw new Exception("Cannot create a collection with non-geometries");
}
}
}
/**
* Returns Collection component geometries
*
* @return array
*/
public function getComponents() {
return $this->components;
}
public function centroid() {
if ($this->isEmpty()) return NULL;
if ($this->geos()) {
$geos_centroid = $this->geos()->centroid();
if ($geos_centroid->typeName() == 'Point') {
return geoPHP::geosToGeometry($this->geos()->centroid());
}
}
// As a rough estimate, we say that the centroid of a colletion is the centroid of it's envelope
// @@TODO: Make this the centroid of the convexHull
// Note: Outside of polygons, geometryCollections and the trivial case of points, there is no standard on what a "centroid" is
$centroid = $this->envelope()->centroid();
return $centroid;
}
public function getBBox() {
if ($this->isEmpty()) return NULL;
if ($this->geos()) {
$envelope = $this->geos()->envelope();
if ($envelope->typeName() == 'Point') {
return geoPHP::geosToGeometry($envelope)->getBBOX();
}
$geos_ring = $envelope->exteriorRing();
return array(
'maxy' => $geos_ring->pointN(3)->getY(),
'miny' => $geos_ring->pointN(1)->getY(),
'maxx' => $geos_ring->pointN(1)->getX(),
'minx' => $geos_ring->pointN(3)->getX(),
);
}
// Go through each component and get the max and min x and y
$i = 0;
foreach ($this->components as $component) {
$component_bbox = $component->getBBox();
// On the first run through, set the bbox to the component bbox
if ($i == 0) {
$maxx = $component_bbox['maxx'];
$maxy = $component_bbox['maxy'];
$minx = $component_bbox['minx'];
$miny = $component_bbox['miny'];
}
// Do a check and replace on each boundary, slowly growing the bbox
$maxx = $component_bbox['maxx'] > $maxx ? $component_bbox['maxx'] : $maxx;
$maxy = $component_bbox['maxy'] > $maxy ? $component_bbox['maxy'] : $maxy;
$minx = $component_bbox['minx'] < $minx ? $component_bbox['minx'] : $minx;
$miny = $component_bbox['miny'] < $miny ? $component_bbox['miny'] : $miny;
$i++;
}
return array(
'maxy' => $maxy,
'miny' => $miny,
'maxx' => $maxx,
'minx' => $minx,
);
}
public function asArray() {
$array = array();
foreach ($this->components as $component) {
$array[] = $component->asArray();
}
return $array;
}
public function area() {
if ($this->geos()) {
return $this->geos()->area();
}
$area = 0;
foreach ($this->components as $component) {
$area += $component->area();
}
return $area;
}
// By default, the boundary of a collection is the boundary of it's components
public function boundary() {
if ($this->isEmpty()) return new LineString();
if ($this->geos()) {
return $this->geos()->boundary();
}
$components_boundaries = array();
foreach ($this->components as $component) {
$components_boundaries[] = $component->boundary();
}
return geoPHP::geometryReduce($components_boundaries);
}
public function numGeometries() {
return count($this->components);
}
// Note that the standard is 1 based indexing
public function geometryN($n) {
$n = intval($n);
if (array_key_exists($n-1, $this->components)) {
return $this->components[$n-1];
}
else {
return NULL;
}
}
public function length() {
$length = 0;
foreach ($this->components as $delta => $component) {
$length += $component->length();
}
return $length;
}
public function greatCircleLength($radius = 6378137) {
$length = 0;
foreach ($this->components as $component) {
$length += $component->greatCircleLength($radius);
}
return $length;
}
public function haversineLength() {
$length = 0;
foreach ($this->components as $component) {
$length += $component->haversineLength();
}
return $length;
}
public function dimension() {
$dimension = 0;
foreach ($this->components as $component) {
if ($component->dimension() > $dimension) {
$dimension = $component->dimension();
}
}
return $dimension;
}
// A collection is empty if it has no components OR all it's components are empty
public function isEmpty() {
if (!count($this->components)) {
return TRUE;
}
else {
foreach ($this->components as $component) {
if (!$component->isEmpty()) return FALSE;
}
return TRUE;
}
}
public function numPoints() {
$num = 0;
foreach ($this->components as $component) {
$num += $component->numPoints();
}
return $num;
}
public function getPoints() {
$points = array();
foreach ($this->components as $component) {
$points = array_merge($points, $component->getPoints());
}
return $points;
}
public function equals($geometry) {
if ($this->geos()) {
return $this->geos()->equals($geometry->geos());
}
// To test for equality we check to make sure that there is a matching point
// in the other geometry for every point in this geometry.
// This is slightly more strict than the standard, which
// uses Within(A,B) = true and Within(B,A) = true
// @@TODO: Eventually we could fix this by using some sort of simplification
// method that strips redundant vertices (that are all in a row)
$this_points = $this->getPoints();
$other_points = $geometry->getPoints();
// First do a check to make sure they have the same number of vertices
if (count($this_points) != count($other_points)) {
return FALSE;
}
foreach ($this_points as $point) {
$found_match = FALSE;
foreach ($other_points as $key => $test_point) {
if ($point->equals($test_point)) {
$found_match = TRUE;
unset($other_points[$key]);
break;
}
}
if (!$found_match) {
return FALSE;
}
}
// All points match, return TRUE
return TRUE;
}
public function isSimple() {
if ($this->geos()) {
return $this->geos()->isSimple();
}
// A collection is simple if all it's components are simple
foreach ($this->components as $component) {
if (!$component->isSimple()) return FALSE;
}
return TRUE;
}
public function explode() {
$parts = array();
foreach ($this->components as $component) {
$parts = array_merge($parts, $component->explode());
}
return $parts;
}
// Not valid for this geometry type
// --------------------------------
public function x() { return NULL; }
public function y() { return NULL; }
public function startPoint() { return NULL; }
public function endPoint() { return NULL; }
public function isRing() { return NULL; }
public function isClosed() { return NULL; }
public function pointN($n) { return NULL; }
public function exteriorRing() { return NULL; }
public function numInteriorRings() { return NULL; }
public function interiorRingN($n) { return NULL; }
public function pointOnSurface() { return NULL; }
}

View file

@ -0,0 +1,347 @@
<?php
/**
* Geometry abstract class
*/
abstract class Geometry
{
private $geos = NULL;
protected $srid = NULL;
protected $geom_type;
// Abtract: Standard
// -----------------
abstract public function area();
abstract public function boundary();
abstract public function centroid();
abstract public function length();
abstract public function y();
abstract public function x();
abstract public function numGeometries();
abstract public function geometryN($n);
abstract public function startPoint();
abstract public function endPoint();
abstract public function isRing(); // Mssing dependancy
abstract public function isClosed(); // Missing dependancy
abstract public function numPoints();
abstract public function pointN($n);
abstract public function exteriorRing();
abstract public function numInteriorRings();
abstract public function interiorRingN($n);
abstract public function dimension();
abstract public function equals($geom);
abstract public function isEmpty();
abstract public function isSimple();
// Abtract: Non-Standard
// ---------------------
abstract public function getBBox();
abstract public function asArray();
abstract public function getPoints();
abstract public function explode();
abstract public function greatCircleLength(); //meters
abstract public function haversineLength(); //degrees
// Public: Standard -- Common to all geometries
// --------------------------------------------
public function SRID() {
return $this->srid;
}
public function setSRID($srid) {
if ($this->geos()) {
$this->geos()->setSRID($srid);
}
$this->srid = $srid;
}
public function envelope() {
if ($this->isEmpty()) return new Polygon();
if ($this->geos()) {
return geoPHP::geosToGeometry($this->geos()->envelope());
}
$bbox = $this->getBBox();
$points = array (
new Point($bbox['maxx'],$bbox['miny']),
new Point($bbox['maxx'],$bbox['maxy']),
new Point($bbox['minx'],$bbox['maxy']),
new Point($bbox['minx'],$bbox['miny']),
new Point($bbox['maxx'],$bbox['miny']),
);
$outer_boundary = new LineString($points);
return new Polygon(array($outer_boundary));
}
public function geometryType() {
return $this->geom_type;
}
// Public: Non-Standard -- Common to all geometries
// ------------------------------------------------
// $this->out($format, $other_args);
public function out() {
$args = func_get_args();
$format = array_shift($args);
$type_map = geoPHP::getAdapterMap();
$processor_type = $type_map[$format];
$processor = new $processor_type();
array_unshift($args, $this);
$result = call_user_func_array(array($processor, 'write'), $args);
return $result;
}
// Public: Aliases
// ---------------
public function getCentroid() {
return $this->centroid();
}
public function getArea() {
return $this->area();
}
public function getX() {
return $this->x();
}
public function getY() {
return $this->y();
}
public function getGeos() {
return $this->geos();
}
public function getGeomType() {
return $this->geometryType();
}
public function getSRID() {
return $this->SRID();
}
public function asText() {
return $this->out('wkt');
}
public function asBinary() {
return $this->out('wkb');
}
// Public: GEOS Only Functions
// ---------------------------
public function geos() {
// If it's already been set, just return it
if ($this->geos && geoPHP::geosInstalled()) {
return $this->geos;
}
// It hasn't been set yet, generate it
if (geoPHP::geosInstalled()) {
$reader = new GEOSWKBReader();
$this->geos = $reader->readHEX($this->out('wkb',TRUE));
}
else {
$this->geos = FALSE;
}
return $this->geos;
}
public function setGeos($geos) {
$this->geos = $geos;
}
public function pointOnSurface() {
if ($this->geos()) {
return geoPHP::geosToGeometry($this->geos()->pointOnSurface());
}
}
public function equalsExact(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->equalsExact($geometry->geos());
}
}
public function relate(Geometry $geometry, $pattern = NULL) {
if ($this->geos()) {
if ($pattern) {
return $this->geos()->relate($geometry->geos(), $pattern);
}
else {
return $this->geos()->relate($geometry->geos());
}
}
}
public function checkValidity() {
if ($this->geos()) {
return $this->geos()->checkValidity();
}
}
public function buffer($distance) {
if ($this->geos()) {
return geoPHP::geosToGeometry($this->geos()->buffer($distance));
}
}
public function intersection(Geometry $geometry) {
if ($this->geos()) {
return geoPHP::geosToGeometry($this->geos()->intersection($geometry->geos()));
}
}
public function convexHull() {
if ($this->geos()) {
return geoPHP::geosToGeometry($this->geos()->convexHull());
}
}
public function difference(Geometry $geometry) {
if ($this->geos()) {
return geoPHP::geosToGeometry($this->geos()->difference($geometry->geos()));
}
}
public function symDifference(Geometry $geometry) {
if ($this->geos()) {
return geoPHP::geosToGeometry($this->geos()->symDifference($geometry->geos()));
}
}
// Can pass in a geometry or an array of geometries
public function union(Geometry $geometry) {
if ($this->geos()) {
if (is_array($geometry)) {
$geom = $this->geos();
foreach ($geometry as $item) {
$geom = $geom->union($item->geos());
}
return geoPHP::geosToGeometry($geom);
}
else {
return geoPHP::geosToGeometry($this->geos()->union($geometry->geos()));
}
}
}
public function simplify($tolerance, $preserveTopology = FALSE) {
if ($this->geos()) {
return geoPHP::geosToGeometry($this->geos()->simplify($tolerance, $preserveTopology));
}
}
public function disjoint(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->disjoint($geometry->geos());
}
}
public function touches(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->touches($geometry->geos());
}
}
public function intersects(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->intersects($geometry->geos());
}
}
public function crosses(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->crosses($geometry->geos());
}
}
public function within(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->within($geometry->geos());
}
}
public function contains(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->contains($geometry->geos());
}
}
public function overlaps(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->overlaps($geometry->geos());
}
}
public function covers(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->covers($geometry->geos());
}
}
public function coveredBy(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->coveredBy($geometry->geos());
}
}
public function distance(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->distance($geometry->geos());
}
}
public function hausdorffDistance(Geometry $geometry) {
if ($this->geos()) {
return $this->geos()->hausdorffDistance($geometry->geos());
}
}
public function project(Geometry $point, $normalized = NULL) {
if ($this->geos()) {
return $this->geos()->project($point->geos(), $normalized);
}
}
// Public - Placeholders
// ---------------------
public function hasZ() {
// geoPHP does not support Z values at the moment
return FALSE;
}
public function is3D() {
// geoPHP does not support 3D geometries at the moment
return FALSE;
}
public function isMeasured() {
// geoPHP does not yet support M values
return FALSE;
}
public function coordinateDimension() {
// geoPHP only supports 2-dimensional space
return 2;
}
public function z() {
// geoPHP only supports 2-dimensional space
return NULL;
}
public function m() {
// geoPHP only supports 2-dimensional space
return NULL;
}
}

View file

@ -0,0 +1,29 @@
<?php
/**
* GeometryCollection: A heterogenous collection of geometries
*/
class GeometryCollection extends Collection
{
protected $geom_type = 'GeometryCollection';
// We need to override asArray. Because geometryCollections are heterogeneous
// we need to specify which type of geometries they contain. We need to do this
// because, for example, there would be no way to tell the difference between a
// MultiPoint or a LineString, since they share the same structure (collection
// of points). So we need to call out the type explicitly.
public function asArray() {
$array = array();
foreach ($this->components as $component) {
$array[] = array(
'type' => $component->geometryType(),
'components' => $component->asArray(),
);
}
return $array;
}
// Not valid for this geomettry
public function boundary() { return NULL; }
public function isSimple() { return NULL; }
}

View file

@ -0,0 +1,190 @@
<?php
/**
* LineString. A collection of Points representing a line.
* A line can have more than one segment.
*/
class LineString extends Collection
{
protected $geom_type = 'LineString';
/**
* Constructor
*
* @param array $points An array of at least two points with
* which to build the LineString
*/
public function __construct($points = array()) {
if (count($points) == 1) {
throw new Exception("Cannot construct a LineString with a single point");
}
// Call the Collection constructor to build the LineString
parent::__construct($points);
}
// The boundary of a linestring is itself
public function boundary() {
return $this;
}
public function startPoint() {
return $this->pointN(1);
}
public function endPoint() {
$last_n = $this->numPoints();
return $this->pointN($last_n);
}
public function isClosed() {
return ($this->startPoint()->equals($this->endPoint()));
}
public function isRing() {
return ($this->isClosed() && $this->isSimple());
}
public function numPoints() {
return $this->numGeometries();
}
public function pointN($n) {
return $this->geometryN($n);
}
public function dimension() {
if ($this->isEmpty()) return 0;
return 1;
}
public function area() {
return 0;
}
public function length() {
if ($this->geos()) {
return $this->geos()->length();
}
$length = 0;
foreach ($this->getPoints() as $delta => $point) {
$previous_point = $this->geometryN($delta);
if ($previous_point) {
$length += sqrt(pow(($previous_point->getX() - $point->getX()), 2) + pow(($previous_point->getY()- $point->getY()), 2));
}
}
return $length;
}
public function greatCircleLength($radius = 6378137) {
$length = 0;
$points = $this->getPoints();
for($i=0; $i<$this->numPoints()-1; $i++) {
$point = $points[$i];
$next_point = $points[$i+1];
if (!is_object($next_point)) {continue;}
// Great circle method
$lat1 = deg2rad($point->getY());
$lat2 = deg2rad($next_point->getY());
$lon1 = deg2rad($point->getX());
$lon2 = deg2rad($next_point->getX());
$dlon = $lon2 - $lon1;
$length +=
$radius *
atan2(
sqrt(
pow(cos($lat2) * sin($dlon), 2) +
pow(cos($lat1) * sin($lat2) - sin($lat1) * cos($lat2) * cos($dlon), 2)
)
,
sin($lat1) * sin($lat2) +
cos($lat1) * cos($lat2) * cos($dlon)
);
}
// Returns length in meters.
return $length;
}
public function haversineLength() {
$degrees = 0;
$points = $this->getPoints();
for($i=0; $i<$this->numPoints()-1; $i++) {
$point = $points[$i];
$next_point = $points[$i+1];
if (!is_object($next_point)) {continue;}
$degree = rad2deg(
acos(
sin(deg2rad($point->getY())) * sin(deg2rad($next_point->getY())) +
cos(deg2rad($point->getY())) * cos(deg2rad($next_point->getY())) *
cos(deg2rad(abs($point->getX() - $next_point->getX())))
)
);
$degrees += $degree;
}
// Returns degrees
return $degrees;
}
public function explode() {
$parts = array();
$points = $this->getPoints();
foreach ($points as $i => $point) {
if (isset($points[$i+1])) {
$parts[] = new LineString(array($point, $points[$i+1]));
}
}
return $parts;
}
public function isSimple() {
if ($this->geos()) {
return $this->geos()->isSimple();
}
$segments = $this->explode();
foreach ($segments as $i => $segment) {
foreach ($segments as $j => $check_segment) {
if ($i != $j) {
if ($segment->lineSegmentIntersect($check_segment)) {
return FALSE;
}
}
}
}
return TRUE;
}
// Utility function to check if any line sigments intersect
// Derived from http://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect
public function lineSegmentIntersect($segment) {
$p0_x = $this->startPoint()->x();
$p0_y = $this->startPoint()->y();
$p1_x = $this->endPoint()->x();
$p1_y = $this->endPoint()->y();
$p2_x = $segment->startPoint()->x();
$p2_y = $segment->startPoint()->y();
$p3_x = $segment->endPoint()->x();
$p3_y = $segment->endPoint()->y();
$s1_x = $p1_x - $p0_x; $s1_y = $p1_y - $p0_y;
$s2_x = $p3_x - $p2_x; $s2_y = $p3_y - $p2_y;
$fps = (-$s2_x * $s1_y) + ($s1_x * $s2_y);
$fpt = (-$s2_x * $s1_y) + ($s1_x * $s2_y);
if ($fps == 0 || $fpt == 0) {
return FALSE;
}
$s = (-$s1_y * ($p0_x - $p2_x) + $s1_x * ($p0_y - $p2_y)) / $fps;
$t = ( $s2_x * ($p0_y - $p2_y) - $s2_y * ($p0_x - $p2_x)) / $fpt;
if ($s > 0 && $s < 1 && $t > 0 && $t < 1) {
// Collision detected
return TRUE;
}
return FALSE;
}
}

View file

@ -0,0 +1,20 @@
<?php
/**
* MultiLineString: A collection of LineStrings
*/
class MultiLineString extends Collection
{
protected $geom_type = 'MultiLineString';
// MultiLineString is closed if all it's components are closed
public function isClosed() {
foreach ($this->components as $line) {
if (!$line->isClosed()) {
return FALSE;
}
}
return TRUE;
}
}

View file

@ -0,0 +1,21 @@
<?php
/**
* MultiPoint: A collection Points
*/
class MultiPoint extends Collection
{
protected $geom_type = 'MultiPoint';
public function numPoints() {
return $this->numGeometries();
}
public function isSimple() {
return TRUE;
}
// Not valid for this geometry type
// --------------------------------
public function explode() { return NULL; }
}

View file

@ -0,0 +1,8 @@
<?php
/**
* MultiPolygon: A collection of Polygons
*/
class MultiPolygon extends Collection
{
protected $geom_type = 'MultiPolygon';
}

View file

@ -0,0 +1,179 @@
<?php
/**
* Point: The most basic geometry type. All other geometries
* are built out of Points.
*/
class Point extends Geometry
{
public $coords = array(2);
protected $geom_type = 'Point';
protected $dimension = 2;
/**
* Constructor
*
* @param numeric $x The x coordinate (or longitude)
* @param numeric $y The y coordinate (or latitude)
* @param numeric $z The z coordinate (or altitude) - optional
*/
public function __construct($x = NULL, $y = NULL, $z = NULL) {
// Check if it's an empty point
if ($x === NULL && $y === NULL) {
$this->coords = array(NULL, NULL);
$this->dimension = 0;
return;
}
// Basic validation on x and y
if (!is_numeric($x) || !is_numeric($y)) {
throw new Exception("Cannot construct Point. x and y should be numeric");
}
// Check to see if this is a 3D point
if ($z !== NULL) {
if (!is_numeric($z)) {
throw new Exception("Cannot construct Point. z should be numeric");
}
$this->dimension = 3;
}
// Convert to floatval in case they are passed in as a string or integer etc.
$x = floatval($x);
$y = floatval($y);
$z = floatval($z);
// Add poitional elements
if ($this->dimension == 2) {
$this->coords = array($x, $y);
}
if ($this->dimension == 3) {
$this->coords = array($x, $y, $z);
}
}
/**
* Get X (longitude) coordinate
*
* @return float The X coordinate
*/
public function x() {
return $this->coords[0];
}
/**
* Returns Y (latitude) coordinate
*
* @return float The Y coordinate
*/
public function y() {
return $this->coords[1];
}
/**
* Returns Z (altitude) coordinate
*
* @return float The Z coordinate or NULL is not a 3D point
*/
public function z() {
if ($this->dimension == 3) {
return $this->coords[2];
}
else return NULL;
}
// A point's centroid is itself
public function centroid() {
return $this;
}
public function getBBox() {
return array(
'maxy' => $this->getY(),
'miny' => $this->getY(),
'maxx' => $this->getX(),
'minx' => $this->getX(),
);
}
public function asArray($assoc = FALSE) {
return $this->coords;
}
public function area() {
return 0;
}
public function length() {
return 0;
}
public function greatCircleLength() {
return 0;
}
public function haversineLength() {
return 0;
}
// The boundary of a point is itself
public function boundary() {
return $this;
}
public function dimension() {
return 0;
}
public function isEmpty() {
if ($this->dimension == 0) {
return TRUE;
}
else {
return FALSE;
}
}
public function numPoints() {
return 1;
}
public function getPoints() {
return array($this);
}
public function equals($geometry) {
if (get_class($geometry) != 'Point') {
return FALSE;
}
if (!$this->isEmpty() && !$geometry->isEmpty()) {
return ($this->x() == $geometry->x() && $this->y() == $geometry->y());
}
else if ($this->isEmpty() && $geometry->isEmpty()) {
return TRUE;
}
else {
return FALSE;
}
}
public function isSimple() {
return TRUE;
}
// Not valid for this geometry type
public function numGeometries() { return NULL; }
public function geometryN($n) { return NULL; }
public function startPoint() { return NULL; }
public function endPoint() { return NULL; }
public function isRing() { return NULL; }
public function isClosed() { return NULL; }
public function pointN($n) { return NULL; }
public function exteriorRing() { return NULL; }
public function numInteriorRings() { return NULL; }
public function interiorRingN($n) { return NULL; }
public function pointOnSurface() { return NULL; }
public function explode() { return NULL; }
}

View file

@ -0,0 +1,215 @@
<?php
/**
* Polygon: A polygon is a plane figure that is bounded by a closed path,
* composed of a finite sequence of straight line segments
*/
class Polygon extends Collection
{
protected $geom_type = 'Polygon';
// The boundary of a polygin is it's outer ring
public function boundary() {
return $this->exteriorRing();
}
public function area($exterior_only = FALSE, $signed = FALSE) {
if ($this->isEmpty()) return 0;
if ($this->geos() && $exterior_only == FALSE) {
return $this->geos()->area();
}
$exterior_ring = $this->components[0];
$pts = $exterior_ring->getComponents();
$c = count($pts);
if((int)$c == '0') return NULL;
$a = '0';
foreach($pts as $k => $p){
$j = ($k + 1) % $c;
$a = $a + ($p->getX() * $pts[$j]->getY()) - ($p->getY() * $pts[$j]->getX());
}
if ($signed) $area = ($a / 2);
else $area = abs(($a / 2));
if ($exterior_only == TRUE) {
return $area;
}
foreach ($this->components as $delta => $component) {
if ($delta != 0) {
$inner_poly = new Polygon(array($component));
$area -= $inner_poly->area();
}
}
return $area;
}
public function centroid() {
if ($this->isEmpty()) return NULL;
if ($this->geos()) {
return geoPHP::geosToGeometry($this->geos()->centroid());
}
$exterior_ring = $this->components[0];
$pts = $exterior_ring->getComponents();
$c = count($pts);
if((int)$c == '0') return NULL;
$cn = array('x' => '0', 'y' => '0');
$a = $this->area(TRUE, TRUE);
// If this is a polygon with no area. Just return the first point.
if ($a == 0) {
return $this->exteriorRing()->pointN(1);
}
foreach($pts as $k => $p){
$j = ($k + 1) % $c;
$P = ($p->getX() * $pts[$j]->getY()) - ($p->getY() * $pts[$j]->getX());
$cn['x'] = $cn['x'] + ($p->getX() + $pts[$j]->getX()) * $P;
$cn['y'] = $cn['y'] + ($p->getY() + $pts[$j]->getY()) * $P;
}
$cn['x'] = $cn['x'] / ( 6 * $a);
$cn['y'] = $cn['y'] / ( 6 * $a);
$centroid = new Point($cn['x'], $cn['y']);
return $centroid;
}
/**
* Find the outermost point from the centroid
*
* @returns Point The outermost point
*/
public function outermostPoint() {
$centroid = $this->getCentroid();
$max = array('length' => 0, 'point' => null);
foreach($this->getPoints() as $point) {
$lineString = new LineString(array($centroid, $point));
if($lineString->length() > $max['length']) {
$max['length'] = $lineString->length();
$max['point'] = $point;
}
}
return $max['point'];
}
public function exteriorRing() {
if ($this->isEmpty()) return new LineString();
return $this->components[0];
}
public function numInteriorRings() {
if ($this->isEmpty()) return 0;
return $this->numGeometries()-1;
}
public function interiorRingN($n) {
return $this->geometryN($n+1);
}
public function dimension() {
if ($this->isEmpty()) return 0;
return 2;
}
public function isSimple() {
if ($this->geos()) {
return $this->geos()->isSimple();
}
$segments = $this->explode();
foreach ($segments as $i => $segment) {
foreach ($segments as $j => $check_segment) {
if ($i != $j) {
if ($segment->lineSegmentIntersect($check_segment)) {
return FALSE;
}
}
}
}
return TRUE;
}
/**
* For a given point, determine whether it's bounded by the given polygon.
* Adapted from http://www.assemblysys.com/dataServices/php_pointinpolygon.php
* @see http://en.wikipedia.org/wiki/Point%5Fin%5Fpolygon
*
* @param Point $point
* @param boolean $pointOnBoundary - whether a boundary should be considered "in" or not
* @param boolean $pointOnVertex - whether a vertex should be considered "in" or not
* @return boolean
*/
public function pointInPolygon($point, $pointOnBoundary = true, $pointOnVertex = true) {
$vertices = $this->getPoints();
// Check if the point sits exactly on a vertex
if ($this->pointOnVertex($point, $vertices)) {
return $pointOnVertex ? TRUE : FALSE;
}
// Check if the point is inside the polygon or on the boundary
$intersections = 0;
$vertices_count = count($vertices);
for ($i=1; $i < $vertices_count; $i++) {
$vertex1 = $vertices[$i-1];
$vertex2 = $vertices[$i];
if ($vertex1->y() == $vertex2->y()
&& $vertex1->y() == $point->y()
&& $point->x() > min($vertex1->x(), $vertex2->x())
&& $point->x() < max($vertex1->x(), $vertex2->x())) {
// Check if point is on an horizontal polygon boundary
return $pointOnBoundary ? TRUE : FALSE;
}
if ($point->y() > min($vertex1->y(), $vertex2->y())
&& $point->y() <= max($vertex1->y(), $vertex2->y())
&& $point->x() <= max($vertex1->x(), $vertex2->x())
&& $vertex1->y() != $vertex2->y()) {
$xinters =
($point->y() - $vertex1->y()) * ($vertex2->x() - $vertex1->x())
/ ($vertex2->y() - $vertex1->y())
+ $vertex1->x();
if ($xinters == $point->x()) {
// Check if point is on the polygon boundary (other than horizontal)
return $pointOnBoundary ? TRUE : FALSE;
}
if ($vertex1->x() == $vertex2->x() || $point->x() <= $xinters) {
$intersections++;
}
}
}
// If the number of edges we passed through is even, then it's in the polygon.
if ($intersections % 2 != 0) {
return TRUE;
}
else {
return FALSE;
}
}
public function pointOnVertex($point) {
foreach($this->getPoints() as $vertex) {
if ($point->equals($vertex)) {
return true;
}
}
}
// Not valid for this geometry type
// --------------------------------
public function length() { return NULL; }
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1 @@
POLYGON EMPTY

View file

@ -0,0 +1,219 @@
<gpx creator="GPS Visualizer http://www.gpsvisualizer.com/" version="1.0">
<wpt lat="45.44283" lon="-121.72904"><ele>1374</ele><name>Vista Ridge Trailhead</name><sym>Trail Head</sym></wpt>
<wpt lat="45.41000" lon="-121.71349"><ele>1777</ele><name>Wy'East Basin</name></wpt>
<wpt lat="45.41124" lon="-121.70404"><ele>1823</ele><name>Dollar Lake</name></wpt>
<wpt lat="45.39260" lon="-121.69937"><ele>2394</ele><name>Barrett Spur</name><sym>Summit</sym></wpt>
<trk>
<name>Barrett Spur 1</name>
<trkseg>
<trkpt lat="45.4431641" lon="-121.7295456"></trkpt>
<trkpt lat="45.4428615" lon="-121.7290800"></trkpt>
<trkpt lat="45.4425697" lon="-121.7279085"></trkpt>
<trkpt lat="45.4424274" lon="-121.7267360"></trkpt>
<trkpt lat="45.4422017" lon="-121.7260429"></trkpt>
<trkpt lat="45.4416576" lon="-121.7252347"></trkpt>
<trkpt lat="45.4406144" lon="-121.7241181"></trkpt>
<trkpt lat="45.4398193" lon="-121.7224890"></trkpt>
<trkpt lat="45.4387649" lon="-121.7226112"></trkpt>
<trkpt lat="45.4383933" lon="-121.7224328"></trkpt>
<trkpt lat="45.4377850" lon="-121.7224159"></trkpt>
<trkpt lat="45.4372204" lon="-121.7226603"></trkpt>
<trkpt lat="45.4347837" lon="-121.7226007"></trkpt>
<trkpt lat="45.4332000" lon="-121.7216480"></trkpt>
<trkpt lat="45.4334576" lon="-121.7223143"></trkpt>
<trkpt lat="45.4321730" lon="-121.7222102"></trkpt>
<trkpt lat="45.4316609" lon="-121.7219974"></trkpt>
<trkpt lat="45.4303068" lon="-121.7220616"></trkpt>
<trkpt lat="45.4270753" lon="-121.7209685"></trkpt>
<trkpt lat="45.4267610" lon="-121.7211872"></trkpt>
<trkpt lat="45.4260133" lon="-121.7212623"></trkpt>
<trkpt lat="45.4257683" lon="-121.7214738"></trkpt>
<trkpt lat="45.4257400" lon="-121.7217762"></trkpt>
<trkpt lat="45.4259485" lon="-121.7226009"></trkpt>
<trkpt lat="45.4249972" lon="-121.7223672"></trkpt>
<trkpt lat="45.4246035" lon="-121.7219816"></trkpt>
<trkpt lat="45.4238682" lon="-121.7219830"></trkpt>
<trkpt lat="45.4226721" lon="-121.7216494"></trkpt>
<trkpt lat="45.4224120" lon="-121.7217998"></trkpt>
<trkpt lat="45.4211497" lon="-121.7218767"></trkpt>
<trkpt lat="45.4193319" lon="-121.7208650"></trkpt>
<trkpt lat="45.4186435" lon="-121.7202956"></trkpt>
<trkpt lat="45.4185934" lon="-121.7200745"></trkpt>
<trkpt lat="45.4178963" lon="-121.7196035"></trkpt>
<trkpt lat="45.4171101" lon="-121.7198115"></trkpt>
<trkpt lat="45.4166827" lon="-121.7193250"></trkpt>
<trkpt lat="45.4161855" lon="-121.7190778"></trkpt>
<trkpt lat="45.4159291" lon="-121.7193146"></trkpt>
<trkpt lat="45.4153644" lon="-121.7193939"></trkpt>
<trkpt lat="45.4151268" lon="-121.7191578"></trkpt>
<trkpt lat="45.4148071" lon="-121.7191043"></trkpt>
<trkpt lat="45.4146310" lon="-121.7187962"></trkpt>
<trkpt lat="45.4142524" lon="-121.7187236"></trkpt>
<trkpt lat="45.4142844" lon="-121.7185595"></trkpt>
<trkpt lat="45.4133520" lon="-121.7180429"></trkpt>
<trkpt lat="45.4131406" lon="-121.7181383"></trkpt>
<trkpt lat="45.4130356" lon="-121.7179036"></trkpt>
<trkpt lat="45.4118436" lon="-121.7168789"></trkpt>
<trkpt lat="45.4109205" lon="-121.7156569"></trkpt>
<trkpt lat="45.4104523" lon="-121.7145250"></trkpt>
<trkpt lat="45.4104930" lon="-121.7143814"></trkpt>
<trkpt lat="45.4102075" lon="-121.7140608"></trkpt>
<trkpt lat="45.4099806" lon="-121.7134527"></trkpt>
</trkseg>
<trkseg>
<trkpt lat="45.4099792" lon="-121.7134610"></trkpt>
<trkpt lat="45.4091489" lon="-121.7134937"></trkpt>
<trkpt lat="45.4086133" lon="-121.7132504"></trkpt>
<trkpt lat="45.4080616" lon="-121.7127670"></trkpt>
<trkpt lat="45.4076426" lon="-121.7126047"></trkpt>
<trkpt lat="45.4075043" lon="-121.7122301"></trkpt>
<trkpt lat="45.4070652" lon="-121.7118980"></trkpt>
<trkpt lat="45.4068712" lon="-121.7114766"></trkpt>
<trkpt lat="45.4067987" lon="-121.7108634"></trkpt>
<trkpt lat="45.4064528" lon="-121.7106934"></trkpt>
<trkpt lat="45.4057286" lon="-121.7110326"></trkpt>
<trkpt lat="45.4056813" lon="-121.7108280"></trkpt>
<trkpt lat="45.4055566" lon="-121.7109216"></trkpt>
<trkpt lat="45.4047244" lon="-121.7093884"></trkpt>
<trkpt lat="45.4039059" lon="-121.7083824"></trkpt>
<trkpt lat="45.4037176" lon="-121.7077738"></trkpt>
<trkpt lat="45.4034533" lon="-121.7074489"></trkpt>
<trkpt lat="45.4026499" lon="-121.7071945"></trkpt>
<trkpt lat="45.4019737" lon="-121.7067004"></trkpt>
<trkpt lat="45.4018086" lon="-121.7067477"></trkpt>
<trkpt lat="45.4014084" lon="-121.7063918"></trkpt>
<trkpt lat="45.4013177" lon="-121.7059701"></trkpt>
<trkpt lat="45.4011965" lon="-121.7058914"></trkpt>
<trkpt lat="45.4010688" lon="-121.7053257"></trkpt>
<trkpt lat="45.4008116" lon="-121.7054978"></trkpt>
<trkpt lat="45.4006075" lon="-121.7053495"></trkpt>
<trkpt lat="45.4005546" lon="-121.7054856"></trkpt>
<trkpt lat="45.3991622" lon="-121.7049765"></trkpt>
<trkpt lat="45.3985560" lon="-121.7042976"></trkpt>
<trkpt lat="45.3981831" lon="-121.7042260"></trkpt>
<trkpt lat="45.3973151" lon="-121.7036992"></trkpt>
<trkpt lat="45.3967974" lon="-121.7036370"></trkpt>
<trkpt lat="45.3963985" lon="-121.7033742"></trkpt>
<trkpt lat="45.3945456" lon="-121.7029688"></trkpt>
<trkpt lat="45.3920595" lon="-121.7015918"></trkpt>
<trkpt lat="45.3907614" lon="-121.7012029"></trkpt>
<trkpt lat="45.3906454" lon="-121.7010483"></trkpt>
<trkpt lat="45.3906726" lon="-121.7008185"></trkpt>
<trkpt lat="45.3909774" lon="-121.7008263"></trkpt>
<trkpt lat="45.3911315" lon="-121.7004300"></trkpt>
<trkpt lat="45.3909963" lon="-121.6998193"></trkpt>
<trkpt lat="45.3908688" lon="-121.6997923"></trkpt>
<trkpt lat="45.3917895" lon="-121.6994679"></trkpt>
<trkpt lat="45.3926205" lon="-121.6994847"></trkpt>
<trkpt lat="45.3925915" lon="-121.6992485"></trkpt>
<trkpt lat="45.3928117" lon="-121.6995661"></trkpt>
</trkseg>
</trk>
<trk>
<name>Barrett Spur 2</name>
<trkseg>
<trkpt lat="45.3928201" lon="-121.6995658"></trkpt>
<trkpt lat="45.3935449" lon="-121.6998805"></trkpt>
<trkpt lat="45.3937897" lon="-121.6997710"></trkpt>
<trkpt lat="45.3941789" lon="-121.6999492"></trkpt>
<trkpt lat="45.3942372" lon="-121.7001375"></trkpt>
<trkpt lat="45.3946353" lon="-121.6999452"></trkpt>
<trkpt lat="45.3953599" lon="-121.7005823"></trkpt>
<trkpt lat="45.3957081" lon="-121.7006533"></trkpt>
<trkpt lat="45.3964324" lon="-121.7016813"></trkpt>
<trkpt lat="45.3965766" lon="-121.7016905"></trkpt>
<trkpt lat="45.3969060" lon="-121.7028225"></trkpt>
<trkpt lat="45.3968739" lon="-121.7033856"></trkpt>
<trkpt lat="45.3974854" lon="-121.7040597"></trkpt>
<trkpt lat="45.3986110" lon="-121.7044455"></trkpt>
<trkpt lat="45.3993308" lon="-121.7050832"></trkpt>
<trkpt lat="45.4006454" lon="-121.7055117"></trkpt>
<trkpt lat="45.4017924" lon="-121.7049952"></trkpt>
<trkpt lat="45.4028690" lon="-121.7048065"></trkpt>
<trkpt lat="45.4055213" lon="-121.7056599"></trkpt>
<trkpt lat="45.4055606" lon="-121.7058477"></trkpt>
</trkseg>
<trkseg>
<trkpt lat="45.4055556" lon="-121.7058619"></trkpt>
<trkpt lat="45.4057016" lon="-121.7055424"></trkpt>
<trkpt lat="45.4064672" lon="-121.7058247"></trkpt>
<trkpt lat="45.4065550" lon="-121.7056490"></trkpt>
<trkpt lat="45.4081392" lon="-121.7055042"></trkpt>
<trkpt lat="45.4084785" lon="-121.7052201"></trkpt>
<trkpt lat="45.4089125" lon="-121.7053029"></trkpt>
<trkpt lat="45.4097597" lon="-121.7050730"></trkpt>
<trkpt lat="45.4098359" lon="-121.7049047"></trkpt>
<trkpt lat="45.4101859" lon="-121.7049419"></trkpt>
<trkpt lat="45.4109946" lon="-121.7045409"></trkpt>
<trkpt lat="45.4110654" lon="-121.7040909"></trkpt>
<trkpt lat="45.4113353" lon="-121.7039421"></trkpt>
<trkpt lat="45.4119105" lon="-121.7047169"></trkpt>
<trkpt lat="45.4120297" lon="-121.7046115"></trkpt>
<trkpt lat="45.4123835" lon="-121.7049762"></trkpt>
<trkpt lat="45.4125020" lon="-121.7053677"></trkpt>
<trkpt lat="45.4134357" lon="-121.7051916"></trkpt>
<trkpt lat="45.4135832" lon="-121.7046182"></trkpt>
<trkpt lat="45.4139565" lon="-121.7044171"></trkpt>
<trkpt lat="45.4140658" lon="-121.7041636"></trkpt>
<trkpt lat="45.4145098" lon="-121.7041176"></trkpt>
<trkpt lat="45.4141414" lon="-121.7043045"></trkpt>
<trkpt lat="45.4141558" lon="-121.7050125"></trkpt>
<trkpt lat="45.4136095" lon="-121.7071948"></trkpt>
<trkpt lat="45.4126067" lon="-121.7080044"></trkpt>
<trkpt lat="45.4122181" lon="-121.7088539"></trkpt>
<trkpt lat="45.4124283" lon="-121.7092346"></trkpt>
<trkpt lat="45.4119295" lon="-121.7101625"></trkpt>
<trkpt lat="45.4124117" lon="-121.7104037"></trkpt>
<trkpt lat="45.4122553" lon="-121.7107970"></trkpt>
<trkpt lat="45.4116919" lon="-121.7107601"></trkpt>
<trkpt lat="45.4116619" lon="-121.7110571"></trkpt>
<trkpt lat="45.4113536" lon="-121.7114942"></trkpt>
<trkpt lat="45.4114186" lon="-121.7117619"></trkpt>
<trkpt lat="45.4110215" lon="-121.7125886"></trkpt>
<trkpt lat="45.4106014" lon="-121.7125816"></trkpt>
<trkpt lat="45.4104916" lon="-121.7129590"></trkpt>
<trkpt lat="45.4102544" lon="-121.7130066"></trkpt>
<trkpt lat="45.4099714" lon="-121.7134279"></trkpt>
</trkseg>
<trkseg>
<trkpt lat="45.4099747" lon="-121.7134529"></trkpt>
<trkpt lat="45.4110685" lon="-121.7158641"></trkpt>
<trkpt lat="45.4121873" lon="-121.7171940"></trkpt>
<trkpt lat="45.4131063" lon="-121.7179663"></trkpt>
<trkpt lat="45.4146646" lon="-121.7186587"></trkpt>
<trkpt lat="45.4147872" lon="-121.7190281"></trkpt>
<trkpt lat="45.4153143" lon="-121.7192079"></trkpt>
<trkpt lat="45.4153716" lon="-121.7193714"></trkpt>
<trkpt lat="45.4164891" lon="-121.7190904"></trkpt>
<trkpt lat="45.4172221" lon="-121.7196833"></trkpt>
<trkpt lat="45.4179416" lon="-121.7195244"></trkpt>
<trkpt lat="45.4185782" lon="-121.7197987"></trkpt>
<trkpt lat="45.4193540" lon="-121.7207025"></trkpt>
<trkpt lat="45.4214007" lon="-121.7218387"></trkpt>
<trkpt lat="45.4226606" lon="-121.7215644"></trkpt>
<trkpt lat="45.4247590" lon="-121.7218690"></trkpt>
<trkpt lat="45.4249036" lon="-121.7221738"></trkpt>
<trkpt lat="45.4259458" lon="-121.7225690"></trkpt>
<trkpt lat="45.4257020" lon="-121.7216118"></trkpt>
<trkpt lat="45.4260738" lon="-121.7212258"></trkpt>
<trkpt lat="45.4272087" lon="-121.7208974"></trkpt>
<trkpt lat="45.4277253" lon="-121.7209468"></trkpt>
<trkpt lat="45.4283981" lon="-121.7213890"></trkpt>
<trkpt lat="45.4288768" lon="-121.7213453"></trkpt>
<trkpt lat="45.4301857" lon="-121.7219605"></trkpt>
<trkpt lat="45.4312165" lon="-121.7219340"></trkpt>
<trkpt lat="45.4334856" lon="-121.7222528"></trkpt>
<trkpt lat="45.4331572" lon="-121.7216508"></trkpt>
<trkpt lat="45.4336070" lon="-121.7217366"></trkpt>
<trkpt lat="45.4350551" lon="-121.7225997"></trkpt>
<trkpt lat="45.4371233" lon="-121.7226122"></trkpt>
<trkpt lat="45.4378561" lon="-121.7223631"></trkpt>
<trkpt lat="45.4387304" lon="-121.7225545"></trkpt>
<trkpt lat="45.4397525" lon="-121.7223926"></trkpt>
<trkpt lat="45.4407832" lon="-121.7243251"></trkpt>
<trkpt lat="45.4422796" lon="-121.7260896"></trkpt>
<trkpt lat="45.4428882" lon="-121.7291117"></trkpt>
<trkpt lat="45.4431708" lon="-121.7295917"></trkpt>
</trkseg>
</trk>
</gpx>

View file

@ -0,0 +1,915 @@
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>KML Samples</name>
<open>1</open>
<description>Unleash your creativity with the help of these examples!</description>
<Style id="downArrowIcon">
<IconStyle>
<Icon>
<href>http://maps.google.com/mapfiles/kml/pal4/icon28.png</href>
</Icon>
</IconStyle>
</Style>
<Style id="globeIcon">
<IconStyle>
<Icon>
<href>http://maps.google.com/mapfiles/kml/pal3/icon19.png</href>
</Icon>
</IconStyle>
<LineStyle>
<width>2</width>
</LineStyle>
</Style>
<Style id="transPurpleLineGreenPoly">
<LineStyle>
<color>7fff00ff</color>
<width>4</width>
</LineStyle>
<PolyStyle>
<color>7f00ff00</color>
</PolyStyle>
</Style>
<Style id="yellowLineGreenPoly">
<LineStyle>
<color>7f00ffff</color>
<width>4</width>
</LineStyle>
<PolyStyle>
<color>7f00ff00</color>
</PolyStyle>
</Style>
<Style id="thickBlackLine">
<LineStyle>
<color>87000000</color>
<width>10</width>
</LineStyle>
</Style>
<Style id="redLineBluePoly">
<LineStyle>
<color>ff0000ff</color>
</LineStyle>
<PolyStyle>
<color>ffff0000</color>
</PolyStyle>
</Style>
<Style id="blueLineRedPoly">
<LineStyle>
<color>ffff0000</color>
</LineStyle>
<PolyStyle>
<color>ff0000ff</color>
</PolyStyle>
</Style>
<Style id="transRedPoly">
<LineStyle>
<width>1.5</width>
</LineStyle>
<PolyStyle>
<color>7d0000ff</color>
</PolyStyle>
</Style>
<Style id="transBluePoly">
<LineStyle>
<width>1.5</width>
</LineStyle>
<PolyStyle>
<color>7dff0000</color>
</PolyStyle>
</Style>
<Style id="transGreenPoly">
<LineStyle>
<width>1.5</width>
</LineStyle>
<PolyStyle>
<color>7d00ff00</color>
</PolyStyle>
</Style>
<Style id="transYellowPoly">
<LineStyle>
<width>1.5</width>
</LineStyle>
<PolyStyle>
<color>7d00ffff</color>
</PolyStyle>
</Style>
<Style id="noDrivingDirections">
<BalloonStyle>
<text><![CDATA[
<b>$[name]</b>
<br /><br />
$[description]
]]></text>
</BalloonStyle>
</Style>
<Folder>
<name>Placemarks</name>
<description>These are just some of the different kinds of placemarks with
which you can mark your favorite places</description>
<LookAt>
<longitude>-122.0839597145766</longitude>
<latitude>37.42222904525232</latitude>
<altitude>0</altitude>
<heading>-148.4122922628044</heading>
<tilt>40.5575073395506</tilt>
<range>500.6566641072245</range>
</LookAt>
<Placemark>
<name>Simple placemark</name>
<description>Attached to the ground. Intelligently places itself at the
height of the underlying terrain.</description>
<Point>
<coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
</Point>
</Placemark>
<Placemark>
<name>Floating placemark</name>
<visibility>0</visibility>
<description>Floats a defined distance above the ground.</description>
<LookAt>
<longitude>-122.0839597145766</longitude>
<latitude>37.42222904525232</latitude>
<altitude>0</altitude>
<heading>-148.4122922628044</heading>
<tilt>40.5575073395506</tilt>
<range>500.6566641072245</range>
</LookAt>
<styleUrl>#downArrowIcon</styleUrl>
<Point>
<altitudeMode>relativeToGround</altitudeMode>
<coordinates>-122.084075,37.4220033612141,50</coordinates>
</Point>
</Placemark>
<Placemark>
<name>Extruded placemark</name>
<visibility>0</visibility>
<description>Tethered to the ground by a customizable
&quot;tail&quot;</description>
<LookAt>
<longitude>-122.0845787421525</longitude>
<latitude>37.42215078737763</latitude>
<altitude>0</altitude>
<heading>-148.4126684946234</heading>
<tilt>40.55750733918048</tilt>
<range>365.2646606980322</range>
</LookAt>
<styleUrl>#globeIcon</styleUrl>
<Point>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<coordinates>-122.0857667006183,37.42156927867553,50</coordinates>
</Point>
</Placemark>
</Folder>
<Folder>
<name>Styles and Markup</name>
<visibility>0</visibility>
<description>With KML it is easy to create rich, descriptive markup to
annotate and enrich your placemarks</description>
<LookAt>
<longitude>-122.0845787422371</longitude>
<latitude>37.42215078726837</latitude>
<altitude>0</altitude>
<heading>-148.4126777488172</heading>
<tilt>40.55750733930874</tilt>
<range>365.2646826292919</range>
</LookAt>
<styleUrl>#noDrivingDirections</styleUrl>
<Document>
<name>Highlighted Icon</name>
<visibility>0</visibility>
<description>Place your mouse over the icon to see it display the new
icon</description>
<LookAt>
<longitude>-122.0856552124024</longitude>
<latitude>37.4224281311035</latitude>
<altitude>0</altitude>
<heading>0</heading>
<tilt>0</tilt>
<range>265.8520424250024</range>
</LookAt>
<Style id="highlightPlacemark">
<IconStyle>
<Icon>
<href>http://maps.google.com/mapfiles/kml/paddle/red-stars.png</href>
</Icon>
</IconStyle>
</Style>
<Style id="normalPlacemark">
<IconStyle>
<Icon>
<href>http://maps.google.com/mapfiles/kml/paddle/wht-blank.png</href>
</Icon>
</IconStyle>
</Style>
<StyleMap id="exampleStyleMap">
<Pair>
<key>normal</key>
<styleUrl>#normalPlacemark</styleUrl>
</Pair>
<Pair>
<key>highlight</key>
<styleUrl>#highlightPlacemark</styleUrl>
</Pair>
</StyleMap>
<Placemark>
<name>Roll over this icon</name>
<visibility>0</visibility>
<styleUrl>#exampleStyleMap</styleUrl>
<Point>
<coordinates>-122.0856545755255,37.42243077405461,0</coordinates>
</Point>
</Placemark>
</Document>
<Placemark>
<name>Descriptive HTML</name>
<visibility>0</visibility>
<description><![CDATA[Click on the blue link!<br><br>
Placemark descriptions can be enriched by using many standard HTML tags.<br>
For example:
<hr>
Styles:<br>
<i>Italics</i>,
<b>Bold</b>,
<u>Underlined</u>,
<s>Strike Out</s>,
subscript<sub>subscript</sub>,
superscript<sup>superscript</sup>,
<big>Big</big>,
<small>Small</small>,
<tt>Typewriter</tt>,
<em>Emphasized</em>,
<strong>Strong</strong>,
<code>Code</code>
<hr>
Fonts:<br>
<font color="red">red by name</font>,
<font color="#408010">leaf green by hexadecimal RGB</font>
<br>
<font size=1>size 1</font>,
<font size=2>size 2</font>,
<font size=3>size 3</font>,
<font size=4>size 4</font>,
<font size=5>size 5</font>,
<font size=6>size 6</font>,
<font size=7>size 7</font>
<br>
<font face=times>Times</font>,
<font face=verdana>Verdana</font>,
<font face=arial>Arial</font><br>
<hr>
Links:
<br>
<a href="http://earth.google.com/">Google Earth!</a>
<br>
or: Check out our website at www.google.com
<hr>
Alignment:<br>
<p align=left>left</p>
<p align=center>center</p>
<p align=right>right</p>
<hr>
Ordered Lists:<br>
<ol><li>First</li><li>Second</li><li>Third</li></ol>
<ol type="a"><li>First</li><li>Second</li><li>Third</li></ol>
<ol type="A"><li>First</li><li>Second</li><li>Third</li></ol>
<hr>
Unordered Lists:<br>
<ul><li>A</li><li>B</li><li>C</li></ul>
<ul type="circle"><li>A</li><li>B</li><li>C</li></ul>
<ul type="square"><li>A</li><li>B</li><li>C</li></ul>
<hr>
Definitions:<br>
<dl>
<dt>Google:</dt><dd>The best thing since sliced bread</dd>
</dl>
<hr>
Centered:<br><center>
Time present and time past<br>
Are both perhaps present in time future,<br>
And time future contained in time past.<br>
If all time is eternally present<br>
All time is unredeemable.<br>
</center>
<hr>
Block Quote:
<br>
<blockquote>
We shall not cease from exploration<br>
And the end of all our exploring<br>
Will be to arrive where we started<br>
And know the place for the first time.<br>
<i>-- T.S. Eliot</i>
</blockquote>
<br>
<hr>
Headings:<br>
<h1>Header 1</h1>
<h2>Header 2</h2>
<h3>Header 3</h3>
<h3>Header 4</h4>
<h3>Header 5</h5>
<hr>
Images:<br>
<i>Remote image</i><br>
<img src="http://code.google.com/apis/kml/documentation/googleSample.png"><br>
<i>Scaled image</i><br>
<img src="http://code.google.com/apis/kml/documentation/googleSample.png" width=100><br>
<hr>
Simple Tables:<br>
<table border="1" padding="1">
<tr><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td></tr>
<tr><td>a</td><td>b</td><td>c</td><td>d</td><td>e</td></tr>
</table>
<br>
[Did you notice that double-clicking on the placemark doesn't cause the viewer to take you anywhere? This is because it is possible to directly author a "placeless placemark". If you look at the code for this example, you will see that it has neither a point coordinate nor a LookAt element.]]]></description>
</Placemark>
</Folder>
<Folder>
<name>Ground Overlays</name>
<visibility>0</visibility>
<description>Examples of ground overlays</description>
<GroundOverlay>
<name>Large-scale overlay on terrain</name>
<visibility>0</visibility>
<description>Overlay shows Mount Etna erupting on July 13th, 2001.</description>
<LookAt>
<longitude>15.02468937557116</longitude>
<latitude>37.67395167941667</latitude>
<altitude>0</altitude>
<heading>-16.5581842842829</heading>
<tilt>58.31228652890705</tilt>
<range>30350.36838438907</range>
</LookAt>
<Icon>
<href>http://code.google.com/apis/kml/documentation/etna.jpg</href>
</Icon>
<LatLonBox>
<north>37.91904192681665</north>
<south>37.46543388598137</south>
<east>15.35832653742206</east>
<west>14.60128369746704</west>
<rotation>-0.1556640799496235</rotation>
</LatLonBox>
</GroundOverlay>
</Folder>
<Folder>
<name>Screen Overlays</name>
<visibility>0</visibility>
<description>Screen overlays have to be authored directly in KML. These
examples illustrate absolute and dynamic positioning in screen space.</description>
<ScreenOverlay>
<name>Simple crosshairs</name>
<visibility>0</visibility>
<description>This screen overlay uses fractional positioning to put the
image in the exact center of the screen</description>
<Icon>
<href>http://code.google.com/apis/kml/documentation/crosshairs.png</href>
</Icon>
<overlayXY x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
<screenXY x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
<rotationXY x="0.5" y="0.5" xunits="fraction" yunits="fraction"/>
<size x="0" y="0" xunits="pixels" yunits="pixels"/>
</ScreenOverlay>
<ScreenOverlay>
<name>Absolute Positioning: Top left</name>
<visibility>0</visibility>
<Icon>
<href>http://code.google.com/apis/kml/documentation/top_left.jpg</href>
</Icon>
<overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/>
<screenXY x="0" y="1" xunits="fraction" yunits="fraction"/>
<rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
<size x="0" y="0" xunits="fraction" yunits="fraction"/>
</ScreenOverlay>
<ScreenOverlay>
<name>Absolute Positioning: Top right</name>
<visibility>0</visibility>
<Icon>
<href>http://code.google.com/apis/kml/documentation/top_right.jpg</href>
</Icon>
<overlayXY x="1" y="1" xunits="fraction" yunits="fraction"/>
<screenXY x="1" y="1" xunits="fraction" yunits="fraction"/>
<rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
<size x="0" y="0" xunits="fraction" yunits="fraction"/>
</ScreenOverlay>
<ScreenOverlay>
<name>Absolute Positioning: Bottom left</name>
<visibility>0</visibility>
<Icon>
<href>http://code.google.com/apis/kml/documentation/bottom_left.jpg</href>
</Icon>
<overlayXY x="0" y="-1" xunits="fraction" yunits="fraction"/>
<screenXY x="0" y="0" xunits="fraction" yunits="fraction"/>
<rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
<size x="0" y="0" xunits="fraction" yunits="fraction"/>
</ScreenOverlay>
<ScreenOverlay>
<name>Absolute Positioning: Bottom right</name>
<visibility>0</visibility>
<Icon>
<href>http://code.google.com/apis/kml/documentation/bottom_right.jpg</href>
</Icon>
<overlayXY x="1" y="-1" xunits="fraction" yunits="fraction"/>
<screenXY x="1" y="0" xunits="fraction" yunits="fraction"/>
<rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
<size x="0" y="0" xunits="fraction" yunits="fraction"/>
</ScreenOverlay>
<ScreenOverlay>
<name>Dynamic Positioning: Top of screen</name>
<visibility>0</visibility>
<Icon>
<href>http://code.google.com/apis/kml/documentation/dynamic_screenoverlay.jpg</href>
</Icon>
<overlayXY x="0" y="1" xunits="fraction" yunits="fraction"/>
<screenXY x="0" y="1" xunits="fraction" yunits="fraction"/>
<rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
<size x="1" y="0.2" xunits="fraction" yunits="fraction"/>
</ScreenOverlay>
<ScreenOverlay>
<name>Dynamic Positioning: Right of screen</name>
<visibility>0</visibility>
<Icon>
<href>http://code.google.com/apis/kml/documentation/dynamic_right.jpg</href>
</Icon>
<overlayXY x="1" y="1" xunits="fraction" yunits="fraction"/>
<screenXY x="1" y="1" xunits="fraction" yunits="fraction"/>
<rotationXY x="0" y="0" xunits="fraction" yunits="fraction"/>
<size x="0" y="1" xunits="fraction" yunits="fraction"/>
</ScreenOverlay>
</Folder>
<Folder>
<name>Paths</name>
<visibility>0</visibility>
<description>Examples of paths. Note that the tessellate tag is by default
set to 0. If you want to create tessellated lines, they must be authored
(or edited) directly in KML.</description>
<Placemark>
<name>Tessellated</name>
<visibility>0</visibility>
<description><![CDATA[If the <tessellate> tag has a value of 1, the line will contour to the underlying terrain]]></description>
<LookAt>
<longitude>-112.0822680013139</longitude>
<latitude>36.09825589333556</latitude>
<altitude>0</altitude>
<heading>103.8120432044965</heading>
<tilt>62.04855796276328</tilt>
<range>2889.145007690472</range>
</LookAt>
<LineString>
<tessellate>1</tessellate>
<coordinates> -112.0814237830345,36.10677870477137,0
-112.0870267752693,36.0905099328766,0 </coordinates>
</LineString>
</Placemark>
<Placemark>
<name>Untessellated</name>
<visibility>0</visibility>
<description><![CDATA[If the <tessellate> tag has a value of 0, the line follow a simple straight-line path from point to point]]></description>
<LookAt>
<longitude>-112.0822680013139</longitude>
<latitude>36.09825589333556</latitude>
<altitude>0</altitude>
<heading>103.8120432044965</heading>
<tilt>62.04855796276328</tilt>
<range>2889.145007690472</range>
</LookAt>
<LineString>
<tessellate>0</tessellate>
<coordinates> -112.080622229595,36.10673460007995,0
-112.085242575315,36.09049598612422,0 </coordinates>
</LineString>
</Placemark>
<Placemark>
<name>Absolute</name>
<visibility>0</visibility>
<description>Transparent purple line</description>
<LookAt>
<longitude>-112.2719329043177</longitude>
<latitude>36.08890633450894</latitude>
<altitude>0</altitude>
<heading>-106.8161545998597</heading>
<tilt>44.60763714063257</tilt>
<range>2569.386744398339</range>
</LookAt>
<styleUrl>#transPurpleLineGreenPoly</styleUrl>
<LineString>
<tessellate>1</tessellate>
<altitudeMode>absolute</altitudeMode>
<coordinates> -112.265654928602,36.09447672602546,2357
-112.2660384528238,36.09342608838671,2357
-112.2668139013453,36.09251058776881,2357
-112.2677826834445,36.09189827357996,2357
-112.2688557510952,36.0913137941187,2357
-112.2694810717219,36.0903677207521,2357
-112.2695268555611,36.08932171487285,2357
-112.2690144567276,36.08850916060472,2357
-112.2681528815339,36.08753813597956,2357
-112.2670588176031,36.08682685262568,2357
-112.2657374587321,36.08646312301303,2357 </coordinates>
</LineString>
</Placemark>
<Placemark>
<name>Absolute Extruded</name>
<visibility>0</visibility>
<description>Transparent green wall with yellow outlines</description>
<LookAt>
<longitude>-112.2643334742529</longitude>
<latitude>36.08563154742419</latitude>
<altitude>0</altitude>
<heading>-125.7518698668815</heading>
<tilt>44.61038665812578</tilt>
<range>4451.842204068102</range>
</LookAt>
<styleUrl>#yellowLineGreenPoly</styleUrl>
<LineString>
<extrude>1</extrude>
<tessellate>1</tessellate>
<altitudeMode>absolute</altitudeMode>
<coordinates> -112.2550785337791,36.07954952145647,2357
-112.2549277039738,36.08117083492122,2357
-112.2552505069063,36.08260761307279,2357
-112.2564540158376,36.08395660588506,2357
-112.2580238976449,36.08511401044813,2357
-112.2595218489022,36.08584355239394,2357
-112.2608216347552,36.08612634548589,2357
-112.262073428656,36.08626019085147,2357
-112.2633204928495,36.08621519860091,2357
-112.2644963846444,36.08627897945274,2357
-112.2656969554589,36.08649599090644,2357 </coordinates>
</LineString>
</Placemark>
<Placemark>
<name>Relative</name>
<visibility>0</visibility>
<description>Black line (10 pixels wide), height tracks terrain</description>
<LookAt>
<longitude>-112.2580438551384</longitude>
<latitude>36.1072674824385</latitude>
<altitude>0</altitude>
<heading>4.947421249553717</heading>
<tilt>44.61324882043339</tilt>
<range>2927.61105910266</range>
</LookAt>
<styleUrl>#thickBlackLine</styleUrl>
<LineString>
<tessellate>1</tessellate>
<altitudeMode>relativeToGround</altitudeMode>
<coordinates> -112.2532845153347,36.09886943729116,645
-112.2540466121145,36.09919570465255,645
-112.254734666947,36.09984998366178,645
-112.255493345654,36.10051310621746,645
-112.2563157098468,36.10108441943419,645
-112.2568033076439,36.10159722088088,645
-112.257494011321,36.10204323542867,645
-112.2584106072308,36.10229131995655,645
-112.2596588987972,36.10240001286358,645
-112.2610581199487,36.10213176873407,645
-112.2626285262793,36.10157011437219,645 </coordinates>
</LineString>
</Placemark>
<Placemark>
<name>Relative Extruded</name>
<visibility>0</visibility>
<description>Opaque blue walls with red outline, height tracks terrain</description>
<LookAt>
<longitude>-112.2683594333433</longitude>
<latitude>36.09884362144909</latitude>
<altitude>0</altitude>
<heading>-72.24271551768405</heading>
<tilt>44.60855445139561</tilt>
<range>2184.193522571467</range>
</LookAt>
<styleUrl>#redLineBluePoly</styleUrl>
<LineString>
<extrude>1</extrude>
<tessellate>1</tessellate>
<altitudeMode>relativeToGround</altitudeMode>
<coordinates> -112.2656634181359,36.09445214722695,630
-112.2652238941097,36.09520916122063,630
-112.2645079986395,36.09580763864907,630
-112.2638827428817,36.09628572284063,630
-112.2635746835406,36.09679275951239,630
-112.2635711822407,36.09740038871899,630
-112.2640296531825,36.09804913435539,630
-112.264327720538,36.09880337400301,630
-112.2642436562271,36.09963644790288,630
-112.2639148687042,36.10055381117246,630
-112.2626894973474,36.10149062823369,630 </coordinates>
</LineString>
</Placemark>
</Folder>
<Folder>
<name>Polygons</name>
<visibility>0</visibility>
<description>Examples of polygon shapes</description>
<Folder>
<name>Google Campus</name>
<visibility>0</visibility>
<description>A collection showing how easy it is to create 3-dimensional
buildings</description>
<LookAt>
<longitude>-122.084120030116</longitude>
<latitude>37.42174011925477</latitude>
<altitude>0</altitude>
<heading>-34.82469740081282</heading>
<tilt>53.454348562403</tilt>
<range>276.7870053764046</range>
</LookAt>
<Placemark>
<name>Building 40</name>
<visibility>0</visibility>
<styleUrl>#transRedPoly</styleUrl>
<Polygon>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates> -122.0848938459612,37.42257124044786,17
-122.0849580979198,37.42211922626856,17
-122.0847469573047,37.42207183952619,17
-122.0845725380962,37.42209006729676,17
-122.0845954886723,37.42215932700895,17
-122.0838521118269,37.42227278564371,17
-122.083792243335,37.42203539112084,17
-122.0835076656616,37.42209006957106,17
-122.0834709464152,37.42200987395161,17
-122.0831221085748,37.4221046494946,17
-122.0829247374572,37.42226503990386,17
-122.0829339169385,37.42231242843094,17
-122.0833837359737,37.42225046087618,17
-122.0833607854248,37.42234159228745,17
-122.0834204551642,37.42237075460644,17
-122.083659133885,37.42251292011001,17
-122.0839758438952,37.42265873093781,17
-122.0842374743331,37.42265143972521,17
-122.0845036949503,37.4226514386435,17
-122.0848020460801,37.42261133916315,17
-122.0847882750515,37.42256395055121,17
-122.0848938459612,37.42257124044786,17 </coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
<Placemark>
<name>Building 41</name>
<visibility>0</visibility>
<styleUrl>#transBluePoly</styleUrl>
<Polygon>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates> -122.0857412771483,37.42227033155257,17
-122.0858169768481,37.42231408832346,17
-122.085852582875,37.42230337469744,17
-122.0858799945639,37.42225686138789,17
-122.0858860101409,37.4222311076138,17
-122.0858069157288,37.42220250173855,17
-122.0858379542653,37.42214027058678,17
-122.0856732640519,37.42208690214408,17
-122.0856022926407,37.42214885429042,17
-122.0855902778436,37.422128290487,17
-122.0855841672237,37.42208171967246,17
-122.0854852065741,37.42210455874995,17
-122.0855067264352,37.42214267949824,17
-122.0854430712915,37.42212783846172,17
-122.0850990714904,37.42251282407603,17
-122.0856769818632,37.42281815323651,17
-122.0860162273783,37.42244918858722,17
-122.0857260327004,37.42229239604253,17
-122.0857412771483,37.42227033155257,17 </coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
<Placemark>
<name>Building 42</name>
<visibility>0</visibility>
<styleUrl>#transGreenPoly</styleUrl>
<Polygon>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates> -122.0857862287242,37.42136208886969,25
-122.0857312990603,37.42136935989481,25
-122.0857312992918,37.42140934910903,25
-122.0856077073679,37.42138390166565,25
-122.0855802426516,37.42137299550869,25
-122.0852186221971,37.42137299504316,25
-122.0852277765639,37.42161656508265,25
-122.0852598189347,37.42160565894403,25
-122.0852598185499,37.42168200156,25
-122.0852369311478,37.42170017860346,25
-122.0852643957828,37.42176197982575,25
-122.0853239032746,37.42176198013907,25
-122.0853559454324,37.421852864452,25
-122.0854108752463,37.42188921823734,25
-122.0854795379357,37.42189285337048,25
-122.0855436229819,37.42188921797546,25
-122.0856260178042,37.42186013499926,25
-122.085937287963,37.42186013453605,25
-122.0859428718666,37.42160898590042,25
-122.0859655469861,37.42157992759144,25
-122.0858640462341,37.42147115002957,25
-122.0858548911215,37.42140571326184,25
-122.0858091162768,37.4214057134039,25
-122.0857862287242,37.42136208886969,25 </coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
<Placemark>
<name>Building 43</name>
<visibility>0</visibility>
<styleUrl>#transYellowPoly</styleUrl>
<Polygon>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates> -122.0844371128284,37.42177253003091,19
-122.0845118855746,37.42191111542896,19
-122.0850470999805,37.42178755121535,19
-122.0850719913391,37.42143663023161,19
-122.084916406232,37.42137237822116,19
-122.0842193868167,37.42137237801626,19
-122.08421938659,37.42147617161496,19
-122.0838086419991,37.4214613409357,19
-122.0837899728564,37.42131306410796,19
-122.0832796534698,37.42129328840593,19
-122.0832609819207,37.42139213944298,19
-122.0829373621737,37.42137236399876,19
-122.0829062425667,37.42151569778871,19
-122.0828502269665,37.42176282576465,19
-122.0829435788635,37.42176776969635,19
-122.083217411188,37.42179248552686,19
-122.0835970430103,37.4217480074456,19
-122.0839455556771,37.42169364237603,19
-122.0840077894637,37.42176283815853,19
-122.084113587521,37.42174801104392,19
-122.0840762473784,37.42171341292375,19
-122.0841447047739,37.42167881534569,19
-122.084144704223,37.42181720660197,19
-122.0842503333074,37.4218170700446,19
-122.0844371128284,37.42177253003091,19 </coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</Folder>
<Folder>
<name>Extruded Polygon</name>
<description>A simple way to model a building</description>
<Placemark>
<name>The Pentagon</name>
<LookAt>
<longitude>-77.05580139178142</longitude>
<latitude>38.870832443487</latitude>
<heading>59.88865561738225</heading>
<tilt>48.09646074797388</tilt>
<range>742.0552506670548</range>
</LookAt>
<Polygon>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates> -77.05788457660967,38.87253259892824,100
-77.05465973756702,38.87291016281703,100
-77.05315536854791,38.87053267794386,100
-77.05552622493516,38.868757801256,100
-77.05844056290393,38.86996206506943,100
-77.05788457660967,38.87253259892824,100 </coordinates>
</LinearRing>
</outerBoundaryIs>
<innerBoundaryIs>
<LinearRing>
<coordinates> -77.05668055019126,38.87154239798456,100
-77.05542625960818,38.87167890344077,100
-77.05485125901024,38.87076535397792,100
-77.05577677433152,38.87008686581446,100
-77.05691162017543,38.87054446963351,100
-77.05668055019126,38.87154239798456,100 </coordinates>
</LinearRing>
</innerBoundaryIs>
</Polygon>
</Placemark>
</Folder>
<Folder>
<name>Absolute and Relative</name>
<visibility>0</visibility>
<description>Four structures whose roofs meet exactly. Turn on/off
terrain to see the difference between relative and absolute
positioning.</description>
<LookAt>
<longitude>-112.3348969157552</longitude>
<latitude>36.14845533214919</latitude>
<altitude>0</altitude>
<heading>-86.91235037566909</heading>
<tilt>49.30695423894192</tilt>
<range>990.6761201087104</range>
</LookAt>
<Placemark>
<name>Absolute</name>
<visibility>0</visibility>
<styleUrl>#transBluePoly</styleUrl>
<Polygon>
<tessellate>1</tessellate>
<altitudeMode>absolute</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates> -112.3382510731295,36.14888505105318,1784
-112.3356128688403,36.14781540589019,1784
-112.3368169371048,36.14658677734382,1784
-112.3374408457543,36.14762778914076,1784
-112.3382510731295,36.14888505105318,1784 </coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
<Placemark>
<name>Absolute Extruded</name>
<visibility>0</visibility>
<styleUrl>#transRedPoly</styleUrl>
<Polygon>
<extrude>1</extrude>
<tessellate>1</tessellate>
<altitudeMode>absolute</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates> -112.3396586818843,36.14637618647505,1784
-112.3380597654315,36.14531751871353,1784
-112.3368254237788,36.14659596244607,1784
-112.3384555043203,36.14762621763982,1784
-112.3396586818843,36.14637618647505,1784 </coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
<Placemark>
<name>Relative</name>
<visibility>0</visibility>
<LookAt>
<longitude>-112.3350152490417</longitude>
<latitude>36.14943123077423</latitude>
<altitude>0</altitude>
<heading>-118.9214100848499</heading>
<tilt>37.92486261093203</tilt>
<range>345.5169113679813</range>
</LookAt>
<styleUrl>#transGreenPoly</styleUrl>
<Polygon>
<tessellate>1</tessellate>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates> -112.3349463145932,36.14988705767721,100
-112.3354019540677,36.14941108398372,100
-112.3344428289146,36.14878490381308,100
-112.3331289492913,36.14780840132443,100
-112.3317019516947,36.14680755678357,100
-112.331131440106,36.1474173426228,100
-112.332616324338,36.14845453364654,100
-112.3339876620524,36.14926570522069,100
-112.3349463145932,36.14988705767721,100 </coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
<Placemark>
<name>Relative Extruded</name>
<visibility>0</visibility>
<LookAt>
<longitude>-112.3351587892382</longitude>
<latitude>36.14979247129029</latitude>
<altitude>0</altitude>
<heading>-55.42811560891606</heading>
<tilt>56.10280503739589</tilt>
<range>401.0997279712519</range>
</LookAt>
<styleUrl>#transYellowPoly</styleUrl>
<Polygon>
<extrude>1</extrude>
<tessellate>1</tessellate>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates> -112.3348783983763,36.1514008468736,100
-112.3372535345629,36.14888517553886,100
-112.3356068927954,36.14781612679284,100
-112.3350034807972,36.14846469024177,100
-112.3358353861232,36.1489624162954,100
-112.3345888301373,36.15026229372507,100
-112.3337937856278,36.14978096026463,100
-112.3331798208424,36.1504472788618,100
-112.3348783983763,36.1514008468736,100 </coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</Folder>
</Folder>
</Document>
</kml>

View file

@ -0,0 +1 @@
<box>42.943 -71.032 43.039 -69.856</box>

View file

@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<Placemark>
<name>CDATA example</name>
<description>
<![CDATA[
<h1>CDATA Tags are useful!</h1>
<p><font color="red">Text is <i>more readable</i> and
<b>easier to write</b> when you can avoid using entity
references.</font></p>
]]>
</description>
<Point>
<coordinates>102.595626,14.996729</coordinates>
</Point>
</Placemark>
</Document>
</kml>

View file

@ -0,0 +1 @@
<circle>42.943 -71.032 500</circle>

View file

@ -0,0 +1 @@
POINT EMPTY

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:georss="http://www.georss.org/georss">
<title>Earthquakes</title>
<subtitle>International earthquake observation labs</subtitle>
<link href="http://example.org/"/>
<updated>2005-12-13T18:30:02Z</updated>
<author>
<name>Dr. Thaddeus Remor</name>
<email>tremor@quakelab.edu</email>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>This has multiple georss entries in it</title>
<link href="http://example.org/2005/09/09/atom01"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2005-08-17T07:02:32Z</updated>
<summary>We just had a big one.</summary>
<georss:point>45.256 -71.92</georss:point>
<georss:point>42.256 -69.92</georss:point>
<georss:line>45.256 -110.45 46.46 -109.48 43.84 -109.86</georss:line>
<georss:polygon>45.256 -110.45 46.46 -109.48 43.84 -109.86 45.256 -110.45</georss:polygon>
</entry>
<entry>
<title>Another Entry</title>d
<summary>Another point.</summary>
<georss:point>46.256 -70.92</georss:point>
</entry>
</feed>

View file

@ -0,0 +1 @@
GEOMETRYCOLLECTION (POINT (4 6), LINESTRING (4 6,7 10))

View file

@ -0,0 +1 @@
<line>45.256 -110.45 46.46 -109.48 43.84 -109.86</line>

View file

@ -0,0 +1 @@
LINESTRING (30 10, 10 30, 40 40)

View file

@ -0,0 +1 @@
xn76urx4epb0

View file

@ -0,0 +1 @@
SRID=4269;MULTILINESTRING((-71.160281 42.258729,-71.160837 42.259113,-71.161144 42.25932))

View file

@ -0,0 +1 @@
MULTILINESTRING ((10 10, 20 20, 10 40), (40 40, 30 30, 40 20, 30 10))

Binary file not shown.

View file

@ -0,0 +1 @@
MULTIPOLYGON (((30 20, 10 40, 45 40, 30 20)), ((15 5, 40 10, 10 20, 5 10, 15 5)))

View file

@ -0,0 +1 @@
MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)),((20 35, 45 20, 30 5, 10 10, 10 30, 20 35),(30 20, 20 25, 20 15, 30 20)))

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" creator="" version="1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
<trk>
<name>Mons and its opposite</name>
<trkseg>
<trkpt lat="50.45409" lon="3.95626"></trkpt>
<trkpt lat="-50.45409" lon="-176.04374"></trkpt>
</trkseg>
</trk>
</gpx>

View file

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Paths</name>
<description>Examples of paths. Note that the tessellate tag is by default
set to 0. If you want to create tessellated lines, they must be authored
(or edited) directly in KML.</description>
<Style id="yellowLineGreenPoly">
<LineStyle>
<color>7f00ffff</color>
<width>4</width>
</LineStyle>
<PolyStyle>
<color>7f00ff00</color>
</PolyStyle>
</Style>
<Placemark>
<name>Absolute Extruded</name>
<description>Transparent green wall with yellow outlines</description>
<styleUrl>#yellowLineGreenPoly</styleUrl>
<LineString>
<extrude>1</extrude>
<tessellate>1</tessellate>
<altitudeMode>absolute</altitudeMode>
<coordinates> -112.2550785337791,36.07954952145647,2357
-112.2549277039738,36.08117083492122,2357
-112.2552505069063,36.08260761307279,2357
-112.2564540158376,36.08395660588506,2357
-112.2580238976449,36.08511401044813,2357
-112.2595218489022,36.08584355239394,2357
-112.2608216347552,36.08612634548589,2357
-112.262073428656,36.08626019085147,2357
-112.2633204928495,36.08621519860091,2357
-112.2644963846444,36.08627897945274,2357
-112.2656969554589,36.08649599090644,2357
</coordinates>
</LineString>
</Placemark>
</Document>
</kml>

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>The Pentagon</name>
<Polygon>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates>
-77.05788457660967,38.87253259892824,100
-77.05465973756702,38.87291016281703,100
-77.05315536854791,38.87053267794386,100
-77.05552622493516,38.868757801256,100
-77.05844056290393,38.86996206506943,100
-77.05788457660967,38.87253259892824,100
</coordinates>
</LinearRing>
</outerBoundaryIs>
<innerBoundaryIs>
<LinearRing>
<coordinates>
-77.05668055019126,38.87154239798456,100
-77.05542625960818,38.87167890344077,100
-77.05485125901024,38.87076535397792,100
-77.05577677433152,38.87008686581446,100
-77.05691162017543,38.87054446963351,100
-77.05668055019126,38.87154239798456,100
</coordinates>
</LinearRing>
</innerBoundaryIs>
</Polygon>
</Placemark>
</kml>

View file

@ -0,0 +1,21 @@
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom"
xmlns:georss="http://www.georss.org/georss">
<title>Earthquakes</title>
<subtitle>International earthquake observation labs</subtitle>
<link href="http://example.org/"/>
<updated>2005-12-13T18:30:02Z</updated>
<author>
<name>Dr. Thaddeus Remor</name>
<email>tremor@quakelab.edu</email>
</author>
<id>urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6</id>
<entry>
<title>M 3.2, Mona Passage</title>
<link href="http://example.org/2005/09/09/atom01"/>
<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
<updated>2005-08-17T07:02:32Z</updated>
<summary>We just had a big one.</summary>
<georss:point>45.256 -71.92</georss:point>
</entry>
</feed>

View file

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Placemark>
<name>Simple placemark</name>
<description>Attached to the ground. Intelligently places itself
at the height of the underlying terrain.</description>
<Point>
<coordinates>-122.0822035425683,37.42228990140251,0</coordinates>
</Point>
</Placemark>
</kml>

View file

@ -0,0 +1 @@
POINT (10 12)

View file

@ -0,0 +1,3 @@
<polygon>
45.256 -110.45 46.46 -109.48 43.84 -109.86 45.256 -110.45
</polygon>

View file

@ -0,0 +1 @@
POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))

View file

@ -0,0 +1 @@
POLYGON ((35 10, 10 20, 15 40, 45 45, 35 10), (20 30, 35 35, 30 20, 20 30))

View file

@ -0,0 +1 @@
POLYGON ((-123.222653196 49.1529676585, -89.4726531957 49.3823707987, -81.0351531957 44.0875828344, -71.1914031957 44.3395630636, -62.0507781957 48.4583498573, -60.2929656957 45.0890334085, -78.9257781957 37.4399716272, -82.0898406957 31.3536343332, -81.3867156957 26.4312253295, -91.9335906957 29.8406412505, -98.2617156957 26.4312253295, -107.753903196 32.2499718728, -116.894528196 33.1375486348, -122.519528196 36.0313293064, -126.035153196 42.2935619329, -123.222653196 49.1529676585))

View file

@ -0,0 +1 @@
POLYGON((4.8352495472368009 52.3561217600921438,4.8354139113045580 52.3561243429663534,4.8356082266282945 52.3561267417385281,4.8358010085903622 52.3561273083083663,4.8358010085903622 52.3561273083083663,4.8358035242637225 52.3559935212917722,4.8363777606561538 52.3559985348227173,4.8365863082998608 52.3560003600829731,4.8365523717335313 52.3570990145454189,4.8365884597636066 52.3572643433297529,4.8366320506970659 52.3574639095218686,4.8366736405531485 52.3576544056339870,4.8367264446828226 52.3578947700094304,4.8367922739966023 52.3581940807800450,4.8368228816936947 52.3583326871276356,4.8368228816936947 52.3583326871276356,4.8346348012064322 52.3583075969840550,4.8346348012064322 52.3583075969840550,4.8346348010943823 52.3583076059723282,4.8346348010943823 52.3583076059723282,4.8344931735728114 52.3583059732702338,4.8343773230572911 52.3583046496785585,4.8342182417472204 52.3583028092031384,4.8340047277034000 52.3583004442080195,4.8340047277034000 52.3583004442080195,4.8340047286008216 52.3583003723016063,4.8340047286008216 52.3583003723016063,4.8333843154510516 52.3582932434377639,4.8333843154510516 52.3582932434377639,4.8333915914677918 52.3580669388087898,4.8333968982183286 52.3578913129544787,4.8334415565569193 52.3563602568407660,4.8336003450092706 52.3563614767834267,4.8336013166539615 52.3563318721204567,4.8336013166539615 52.3563318721204567,4.8339582156582548 52.3563361223319603,4.8339656498645338 52.3561015845598732,4.8340692910524092 52.3561032110135258,4.8340692910524092 52.3561032110135258,4.8345511248958477 52.3561107854074095,4.8345511248958477 52.3561107854074095,4.8345513450958055 52.3561107864365809,4.8345513450958055 52.3561107864365809,4.8346742584771087 52.3561127181661092,4.8346742584771087 52.3561127181661092,4.8347750227755597 52.3561143035917596,4.8347750227755597 52.3561143035917596,4.8352495472368009 52.3561217600921438))

View file

@ -0,0 +1,2 @@
POLYGON ((30 10 , 10 20 , 20 40 , 40 40 , 30 10 ))

4749
vendor/phayes/geophp/tests/input/route.gpx vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1 @@
xpssc0

View file

@ -0,0 +1 @@
{"type": "Feature", "geometry": {"type": "Point", "coordinates": [-80.73029, 35.3936]}}

View file

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:gpxx="http://www.garmin.com/xmlschemas/GpxExtensions/v3" xmlns:gpxtpx="http://www.garmin.com/xmlschemas/TrackPointExtension/v1" creator="Oregon 400t" version="1.1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd http://www.garmin.com/xmlschemas/GpxExtensions/v3 http://www.garmin.com/xmlschemas/GpxExtensionsv3.xsd http://www.garmin.com/xmlschemas/TrackPointExtension/v1 http://www.garmin.com/xmlschemas/TrackPointExtensionv1.xsd">
<metadata>
<link href="http://www.garmin.com">
<text>Garmin International</text>
</link>
<time>2009-10-17T22:58:43Z</time>
</metadata>
<trk>
<name>Example GPX Document</name>
<trkseg>
<trkpt lat="47.644548" lon="-122.326897">
<ele>4.46</ele>
<time>2009-10-17T18:37:26Z</time>
</trkpt>
<trkpt lat="47.644550" lon="-122.326897">
<ele>4.94</ele>
<time>2009-10-17T18:37:31Z</time>
</trkpt>
<trkpt lat="47.644552" lon="-122.326899">
<ele>6.87</ele>
<time>2009-10-17T18:37:34Z</time>
</trkpt>
</trkseg>
</trk>
</gpx>

82
vendor/phayes/geophp/tests/postgis.php vendored Normal file
View file

@ -0,0 +1,82 @@
<?
// Uncomment to test
# run_test();
function run_test() {
header("Content-type: text");
include_once('../geoPHP.inc');
// Your database test table should contain 3 columns: name (text), type (text), geom (geometry)
$host = 'localhost';
$database = 'phayes';
$table = 'test';
$column = 'geom';
$user = 'phayes';
$pass = 'supersecret';
$connection = pg_connect("host=$host dbname=$database user=$user password=$pass");
// Truncate
pg_query($connection, "DELETE FROM $table");
// Working with PostGIS and EWKB
// ----------------------------
foreach (scandir('./input', SCANDIR_SORT_NONE) as $file) {
$parts = explode('.',$file);
if ($parts[0]) {
$name = $parts[0];
$format = $parts[1];
$value = file_get_contents('./input/'.$file);
print '---- Testing '.$file."\n";
flush();
$geometry = geoPHP::load($value, $format);
test_postgis($name, $format, $geometry, $connection, 'wkb');
$geometry->setSRID(4326);
test_postgis($name, $format, $geometry, $connection, 'ewkb');
}
}
print "Testing Done!";
}
function test_postgis($name, $type, $geom, $connection, $format) {
global $table;
// Let's insert into the database using GeomFromWKB
$insert_string = pg_escape_bytea($geom->out($format));
pg_query($connection, "INSERT INTO $table (name, type, geom) values ('$name', '$type', GeomFromWKB('$insert_string'))");
// SELECT using asBinary PostGIS
$result = pg_fetch_all(pg_query($connection, "SELECT asBinary(geom) as geom FROM $table WHERE name='$name'"));
foreach ($result as $item) {
$wkb = pg_unescape_bytea($item['geom']); // Make sure to unescape the hex blob
$geom = geoPHP::load($wkb, $format); // We now a full geoPHP Geometry object
}
// SELECT and INSERT directly, with no wrapping functions
$result = pg_fetch_all(pg_query($connection, "SELECT geom as geom FROM $table WHERE name='$name'"));
foreach ($result as $item) {
$wkb = pack('H*',$item['geom']); // Unpacking the hex blob
$geom = geoPHP::load($wkb, $format); // We now have a geoPHP Geometry
// Let's re-insert directly into postGIS
// We need to unpack the WKB
$unpacked = unpack('H*', $geom->out($format));
$insert_string = $unpacked[1];
pg_query($connection, "INSERT INTO $table (name, type, geom) values ('$name', '$type', '$insert_string')");
}
// SELECT and INSERT using as EWKT (ST_GeomFromEWKT and ST_AsEWKT)
$result = pg_fetch_all(pg_query($connection, "SELECT ST_AsEWKT(geom) as geom FROM $table WHERE name='$name'"));
foreach ($result as $item) {
$wkt = $item['geom']; // Make sure to unescape the hex blob
$geom = geoPHP::load($wkt, 'ewkt'); // We now a full geoPHP Geometry object
// Let's re-insert directly into postGIS
$insert_string = $geom->out('ewkt');
pg_query($connection, "INSERT INTO $table (name, type, geom) values ('$name', '$type', ST_GeomFromEWKT('$insert_string'))");
}
}

258
vendor/phayes/geophp/tests/test.php vendored Normal file
View file

@ -0,0 +1,258 @@
<?php
// Uncomment to test
if (getenv("GEOPHP_RUN_TESTS") == 1) {
run_test();
}
else {
print "Skipping tests. Please set GEOPHP_RUN_TESTS=1 environment variable if you wish to run tests\n";
}
function run_test() {
set_time_limit(0);
set_error_handler("FailOnError");
header("Content-type: text");
include_once('../geoPHP.inc');
if (geoPHP::geosInstalled()) {
print "GEOS is installed.\n";
}
else {
print "GEOS is not installed.\n";
}
foreach (scandir('./input', SCANDIR_SORT_NONE) as $file) {
$parts = explode('.',$file);
if ($parts[0]) {
$format = $parts[1];
$value = file_get_contents('./input/'.$file);
print '---- Testing '.$file."\n";
$geometry = geoPHP::load($value, $format);
test_adapters($geometry, $format, $value);
test_methods($geometry);
test_geometry($geometry);
test_detection($value, $format, $file);
}
}
print "\e[32m" . "PASS". "\e[39m\n";
}
function test_geometry($geometry) {
// Test common functions
$geometry->area();
$geometry->boundary();
$geometry->envelope();
$geometry->getBBox();
$geometry->centroid();
$geometry->length();
$geometry->greatCircleLength();
$geometry->haversineLength();
$geometry->y();
$geometry->x();
$geometry->numGeometries();
$geometry->geometryN(1);
$geometry->startPoint();
$geometry->endPoint();
$geometry->isRing();
$geometry->isClosed();
$geometry->numPoints();
$geometry->pointN(1);
$geometry->exteriorRing();
$geometry->numInteriorRings();
$geometry->interiorRingN(1);
$geometry->dimension();
$geometry->geometryType();
$geometry->SRID();
$geometry->setSRID(4326);
// Aliases
$geometry->getCentroid();
$geometry->getArea();
$geometry->getX();
$geometry->getY();
$geometry->getGeos();
$geometry->getGeomType();
$geometry->getSRID();
$geometry->asText();
$geometry->asBinary();
// GEOS only functions
$geometry->geos();
$geometry->setGeos($geometry->geos());
$geometry->pointOnSurface();
$geometry->equals($geometry);
$geometry->equalsExact($geometry);
$geometry->relate($geometry);
$geometry->checkValidity();
$geometry->isSimple();
$geometry->buffer(10);
$geometry->intersection($geometry);
$geometry->convexHull();
$geometry->difference($geometry);
$geometry->symDifference($geometry);
$geometry->union($geometry);
$geometry->simplify(0);// @@TODO: Adjust this once we can deal with empty geometries
$geometry->disjoint($geometry);
$geometry->touches($geometry);
$geometry->intersects($geometry);
$geometry->crosses($geometry);
$geometry->within($geometry);
$geometry->contains($geometry);
$geometry->overlaps($geometry);
$geometry->covers($geometry);
$geometry->coveredBy($geometry);
$geometry->distance($geometry);
$geometry->hausdorffDistance($geometry);
// Place holders
$geometry->hasZ();
$geometry->is3D();
$geometry->isMeasured();
$geometry->isEmpty();
$geometry->coordinateDimension();
$geometry->z();
$geometry->m();
}
function test_adapters($geometry, $format, $input) {
// Test adapter output and input. Do a round-trip and re-test
foreach (geoPHP::getAdapterMap() as $adapter_key => $adapter_class) {
if ($adapter_key != 'google_geocode') { //Don't test google geocoder regularily. Uncomment to test
$output = $geometry->out($adapter_key);
if ($output) {
$adapter_loader = new $adapter_class();
$test_geom_1 = $adapter_loader->read($output);
$test_geom_2 = $adapter_loader->read($test_geom_1->out($adapter_key));
if ($test_geom_1->out('wkt') != $test_geom_2->out('wkt')) {
print "Mismatched adapter output in ".$adapter_class."\n";
}
}
else {
print "Empty output on " . $adapter_key . "\n";
}
}
}
// Test to make sure adapter work the same wether GEOS is ON or OFF
// Cannot test methods if GEOS is not intstalled
if (!geoPHP::geosInstalled()) return;
foreach (geoPHP::getAdapterMap() as $adapter_key => $adapter_class) {
if ($adapter_key != 'google_geocode') { //Don't test google geocoder regularily. Uncomment to test
// Turn GEOS on
geoPHP::geosInstalled(TRUE);
$output = $geometry->out($adapter_key);
if ($output) {
$adapter_loader = new $adapter_class();
$test_geom_1 = $adapter_loader->read($output);
// Turn GEOS off
geoPHP::geosInstalled(FALSE);
$test_geom_2 = $adapter_loader->read($output);
// Turn GEOS back On
geoPHP::geosInstalled(TRUE);
// Check to make sure a both are the same with geos and without
if ($test_geom_1->out('wkt') != $test_geom_2->out('wkt')) {
print "Mismatched adapter output between GEOS and NORM in ".$adapter_class."\n";
}
}
}
}
}
function test_methods($geometry) {
// Cannot test methods if GEOS is not intstalled
if (!geoPHP::geosInstalled()) return;
$methods = array(
//'boundary', //@@TODO: Uncomment this and fix errors
'envelope', //@@TODO: Testing reveales errors in this method -- POINT vs. POLYGON
'getBBox',
'x',
'y',
'startPoint',
'endPoint',
'isRing',
'isClosed',
'numPoints',
);
foreach ($methods as $method) {
// Turn GEOS on
geoPHP::geosInstalled(TRUE);
$geos_result = $geometry->$method();
// Turn GEOS off
geoPHP::geosInstalled(FALSE);
$norm_result = $geometry->$method();
// Turn GEOS back On
geoPHP::geosInstalled(TRUE);
$geos_type = gettype($geos_result);
$norm_type = gettype($norm_result);
if ($geos_type != $norm_type) {
print 'Type mismatch on '.$method."\n";
continue;
}
// Now check base on type
if ($geos_type == 'object') {
$haus_dist = $geos_result->hausdorffDistance(geoPHP::load($norm_result->out('wkt'),'wkt'));
// Get the length of the diagonal of the bbox - this is used to scale the haustorff distance
// Using Pythagorean theorem
$bb = $geos_result->getBBox();
$scale = sqrt((($bb['maxy'] - $bb['miny'])^2) + (($bb['maxx'] - $bb['minx'])^2));
// The difference in the output of GEOS and native-PHP methods should be less than 0.5 scaled haustorff units
if ($haus_dist / $scale > 0.5) {
print 'Output mismatch on '.$method.":\n";
print 'GEOS : '.$geos_result->out('wkt')."\n";
print 'NORM : '.$norm_result->out('wkt')."\n";
continue;
}
}
if ($geos_type == 'boolean' || $geos_type == 'string') {
if ($geos_result !== $norm_result) {
print 'Output mismatch on '.$method.":\n";
print 'GEOS : '.(string) $geos_result."\n";
print 'NORM : '.(string) $norm_result."\n";
continue;
}
}
//@@TODO: Run tests for output of types arrays and float
//@@TODO: centroid function is non-compliant for collections and strings
}
}
function test_detection($value, $format, $file) {
$detected = geoPHP::detectFormat($value);
if ($detected != $format) {
if ($detected) print 'detected as ' . $detected . "\n";
else print "format not detected\n";
}
// Make sure it loads using auto-detect
geoPHP::load($value);
}
function FailOnError($error_level, $error_message, $error_file, $error_line, $error_context) {
echo "$error_level: $error_message in $error_file on line $error_line\n";
echo "\e[31m" . "FAIL" . "\e[39m\n";
exit(1);
}

View file

@ -0,0 +1,287 @@
<?php
require_once('../geoPHP.inc');
class Tests_20120702 extends PHPUnit_Framework_TestCase {
function setUp() {
}
function testMethods() {
$format = 'gpx';
$value = file_get_contents('./input/20120702.gpx');
$geometry = geoPHP::load($value, $format);
$methods = array(
array('name' => 'area'),
array('name' => 'boundary'),
array('name' => 'getBBox'),
array('name' => 'centroid'),
array('name' => 'length'),
array('name' => 'greatCircleLength', 'argument' => 6378137),
array('name' => 'haversineLength'),
array('name' => 'y'),
array('name' => 'x'),
array('name' => 'numGeometries'),
array('name' => 'geometryN', 'argument' => '1'),
array('name' => 'startPoint'),
array('name' => 'endPoint'),
array('name' => 'isRing'),
array('name' => 'isClosed'),
array('name' => 'numPoints'),
array('name' => 'pointN', 'argument' => '1'),
array('name' => 'exteriorRing'),
array('name' => 'numInteriorRings'),
array('name' => 'interiorRingN', 'argument' => '1'),
array('name' => 'dimension'),
array('name' => 'geometryType'),
array('name' => 'SRID'),
array('name' => 'setSRID', 'argument' => '4326'),
);
foreach($methods as $method) {
$argument = NULL;
$method_name = $method['name'];
if (isset($method['argument'])) {
$argument = $method['argument'];
}
$this->_methods_tester($geometry, $method_name, $argument);
}
}
function _methods_tester($geometry, $method_name, $argument) {
if (!method_exists($geometry, $method_name)) {
$this->fail("Method ".$method_name.'() doesn\'t exists.');
return;
}
switch ($method_name) {
case 'y':
case 'x':
if ($geometry->geometryType() == 'Point') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'geometryN':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'startPoint':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
//TODO: Add a method startPoint() to MultiLineString.
//$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'endPoint':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
//TODO: Add a method endPoint() to MultiLineString.
//$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'isRing':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'isClosed':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'pointN':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
//TODO: Add a method pointN() to MultiLineString.
//$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'exteriorRing':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'numInteriorRings':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'interiorRingN':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'setSRID':
//TODO: The method setSRID() should return TRUE.
break;
case 'SRID':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'getBBox':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'centroid':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'length':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertEquals($geometry->$method_name($argument), (float) '0.11624637315233', 'Failed on ' . $method_name);
}
break;
case 'numGeometries':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'numPoints':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'dimension':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'boundary':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'greatCircleLength':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotEquals($geometry->$method_name($argument), '9500.9359867418', 'Failed on ' . $method_name);
}
break;
case 'haversineLength':
case 'area':
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
break;
case 'geometryType':
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
break;
default:
$this->assertTrue($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
}
}

View file

@ -0,0 +1,63 @@
<?php
require_once('../geoPHP.inc');
class AdaptersTests extends PHPUnit_Framework_TestCase {
function setUp() {
}
function testAdapters() {
foreach (scandir('./input', SCANDIR_SORT_NONE) as $file) {
$parts = explode('.',$file);
if ($parts[0]) {
$format = $parts[1];
$input = file_get_contents('./input/'.$file);
echo "\nloading: " . $file . " for format: " . $format;
$geometry = geoPHP::load($input, $format);
// Test adapter output and input. Do a round-trip and re-test
foreach (geoPHP::getAdapterMap() as $adapter_key => $adapter_class) {
if ($adapter_key != 'google_geocode') { //Don't test google geocoder regularily. Uncomment to test
$output = $geometry->out($adapter_key);
$this->assertNotNull($output, "Empty output on " . $adapter_key);
if ($output) {
$adapter_loader = new $adapter_class();
$test_geom_1 = $adapter_loader->read($output);
$test_geom_2 = $adapter_loader->read($test_geom_1->out($adapter_key));
$this->assertEquals($test_geom_1->out('wkt'), $test_geom_2->out('wkt'), "Mismatched adapter output in ".$adapter_class .' (test file: ' . $file . ')');
}
}
}
// Test to make sure adapter work the same wether GEOS is ON or OFF
// Cannot test methods if GEOS is not intstalled
if (!geoPHP::geosInstalled()) return;
foreach (geoPHP::getAdapterMap() as $adapter_key => $adapter_class) {
if ($adapter_key != 'google_geocode') { //Don't test google geocoder regularily. Uncomment to test
// Turn GEOS on
geoPHP::geosInstalled(TRUE);
$output = $geometry->out($adapter_key);
if ($output) {
$adapter_loader = new $adapter_class();
$test_geom_1 = $adapter_loader->read($output);
// Turn GEOS off
geoPHP::geosInstalled(FALSE);
$test_geom_2 = $adapter_loader->read($output);
// Turn GEOS back On
geoPHP::geosInstalled(TRUE);
// Check to make sure a both are the same with geos and without
$this->assertEquals($test_geom_1->out('wkt'), $test_geom_2->out('wkt'), "Mismatched adapter output between GEOS and NORM in ".$adapter_class .' (test file: ' . $file . ')');
}
}
}
}
}
}
}

View file

@ -0,0 +1,7 @@
<?php
require_once ('../geoPHP.inc');
if (!@include __DIR__ . '/../../vendor/autoload.php') {
die('You must set up the project dependencies, run the following commands:
wget http://getcomposer.org/composer.phar
php composer.phar install');
}

View file

@ -0,0 +1,20 @@
<?php
require_once ('../geoPHP.inc');
class GeoHashTest extends PHPUnit_Framework_TestCase {
function setUp() {
}
/**
* test cases for adjacent geohashes.
*/
function testAdjacent() {
$geohash = new Geohash();
$this->assertEquals ( 'xne', $geohash->adjacent ( 'xn7', 'top' ), 'Did not find correct top adjacent geohash for xn7' );
$this->assertEquals ( 'xnk', $geohash->adjacent ( 'xn7', 'right' ), 'Did not find correct right adjacent geohash for xn7' );
$this->assertEquals ( 'xn5', $geohash->adjacent ( 'xn7', 'bottom' ), 'Did not find correct bottom adjacent geohash for xn7' );
$this->assertEquals ( 'xn6', $geohash->adjacent ( 'xn7', 'left' ), 'Did not find correct left adjacent geohash for xn7' );
$this->assertEquals ( 'xnd', $geohash->adjacent ( $geohash->adjacent ( 'xn7', 'left' ), 'top' ), 'Did not find correct top-left adjacent geohash for xn7' );
}
}

View file

@ -0,0 +1,89 @@
<?php
require_once('../geoPHP.inc');
class GeosTests extends PHPUnit_Framework_TestCase {
function setUp() {
}
function testGeos() {
if (!geoPHP::geosInstalled()) {
echo "Skipping GEOS -- not installed";
return;
}
foreach (scandir('./input', SCANDIR_SORT_NONE) as $file) {
$parts = explode('.',$file);
if ($parts[0]) {
$format = $parts[1];
$value = file_get_contents('./input/'.$file);
echo "\nloading: " . $file . " for format: " . $format;
$geometry = geoPHP::load($value, $format);
$geosMethods = array(
array('name' => 'geos'),
array('name' => 'setGeos', 'argument' => $geometry->geos()),
array('name' => 'PointOnSurface'),
array('name' => 'equals', 'argument' => $geometry),
array('name' => 'equalsExact', 'argument' => $geometry),
array('name' => 'relate', 'argument' => $geometry),
array('name' => 'checkValidity'),
array('name' => 'isSimple'),
array('name' => 'buffer', 'argument' => '10'),
array('name' => 'intersection', 'argument' => $geometry),
array('name' => 'convexHull'),
array('name' => 'difference', 'argument' => $geometry),
array('name' => 'symDifference', 'argument' => $geometry),
array('name' => 'union', 'argument' => $geometry),
array('name' => 'simplify', 'argument' => '0'),
array('name' => 'disjoint', 'argument' => $geometry),
array('name' => 'touches', 'argument' => $geometry),
array('name' => 'intersects', 'argument' => $geometry),
array('name' => 'crosses', 'argument' => $geometry),
array('name' => 'within', 'argument' => $geometry),
array('name' => 'contains', 'argument' => $geometry),
array('name' => 'overlaps', 'argument' => $geometry),
array('name' => 'covers', 'argument' => $geometry),
array('name' => 'coveredBy', 'argument' => $geometry),
array('name' => 'distance', 'argument' => $geometry),
array('name' => 'hausdorffDistance', 'argument' => $geometry),
);
foreach($geosMethods as $method) {
$argument = NULL;
$method_name = $method['name'];
if (isset($method['argument'])) {
$argument = $method['argument'];
}
switch ($method_name) {
case 'isSimple':
case 'equals':
case 'geos':
if ($geometry->geometryType() == 'Point') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
default:
if ($geometry->geometryType() == 'Point') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
}
}
}
}
}
}

View file

@ -0,0 +1,359 @@
<?php
require_once('../geoPHP.inc');
class MethodsTests extends PHPUnit_Framework_TestCase {
function setUp() {
}
function testMethods() {
foreach (scandir('./input', SCANDIR_SORT_NONE) as $file) {
$parts = explode('.',$file);
if ($parts[0]) {
$format = $parts[1];
$value = file_get_contents('./input/'.$file);
echo "\nloading: " . $file . " for format: " . $format;
$geometry = geoPHP::load($value, $format);
$methods = array(
array('name' => 'area'),
array('name' => 'boundary'),
array('name' => 'getBBox'),
array('name' => 'centroid'),
array('name' => 'length'),
array('name' => 'greatCircleLength'),
array('name' => 'haversineLength'),
array('name' => 'y'),
array('name' => 'x'),
array('name' => 'numGeometries'),
array('name' => 'geometryN', 'argument' => '1'),
array('name' => 'startPoint'),
array('name' => 'endPoint'),
array('name' => 'isRing'),
array('name' => 'isClosed'),
array('name' => 'numPoints'),
array('name' => 'pointN', 'argument' => '1'),
array('name' => 'exteriorRing'),
array('name' => 'numInteriorRings'),
array('name' => 'interiorRingN', 'argument' => '1'),
array('name' => 'dimension'),
array('name' => 'geometryType'),
array('name' => 'SRID'),
array('name' => 'setSRID', 'argument' => '4326'),
);
foreach($methods as $method) {
$argument = NULL;
$method_name = $method['name'];
if (isset($method['argument'])) {
$argument = $method['argument'];
}
$this->_methods_tester($geometry, $method_name, $argument, $file);
}
$this->_methods_tester_with_geos($geometry);
}
}
}
function _methods_tester($geometry, $method_name, $argument, $file) {
if (!method_exists($geometry, $method_name)) {
$this->fail("Method ".$method_name.'() doesn\'t exists.');
return;
}
switch ($method_name) {
case 'y':
case 'x':
if (!$geometry->isEmpty()) {
if ($geometry->geometryType() == 'Point') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
}
break;
case 'geometryN':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'startPoint':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
//TODO: Add a method startPoint() to MultiLineString.
//$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'endPoint':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
//TODO: Add a method endPoint() to MultiLineString.
//$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name);
}
break;
case 'isRing':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'isClosed':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'pointN':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
//TODO: Add a method pointN() to MultiLineString.
//$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'exteriorRing':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'numInteriorRings':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'interiorRingN':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'SRID':
break;
case 'getBBox':
if (!$geometry->isEmpty()) {
if ($geometry->geometryType() == 'Point') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
}
break;
case 'centroid':
if ($geometry->geometryType() == 'Point') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'length':
if ($geometry->geometryType() == 'Point') {
$this->assertEquals($geometry->$method_name($argument), 0, 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotEquals($geometry->$method_name($argument), 0, 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotEquals($geometry->$method_name($argument), 0, 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'numGeometries':
if ($geometry->geometryType() == 'Point') {
$this->assertNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'numPoints':
if ($geometry->geometryType() == 'Point') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'dimension':
if ($geometry->geometryType() == 'Point') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'boundary':
if ($geometry->geometryType() == 'Point') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'haversineLength':
//TODO: Check if output is a float >= 0.
//TODO: Sometimes haversineLength() returns NAN, needs to check why.
break;
case 'greatCircleLength':
case 'area':
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
break;
case 'geometryType':
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
break;
case 'setSRID':
//TODO: The method setSRID() should return TRUE.
break;
default:
$this->assertTrue($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
}
function _methods_tester_with_geos($geometry) {
// Cannot test methods if GEOS is not intstalled
if (!geoPHP::geosInstalled()) return;
$methods = array(
//'boundary', //@@TODO: Uncomment this and fix errors
'envelope', //@@TODO: Testing reveales errors in this method -- POINT vs. POLYGON
'getBBox',
'x',
'y',
'startPoint',
'endPoint',
'isRing',
'isClosed',
'numPoints',
);
foreach ($methods as $method) {
// Turn GEOS on
geoPHP::geosInstalled(TRUE);
$geos_result = $geometry->$method();
// Turn GEOS off
geoPHP::geosInstalled(FALSE);
$norm_result = $geometry->$method();
// Turn GEOS back On
geoPHP::geosInstalled(TRUE);
$geos_type = gettype($geos_result);
$norm_type = gettype($norm_result);
if ($geos_type != $norm_type) {
$this->fail('Type mismatch on '.$method);
$this->dump($geos_type);
$this->dump($norm_type);
continue;
}
// Now check base on type
if ($geos_type == 'object') {
$haus_dist = $geos_result->hausdorffDistance(geoPHP::load($norm_result->out('wkt'),'wkt'));
// Get the length of the diagonal of the bbox - this is used to scale the haustorff distance
// Using Pythagorean theorem
$bb = $geos_result->getBBox();
$scale = sqrt((($bb['maxy'] - $bb['miny'])^2) + (($bb['maxx'] - $bb['minx'])^2));
// The difference in the output of GEOS and native-PHP methods should be less than 0.5 scaled haustorff units
if ($haus_dist / $scale > 0.5) {
$this->fail('Output mismatch on '.$method);
$this->dump('GEOS : ');
$this->dump($geos_result->out('wkt'));
$this->dump('NORM : ');
$this->dump($norm_result->out('wkt'));
continue;
}
}
if ($geos_type == 'boolean' || $geos_type == 'string') {
if ($geos_result !== $norm_result) {
$this->fail('Output mismatch on '.$method);
$this->dump('GEOS : ');
$this->dump((string) $geos_result);
$this->dump('NORM : ');
$this->dump((string) $norm_result);
continue;
}
}
//@@TODO: Run tests for output of types arrays and float
//@@TODO: centroid function is non-compliant for collections and strings
}
}
}

View file

@ -0,0 +1,60 @@
<?php
require_once('../geoPHP.inc');
class PlaceholdersTests extends PHPUnit_Framework_TestCase {
function setUp() {
}
function testPlaceholders() {
foreach (scandir('./input', SCANDIR_SORT_NONE) as $file) {
$parts = explode('.',$file);
if ($parts[0]) {
$format = $parts[1];
$value = file_get_contents('./input/'.$file);
echo "\nloading: " . $file . " for format: " . $format;
$geometry = geoPHP::load($value, $format);
$placeholders = array(
array('name' => 'hasZ'),
array('name' => 'is3D'),
array('name' => 'isMeasured'),
array('name' => 'isEmpty'),
array('name' => 'coordinateDimension'),
array('name' => 'z'),
array('name' => 'm'),
);
foreach($placeholders as $method) {
$argument = NULL;
$method_name = $method['name'];
if (isset($method['argument'])) {
$argument = $method['argument'];
}
switch ($method_name) {
case 'hasZ':
if ($geometry->geometryType() == 'Point') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'LineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
if ($geometry->geometryType() == 'MultiLineString') {
$this->assertNotNull($geometry->$method_name($argument), 'Failed on ' . $method_name .' (test file: ' . $file . ')');
}
break;
case 'm':
case 'z':
case 'coordinateDimension':
case 'isEmpty':
case 'isMeasured':
case 'is3D':
}
}
}
}
}
}