GeoJSON implementation for PHP

Last update: Aug 4, 2022

GeoJson PHP Library

Build Status Scrutinizer Code Quality Code Coverage

This library implements the GeoJSON format specification.

The GeoJson namespace includes classes for each data structure defined in the GeoJSON specification. Core GeoJSON objects include geometries, features, and collections. Geometries range from primitive points to more complex polygons. Classes also exist for bounding boxes and coordinate reference systems.

Installation

The library is published as a package and is installable via Composer:

$ composer require "jmikola/geojson=~1.0"

More Resources

GitHub

https://github.com/jmikola/geojson
Comments
  • 1. Apply language level migrations and clean-ups

    Hey there 👋,

    as promised (threatened 😅), here's my follow-up PR. Since we can now expect to be on at least PHP 7.4 and PHPUnit 9.5, there are some improvements that can be applied.

    I tried to be as atomic as possible, with each commit message describing what it is about, but I think some of the changes warrant a little more context:

    • Since we now have type-hints, PHPDocs are even more meant for documentation rather than support for IDEs or API Doc generation. That's the reason why I removed all property, argument and return value annotations that are already visible through the type hints.
    • There's no need for reflection or func_get_args() anymore \o/
    • According to the RFC, the "id" property of a Feature is expected to be a JSON string or a number (https://www.rfc-editor.org/rfc/rfc7946#section-3.2), so I added a check for this. This would be a breaking change, so if you're targeting a 1.1 release instead of a 2.0 release, I can remove the check again.
    • Testing the unhappy paths of the GeoJson::unserialize() method is not strictly part of the language level migration, but it was the only method that prevented a 100% code coverage and even if its importance can be disputed, I still think that it's a nice metric 😅
    • The array<...> notation in DocBlocks is used to avoid consecutive [][][]s and to make it a little bit easier to make out the supported types - especially for the nested ones. The changes should enable IDEs like PHPStorm to provide autocompletion and Static Code Analysis Tools like PHPStan to parse them.

    :octocat:

    Closes #21 Closes #22 Closes #30

    Reviewed by jeromegamez at 2022-01-21 23:26
  • 2. PHP warning when Polygon is created from invalid data

    When not correct data is used to create Polygon following php warning is shown

    new \GeoJson\Geometry\Polygon([[2,4]]);
    
    PHP Warning:  array_map(): An error occurred while invoking the map callback in ...
    

    I suggest removing array_map in Polygon constructor in favor of using foreach to create coordinates array for polygon.

    See php bug related to throwing Exception in array_map callback - https://bugs.php.net/bug.php?id=55416

    Reviewed by munkie at 2015-08-11 10:46
  • 3. Installation guidelines for composer should be updated

    In https://github.com/jmikola/geojson#installation

    From:

    $ composer require "jmikola/geojson=~1.0"
    

    to

    
    "jmikola/geojson": "1.0.*@dev"
    
    

    I have figured it out now but before I have downloaded with composer an old version with some bug. I even wrote an issue post with how to solve this bug! ;)

    Reviewed by Conradaek at 2014-09-02 20:12
  • 4. Add Travis build for PHP 5.3.3

    As I have failed tests on my computer with PHP 5.3.3, I'd like to run them on Travis to see if it works.

    [email protected]:~/lamp/oss/geojson$ php -v
    PHP 5.3.3-7+squeeze14 with Suhosin-Patch (cli) (built: Aug  6 2012 14:18:06) 
    Copyright (c) 1997-2009 The PHP Group
    Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies
        with Xdebug v2.1.0, Copyright (c) 2002-2010, by Derick Rethans
        with Suhosin v0.9.32.1, Copyright (c) 2007-2010, by SektionEins GmbH
    
    [email protected]:~/lamp/oss/geojson$ bin/phpunit 
    PHPUnit 3.7.28 by Sebastian Bergmann.
    
    Configuration read from /home/gnutix/lamp/oss/geojson/phpunit.xml.dist
    
    FF.........FF.............................FF...................  63 / 112 ( 56%)
    .................................................
    
    Time: 57 ms, Memory: 11.25Mb
    
    There were 6 failures:
    
    1) GeoJson\Tests\BoundingBoxTest::testIsJsonSerializable
    Failed asserting that false is true.
    
    /home/gnutix/lamp/oss/geojson/tests/GeoJson/Tests/BoundingBoxTest.php:11
    
    2) GeoJson\Tests\BoundingBoxTest::testIsJsonUnserializable
    Failed asserting that false is true.
    
    /home/gnutix/lamp/oss/geojson/tests/GeoJson/Tests/BoundingBoxTest.php:16
    
    3) GeoJson\Tests\CoordinateReferenceSystem\CoordinateReferenceSystemTest::testIsJsonSerializable
    Failed asserting that false is true.
    
    /home/gnutix/lamp/oss/geojson/tests/GeoJson/Tests/CoordinateReferenceSystem/CoordinateReferenceSystemTest.php:14
    
    4) GeoJson\Tests\CoordinateReferenceSystem\CoordinateReferenceSystemTest::testIsJsonUnserializable
    Failed asserting that false is true.
    
    /home/gnutix/lamp/oss/geojson/tests/GeoJson/Tests/CoordinateReferenceSystem/CoordinateReferenceSystemTest.php:22
    
    5) GeoJson\Tests\GeoJsonTest::testIsJsonSerializable
    Failed asserting that false is true.
    
    /home/gnutix/lamp/oss/geojson/tests/GeoJson/Tests/GeoJsonTest.php:11
    
    6) GeoJson\Tests\GeoJsonTest::testIsJsonUnserializable
    Failed asserting that false is true.
    
    /home/gnutix/lamp/oss/geojson/tests/GeoJson/Tests/GeoJsonTest.php:16
    
    FAILURES!
    Tests: 112, Assertions: 418, Failures: 6.
    
    Reviewed by gnutix at 2013-11-07 16:01
  • 5. Drop support for PHP <7.4, update PHPUnit to ~9.5, migrate to GitHub Actions

    Hey there 👋,

    while working on a PHP 8.1 project, I noticed the following deprecation message

    PHP Deprecated: Return type of GeoJson\GeoJson::jsonSerialize() should either be compatible with JsonSerializable::jsonSerialize(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice in /path/to/code/vendor/jmikola/geojson/src/GeoJson/GeoJson.php on line 64

    the reason probably being the JsonSerializable stub, and I thought this might be an excellent opportunity to propose a 1.1 release of this library.

    I tried to keep the changes as atomic as possible and as minimal as needed, just enough to support the updated dependencies, which are:

    • The minimum required PHP version is now 7.4 because it hasn't quite yet reached its end of life
    • Updated PHPUnit vom ~3.7 to ~9.5
    • Removed obsolete JsonSerializable stub
    • Removed API Doc generation with Apigen (Apigen doesn't support newer PHP versions and hasn't received updates in quite some time - clicking through GitHub or downloading the source code to open it in one's favorite editor should be sufficient)
    • Updated MkDocs configuration (the spacelab theme is not included in MkDocs anymore, and I couldn't find it elsewhere)
    • Migrated the defunct Travis CI configuration to a GitHub actions workflow (including PHP 8.2 tests)
    • Partially reverted the changes in #24, because they, unfortunately, broke the tests.

    This PR supersedes #27 and #29.

    I'd greatly appreciate it if you could let me know if you could see these changes in a 1.1 release 🙏 . I have more improvements in mind (and already prepared 😅), e.g., updated usage of language features and type checks, but I didn't want to blow this PR more than necessary.

    Thank you! :octocat:

    Reviewed by jeromegamez at 2022-01-18 00:04
  • 6. Documentation is missing

    Is the README the only documentation for this library? I don't think I should have to leaf through the test code to find out that a Feature is instantiated with new \GeoJson\Feature\Feature($geometry, $properties, $id); but how would I know the ordering of the arguments otherwise?

    Reviewed by martinburch at 2014-06-12 16:34
  • 7. PHP 8.1: Return type of GeoJson\GeoJson::jsonSerialize()

    When using PHP 8.1, i get the following log message :

    Deprecated: Return type of GeoJson\GeoJson::jsonSerialize() should either be compatible with JsonSerializable::jsonSerialize(): mixed, or the #[\ReturnTypeWillChange] attribute should be used to temporarily suppress the notice
    

    I appears all the class extending \JsonSerializable and implementing the "jsonSerializer" method needs their return to be explicitly typed to "mixed" for this deprecation to disappear.

    Reviewed by jcrombez at 2022-03-14 12:01
  • 8. Errors trying to jsonSerialize in PHP 5.3

    The readme says "jsonSerialize() will need to be manually called and its return value passed to json_encode()."

    <?php
    require 'vendor/autoload.php';
    $point = new \GeoJson\Geometry\Point(array(1, 1));
    $json = json_encode(\GeoJson\GeoJson::jsonSerialize($point));
    print($json);
    

    Produces two errors PHP Strict Standards: Non-static method GeoJson\GeoJson::jsonSerialize() should not be called statically in /path/file.php on line 4 PHP Fatal error: Using $this when not in object context in /path/vendor/jmikola/geojson/src/GeoJson/GeoJson.php on line 66

    Please advise.

    Reviewed by martinburch at 2014-06-12 15:42
  • 9. Ignore files when exporting package

    This commit is part of a campaign to reduce the amount of data transferred to save global bandwidth and reduce the amount of CO2. See https://github.com/Codeception/Codeception/pull/5527 for more info.

    Reviewed by simonschaufi at 2020-06-06 23:37
  • 10. Patch release

    Would be nice to have a patch release. I just ran into https://github.com/jmikola/geojson/commit/844e43abf14b871e7e50a216f6f357f1fbf76f1b which was fixed 4 years ago.

    Reviewed by JeroenDeDauw at 2020-02-13 23:57
  • 11. Adjusting constructor for multiple arguments

    The code in Point seems more complicated than necessary. It may be good to modify the constructor so that it's more clear how to structure data going into the class. For instance:

        public function __construct(
            $latitude,
            $longitude,
            CoordinateReferenceSystem $crs = null,
            BoundingBox $box = null
        ) {
            $this->coordinates = [
                $latitude,
                $longitude
            ];
    
    Reviewed by bkuhl at 2016-07-24 01:36
  • 12. enhance php8.1 support

    added #[\ReturnTypeWillChange] attributes to jsonSerialize()-methods to avoid php8.1 deprecation notes.

    phpCS/Beautifier fails because of not imported ReturnTypeWillChange class, but it is only available with php8.1.

    Reviewed by ThomasEnssner at 2022-05-12 19:15
  • 13. Improved documentation

    Hello!

    I try to use this package, but the examples in the USAGE.md file is not clear for me...

    In my case I need to extract points from database and then serve as API to the client, that's show a map with a mapbox gl implementation.

    Can you please let me an real example? If you can... In the meantime I'll try to deal with this. If I can reach my goal I'll a PR with my usage example.

    Thanks in advance. Regards.

    Reviewed by nonDeath at 2022-05-12 14:22
  • 14. Remove CoordinateReferenceSystem classes

    As discussed in https://github.com/jmikola/geojson/pull/33#issuecomment-1018947287, RFC7946 states:

    B.1. Normative Changes

    Specification of coordinate reference systems has been removed, i.e., the "crs" member of [GJ2008] is no longer used.

    If CRS is no longer part of the GeoJSON spec, we can consider removing these classes altogether.

    Reviewed by jmikola at 2022-04-01 02:52
  • 15. Validate Feature "id" property as string or number

    As discussed in #33:

    According to the RFC, the "id" property of a Feature is expected to be a JSON string or a number (https://www.rfc-editor.org/rfc/rfc7946#section-3.2), so I added a check for this. This would be a breaking change, so if you're targeting a 1.1 release instead of a 2.0 release, I can remove the check again.

    That change was ultimately not included in #33 since it would be a BC break, but this can be considered for 2.0.

    Reviewed by jmikola at 2022-04-01 02:47
  • 16. MultiPolygon not parsing although appearing to be valid

    Hello

    I am having an issue parsing the following GeoJSON ...

    https://gist.github.com/sptdigital/f0b7102bae5e9d72c3845b406c323951

    It returns the error message LinearRing requires at least four positions, even though my LinearRings are compliant with the latest version of the GeoJson standard as far as I can see.

    I have no issues using this GeoJson anywhere outside of this package.

    Could you possibly point me in the right direction please?

    Thanks, Ally

    Reviewed by sptdigital at 2019-02-28 12:47
Related tags
PHP Extension to handle common geospatial functions.

geospatial - PHP Geospatial Extension PHP Extension to handle common geospatial functions. The extension currently has implementations of the Haversin

Aug 11, 2022
ESRI ShapeFile library for PHP

shapefile ShapeFile library for PHP Features Currently the 2D and 3D variants except MultiPatch of the ShapeFile format as defined in https://www.esri

Jun 29, 2022
The most featured Geocoder library written in PHP.

Geocoder Important: You are browsing the documentation of Geocoder 4.x. Documentation for version 3.x is available here: Geocoder 3.x documentation. D

Aug 9, 2022
Simple Yet Powerful Geo Library for PHP

phpgeo - A Simple Geo Library for PHP phpgeo provides abstractions to geographical coordinates (including support for different ellipsoids) and allows

Jul 29, 2022
Geo-related tools PHP 5.4+ library built atop Geocoder and React libraries

Geotools Geotools is a PHP geo-related library, built atop Geocoder and React libraries. Features Batch geocode & reverse geocoding request(s) in seri

Aug 7, 2022
PHP library to access the OpenCage geocoding API
PHP library to access the OpenCage geocoding API

OpenCage Geocoding API Library for PHP A PHP library to use the OpenCage geocoding API. Build Status / Code Quality Overview This library attempts to

Jun 20, 2022
PHP library for determining the physical location of binaries

Bin Locator Library for searching binary files in the operating system. Requirements PHP >= 7.4 Installation Library is available as composer reposito

Jul 27, 2022
PHP library to easily get static image from French Cadastral Government map with markers and lines.
PHP library to easily get static image from French Cadastral Government map with markers and lines.

PHP French Cadastral Map Static API PHP library to easily get static image from French Cadastral Government map with markers and lines. Map source : c

May 24, 2022
PHP library to easily get static image from OpenStreetMap (OSM) with markers and lines.
PHP library to easily get static image from OpenStreetMap (OSM) with markers and lines.

PHP OpenStreetMap Static API PHP library to easily get static image from OpenStreetMap with markers and lines. ✨ Supporting ⭐ Star this repository to

Jul 28, 2022
Official PHP library for IPinfo (IP geolocation and other types of IP data)

This is the official PHP client library for the IPinfo.io IP address API, allowing you to lookup your own IP address,

Aug 14, 2022
A PHP implementation of the GraphQL specification based on the JavaScript reference implementation

GraphQL This is a PHP implementation of the GraphQL specification based on the JavaScript reference implementation. Related projects DateTime scalar R

May 4, 2022
A PHP VM implementation in PHP
A PHP VM implementation in PHP

PHPPHP A PHP VM implementation written in PHP. This is a basic VM implemented in PHP using the AST generating parser developed by @nikic To see what's

Jul 28, 2022
Retrofit implementation in PHP. A REST client for PHP.

Retrofit PHP Retrofit is a type-safe REST client. It is blatantly stolen from square/retrofit and implemented in PHP. ❗ UPGRADE NOTICE ❗ Version 3 int

Jun 18, 2022
Zipkin PHP is the official PHP Tracer implementation for Zipkin

Zipkin PHP is the official PHP Tracer implementation for Zipkin, supported by the OpenZipkin community. Installation composer require openz

Aug 9, 2022
A pure PHP implementation of the MessagePack serialization format / msgpack.org[PHP]

msgpack.php A pure PHP implementation of the MessagePack serialization format. Features Fully compliant with the latest MessagePack specification, inc

Jul 26, 2022
Php-rpc-server - JSON RPC server implementation for PHP.

JSON RPC Server implementation for PHP. The json-rpc is a very simple protocol. You can see this by reading the protocol specification. This library i

Mar 8, 2022
A pure PHP implementation of the open Language Server Protocol. Provides static code analysis for PHP for any IDE.
A pure PHP implementation of the open Language Server Protocol. Provides static code analysis for PHP for any IDE.

A pure PHP implementation of the open Language Server Protocol. Provides static code analysis for PHP for any IDE.

Aug 7, 2022
Pure PHP implementation of GraphQL Server – Symfony Bundle

Symfony GraphQl Bundle This is a bundle based on the pure PHP GraphQL Server implementation This bundle provides you with: Full compatibility with the

Aug 14, 2022
Powerful implementation of the Specification pattern in PHP

RulerZ The central idea of Specification is to separate the statement of how to match a candidate, from the candidate object that it is matched agains

Jul 26, 2022
A PHP implementation of bower :bird:

Bowerphp An implementation of bower in PHP. https://bowerphp.github.io/ Installation $ composer require beelab/bowerphp Configuration Currently, you c

Apr 16, 2022