creof / doctrine2-spatial Goto Github PK
View Code? Open in Web Editor NEWDoctrine2 multi-platform support for spatial types and functions.
License: MIT License
Doctrine2 multi-platform support for spatial types and functions.
License: MIT License
When I attempt to use the multipolygon type for mysql, I get errors because the referenced classes are missing. I made a branch where this issue is fixed, by creating the classes needed. I'd be happy to push the branch, provided permission.
Hi,
on muka@4844d59
I've added some MySql specific function. Please consider if they can be useful to the project.
Thank your.
Regards
array:564 [
0 => array:2 [
0 => -73.698313
1 => 45.546876
]
1 => array:2 [
0 => -73.69813
1 => 45.546916
]
2 => array:2 [
0 => -73.697656
1 => 45.546899
]
3 => array:2 [
0 => -73.697413
1 => 45.546899
]
$poly = new Polygon($array);
What's the problem I don't understand at all, theres like no doc telling you how to create a polygon
Problem fixed - error in my config.yml spacing.
example:
$rsm = new ResultSetMapping;
$rsm->addEntityResult('FarmField\Entity\Field', 'f');
$rsm->addFieldResult('f', 'id', 'id');
$rsm->addFieldResult('f', 'name', 'name');
$rsm->addFieldResult('f', 'polygon', 'polygon');
$sql = "SELECT f.* FROM `fields` f";
$query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
$result = $query->getResult();
return $result;
In database polygon column contains a POLYGON but in result I get POINT.
Not native query returns correctly a polygon. Or maybe my sql is not correct?
Tests now passing with doctrine/orm <2.5.
Hello,
i have this error when trying a query with the "contains" function
firstly, if i put this :
dql:
numeric_functions:
Contains: CrEOF\Spatial\ORM\Query\AST\Functions\MySql\Contains
under orm like in doc, i have this error :
[Symfony\Component\Config\Definition\Exception\InvalidConfigurationException]
Unrecognized options "dql" under "doctrine.orm"
but if i put it under doctrine.orm.entity_managers.default there is no error but i still have an error when running the query, here is my code :
$sql = 'SELECT DemoTadBundle:DeliveryZone dz WHERE Contains(dz.area, :point)'; //dz.area is of type polygon
$converter = new SpatialConverter();
$q = $this->_em->createQuery($sql)->setParameter('point', $converter->convertToDatabaseValue($address->getPoint())); //$address->getPoint returns an CrEOF\Spatial\PHP\Types\Geometry\Point object
return $q->getOneOrNullResult();
and here is the error :
[Semantical Error] line 0, col 41 near 'Contains(dz.area,': Error: Class 'Contains' is not defined.
can someone help me to resolve this problem ?
my symfony version is 2.5
thank you.
Tests now passing with doctrine/orm <2.5.
OrmTest no longer extends from doctrine/orm. Replace property access in tests with getters.
Tests still failing with Doctrine 2.5, next on the list.
When I execute a native query in a table (PostgreSQL) containing a field of type 'point' the following exception occurs:
ContextErrorException: Catchable Fatal Error: Argument 1 passed to CrEOF\Spatial\Exception\InvalidValueException::invalidType() must implement interface CrEOF\Spatial\PHP\Types\Geometry\GeometryInterface, string given, called in (...)/vendor/creof/doctrine2-spatial/lib/CrEOF/Spatial/DBAL/Types/Geometry/Platforms/PostgreSql.php on line 80 and defined in (...)/vendor/creof/doctrine2-spatial/lib/CrEOF/Spatial/Exception/InvalidValueException.php line 45
Tests now passing with doctrine/orm <2.5.
Actually implemented
Instead X should represent the latitude, Y the longitude. This is even how it is stated in the first lines of lib/CrEOF/Spatial/PHP/Types/AbstractPoint.php:
/**
* @var float $latitude
*/
protected $x;
/**
* @var float $longitude
*/
protected $y;
Hi,
are mutipolygons supported ? It seems that Multipolygon type doesn't exist.
Is it planned ?
Thx
I've noticed that Doctrine doesn't pickup classes with the underscore eg ST_*
Refactored class names to ST* (Follow up of #11)
Best, Luca
Hello,
I have a problem with simple queries ...
here is my entity
/**
* @Entity
* @Table(name="ver2.shapes")
*/
class Shape
{
/**
* @Id
* @Column(type="integer")
* @GeneratedValue
*/
protected $id;
/**
* @Column(type="string")
*/
protected $name;
/**
* @Column(type="geometry")
*/
protected $geom;
/**
* @return int
*/
function getId(){
return $this->id;
}
/**
* @return string
*/
function getName(){
return $this->name;
}
/**
* @return string
*/
function getGeom(){
return $this->geom;
}
and simple query
$em->createQueryBuilder()->select('s')->from('Model\Shape','s')->setFirstResult($start)->setMaxResults($limit)->getQuery()->getResult();
and exception
Warning: pack() [<a href='function.pack'>function.pack</a>]: Type H: illegal hex digit x in C:\Program Files (x86)\Zend\Apache2\htdocs\backend_rest\vendor\creof\doctrine2-spatial\lib\CrEOF\Spatial\DBAL\Types\BinaryReader.php on line
and some exception stack
CrEOF\Spatial\DBAL\Types\BinaryParser->__construct( )
C:\Program Files (x86)\Zend\Apache2\htdocs\backend_rest\vendor\creof\doctrine2-spatial\lib\CrEOF\Spatial\DBAL\Types\Platforms\AbstractPlatform.php ..\AbstractPlatform.php 54
CrEOF\Spatial\DBAL\Types\BinaryReader->__construct( )
C:\Program Files (x86)\Zend\Apache2\htdocs\backend_rest\vendor\creof\doctrine2-spatial\lib\CrEOF\Spatial\DBAL\Types\BinaryParser.php ..\BinaryParser.php 69
CrEOF\Spatial\DBAL\Types\BinaryReader->setInput( )
C:\Program Files (x86)\Zend\Apache2\htdocs\backend_rest\vendor\creof\doctrine2-spatial\lib\CrEOF\Spatial\DBAL\Types\BinaryReader.php ..\BinaryReader.php 54
pack ( )
C:\Program Files (x86)\Zend\Apache2\htdocs\icar2\backend_rest\vendor\creof\doctrine2-spatial\lib\CrEOF\Spatial\DBAL\Types\BinaryReader.php' bgcolor='#eeeeec'>..\BinaryReader.php 128
and sql query that is ok
select ST_AsEWKB(s.geom) from ver2.shapes as s;
return
\001\003\000\000\000\001\000\000\000\005\000\000\000\317\202P\336\307\027J@\343n\020\255\025\3214@\373\\m\305\376\200I@x\016e\250\212=5@P\304"\206\035\024J@\243\224\020\254\252\3774@\004q\036N`$J@\006\330G\247\256\3544@\317\202P\336\307\027J@\343n\020\255\025\3214@
I run this under Win 7, PostgreSQL 9.1 and Postgis 1.5, php is 5.3.14
Best regards,
patS
Postgres prior to 9.0 does not support type hints for the geometry/geography type, i.e.:
center geometry(POINT) NOT NULL -- fails
while
center geometry NOT NULL -- works
A simple change in PostgreSql.php (line 55) would fix this - but then it is missing for 9.x. I don't know how to test the version or if it is even possible, so I'm just putting this information here for now.
I've noticed that Doctrine doesn't pickup classes with the underscore eg ST_*
Refactored class names to ST* (Follow up of #11)
Best, Luca
I didn't offer them as a pull request because it includes some composer package info that I changed, so I could use the improvements and still treat it like an external package.
Hi,
I was wondering what would it take to implement support:
https://www.gaia-gis.it/fossil/libspatialite/index
Bests,
Yoanis.
I, this is a question, not a bug.
I'm setting up the module with ZF2 but I couldn't find any way to create a new instance of the object (Point) inside my entity.
While this is true for ZF2 I think it will also be true to SF2.
In my conf I have
'configuration' => array(
'orm_default' => array(
'types' => array(
'Point' => 'CrEOF\Spatial\DBAL\Types\Geometry\PointType'
)
)
),
'connection' => array(
'orm_default' => array(
'doctrine_type_mappings' => array(
'Point' => 'Point'
),
)
)
My problem is that I want to create a new instance of my entity (Place) that has a column (Coordinates) whose type is Point and I want to populate it with values to store on the database:
$placeEntity = $this->getServiceLocator()->get('placeEntity');
$placeEntity->setName('foo');
$placeEntity->setAddress('bar');
etc...
In order to call $placeEntity->setCoordinates($coordinatesObject)
I have to know what kind of object $coordinatesObject has to be. While I know that it will always be a CrEOF\Spatial\PHP\Types\Geometry\Point
I don't like the idea of hardcode this, because latter I might want to replace the plugin or override the class and this would prevent me.
Is there any way to know what object type should be instantiate for any column with a custom type?
Thanks
after configure it follow the document, the doctrine generate my scheme as well. But when I trying to update/drop the schema it throw me an fatal error:
$ php app/console doctrine:schema:drop
ATTENTION: This operation should not be executed in a production environment.
[Doctrine\DBAL\DBALException]
Unknown database type point requested, Doctrine\DBAL\Platforms\MySqlPlatform may not support it.
My symfony config file:
doctrine:
dbal:
...
types:
geometry: CrEOF\Spatial\DBAL\Types\GeometryType
point: CrEOF\Spatial\DBAL\Types\Geometry\PointType
polygon: CrEOF\Spatial\DBAL\Types\Geometry\PolygonType
linestring: CrEOF\Spatial\DBAL\Types\Geometry\LineStringType
Tests now passing with doctrine/orm <2.5.
Hello Derek / Jon,
First of all, thanks for your contribution for the spatial library, it's very useful !
We will be using the spatial library heavily in the next two years and we need to have a stable origin on where to work from.
I think it would be a good idea for the project to be moved to a neutral location where a few moderators could perform the merge and restart the release cycle. There is 10 PR+ waiting, and about 5 active forks which are all going in different directions...
I would suggest to @djlambert and @ddproxy merge their branches into a common 'neutral' project. Both major contributors would be administrator of the project.
I've created the organisation https://github.com/FriendsOfDoctrine/doctrine2-spatial to allow the project to continue growing and have active maintainers.
Let me know what you think,
Samuel
I am using this bundle successfully, but it took me (a new Symfony2 developer) several hours to sort out why I could update my doctrine's database schema but it would always fail validation.
The problem seems to have been related to the capitalization of the geometry type in the DB column comment: (DC2Type:Point)
or (DC2Type:Polygon)
.
Originally, I had used lowercase data type names throughout (except for the names of classes). I could get the schema to validate (after successfully updating it without a problem) only after changing the case of the comment: (DC2Type:Polygon)
became (DC2Type:polygon)
.
Now I've gotten closer to a more reliable fix... capitalization throughout.
types:
Geometry: CrEOF\Spatial\DBAL\Types\GeometryType
Point: CrEOF\Spatial\DBAL\Types\Geometry\PointType
Polygon: CrEOF\Spatial\DBAL\Types\Geometry\PolygonType
LineString: CrEOF\Spatial\DBAL\Types\Geometry\LineStringType
mapping_types:
geometry: Geometry
point: Point
polygon: Polygon
linestring: LineString
I have defined my columns in PHP annotations like this:
/**
* @var Point
*
* @ORM\Column(name="coordinates", type="Point", nullable=true)
*/
private $coordinates;
/**
* @var Polygon
*
* @ORM\Column(name="bounding_box", type="Polygon", nullable=true)
*/
private $boundingBox;
I don't really understand what I was doing wrong: why the types had to be capitalized when normally they can be lowercase? This fix also contradicts and expands on the installation instructions. If someone can get to the bottom of my mistake, I'd happily make a pull request that improves the installation instructions (at least for MySQL).
Can you add st_buffer and st_transform function to the extension?
It would be nice to have the composer.json available in http://packagist.org, so no advanced configuration has to be setup to use the library
Hi,
I got this error, when running with Postgres 9.3
(without postgis as we only need the point type for now) & Symfony 2.4
+ Doctrine 2.4.1
. Im using the latest commit in the master branch of this lib.
Any idea why ?
/**
* @var \stdClass
*
* @ORM\Column(name="coordinates", type="point")
*/
private $coordinates;
[Doctrine\ORM\Tools\ToolsException]
Schema-Tool failed with Error 'An exception occurred while executing 'CREATE TABLE city (id INT NOT NULL, name VARCHAR(255) NOT NULL, zipcode VARCHAR(255) NOT NULL, coordinates geometry(Point) NOT NULL, urbanArea_id INT DEFAULT NULL, PRIMARY KEY(id))':
SQLSTATE[42704]: Undefined object: 7 ERROR: type "geometry" does not exist at character 108' while executing DDL: CREATE TABLE city (id INT NOT NULL, name VARCHAR(255) NOT NULL, zipcode VARCHAR(255) NOT NULL, coordinates geometry(Point) NOT NULL, urbanArea_id INT DEFAULT NULL, PRIMARY KEY(id))
[Doctrine\DBAL\DBALException]
An exception occurred while executing 'CREATE TABLE city (id INT NOT NULL, name VARCHAR(255) NOT NULL, zipcode VARCHAR(255) NOT NULL, coordinates geometry(Point) NOT NULL, urbanArea_id INT DEFAULT NULL, PRIMARY KEY(id))':
SQLSTATE[42704]: Undefined object: 7 ERROR: type "geometry" does not exist at character 108
ception]
SQLSTATE[42704]: Undefined object: 7 ERROR: type "geometry" does not exist at character 108
Hi,
This is more of a question than an issue. I'm using symfony2 and mysql. I have Place entities (they have a point property), and I want to get all the places within a distance of a specific point, the distance depending on the place. I'm trying to use GLength and everything works fine as long as the linestring used in the parameter (like in the tests) is fixed, but I can't figure out how to use my places' points.
$base = new Point(1, 1);
$query = $em->createQuery('SELECT p FROM DpPlacesBundle:Place p WHERE GLength(GeomFromText(:p1)) < p.radius');
$query->setParameter('p1', new LineString(array($base, new Point(1, 1))), 'linestring');
$result = $query->getResult();
But this is of course useless, as I need to replace "new Point(1, 1)" in the linestring parameter by my entity point (p.point). How can this be done?
Thanks,
Alban
I am currently looking at some homebrew Geometry classes and checking whether they can be replaced by the Doctrine2-spatial classes.
Since I once created these classes to be able to deal with KML files, the 'Point' type also supports the optional 'z' axis, representing the 'altitude'
http://code.google.com/apis/kml/documentation/kmlreference.html#coordinates
Would it be a big problem to add support for this to the Doctrine2-spatial Point type? Or is this a 'no-go-area' ;)? When no problem, I can try to find some time to come up with a PR.
Cheers.
Hi,
I'm missing some information about licencing. It would be great if you could provide a licence soon.
Thank you,
Nabil
The file content of https://github.com/djlambert/doctrine2-spatial/blob/master/lib/CrEOF/Spatial/ORM/Query/AST/Functions/PostgreSql/STClosestDistance.php does not incude the class STClosestDistance
, but a (almost) duplicate of STClosestPoint
.
This will cause PHP to crash when using both class. It will also generate error in API document generator (such as ApiGen). But most importantly it does not seem to make any sense in the first place and it's probably a copy/paste error.
According to PostGIS reference, the function does not exist at all. And it's never used within doctrine2-spatial itself (no unit-tests). So I would suggest to delete the file entirely.
Nice library you got here, thumbs up.
First issue I noticed when adding a Polygon type property to an Entity
Warning: include_once(CrEOF/Spatial/PHP/Types/Geometry/POLYGON.php)
The following functions take the Geometry type as unqualified classname:
CrEOF\Spatial\DBAL\Types\Platforms\AbstractPlatform::convertStringToPHPValue()
CrEOF\Spatial\DBAL\Types\Platforms\AbstractPlatform::convertBinaryToPHPValue()
For POLYGON this can be fixed by using ucfirst(strtolower($value['type'])) => 'Polygon', however, this wont be able to realize the more complex words:
MULTILINESTRING => MultiLineString
MULTIPOINT => MultiPoint
etc..
Since the information is already available in the AbstractGeometry class, the following function might help:
/**
* Get the unqualified classname for a Geometry type
*
* @see \CrEOF\Spatial\PHP\Types\AbstractGeometry
* @link http://php.net/manual/en/reflectionclass.getconstants.php
* @param string $type The Geometry type, for example: 'MULTILINESTRING'
* @return string The unqualified class name, for example: 'MultiLineString'
* @throws \Exception
*/
public function getUnqualifiedClassForGeometryType($type)
{
$r = new \ReflectionClass('\CrEOF\Spatial\PHP\Types\AbstractGeometry');
//Iterate over the associative array label -> value
foreach ($r->getConstants() as $label => $value) {
if ($label == $type) {
return $value;
}
}
throw new \Exception("Unsupported Geometry type used: '$type'");
}
When trying to install on the current Symfony2, I get this error message:
Writing lock file
Generating autoload files
[Doctrine\DBAL\DBALException]
Type to be overwritten point does not exist.
Script Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache handling the post-update-cmd event terminated with an exception
[RuntimeException]
An error occurred when executing the "'cache:clear --no-warmup'" command.
Tests now passing with doctrine/orm <2.5.
Tests now passing with doctrine/orm <2.5.
When are you planning to do a x.y.z numerical versions of the package?
It'd be nice to have the ability to "djlambert/doctrine2-spatial" : "0.1.*" so I can have the updates over time instead changing the version names for each revision.
I'd like to do something other than dev-master, preferably.
Currently I need the ST_SImplifiy function to work in DQL.
Is it coing anytime soon? I can give you a hand in writing if you point me in the right direction in your codebase
OrmTest no longer extends from doctrine/orm. Replace property access in tests with getters.
Tests still failing with Doctrine 2.5, next on the list.
Would be nice to have public API for converting WKT to PHP and PHP to WKT.
The best what is available now WKT to PHP:
$parser = new StringParser('POLYGON((54.889975 23.9272635,54.879792 24.010124,54.879409 23.839321,54.889975 23.9272635))');
$array = $parser->parse(); // return array with type and value
and PHP to WKT:
$polygon = new Polygon($rings);
echo sprintf('%s(%s)', strtoupper($polygon->getType()), $polygon);
So not so much. Unless I didn't found the right way to do this.
OrmTest no longer extends from doctrine/orm. Replace property access in tests with getters.
Tests still failing with Doctrine 2.5, next on the list.
I've noticed that Doctrine doesn't pickup classes with the underscore eg ST_*
Refactored class names to ST* (Follow up of #11)
Best, Luca
I'm getting the following error when reading what supposed to be a Polygon from my database. I really don't have much of a clue what's going on but before I delve in I thought I'd see if anyone else had bumped into this already. :)
PHP Warning: unpack(): Type d: not enough input, need 8, have 0 in vendor/creof/doctrine2-spatial/lib/CrEOF/Spatial/DBAL/Types/BinaryReader.php on line 64
Which leaves my with a Point (part of a Polygon) like this:
array(2) {
[0]=>
float(-35.4)
[1]=>
NULL
}
Perhaps I did something wrong when saving the data in the first place? Can't find any errors of it in my logs though.
When I want to save a polygon from string input I'm using this method in my Entity class to parse the string for me. I believe there are some string parsing methods included with this package, can I use them instead of this code? How? Too bad there's no doc explaining this or anything else, I was able to put this code together just by looking at the test files.
/**
* Set polygon
*
* @param string $polygon
* @return Area
*/
public function setPolygon($polygon)
{
$points = array();
foreach(explode(",", $polygon) as $point) {
$coordinates = explode(" ", $point);
echo"$coordinates[0], $coordinates[1] <br>";
$points[] = new Point($coordinates[0], $coordinates[1]);
}
$rings = array( new LineString($points));
$this->polygon = new Polygon($rings);
return $this;
}
Hi,
First of all, thank you for the library its work's great :)
In my form I have 2 fields. I transform those fields in a Point Object in each controller.
Does a best Way exist to have 2 fields (lat + long) in the view and to transform them in a Point object later ?
In advance thanks you for your help.
// FormType
$builder->add('lat', 'hidden', array(
'attr' => array('data-geo' => 'lat')
));
$builder->add('lng', 'hidden', array(
'attr' => array('data-geo' => 'lng')
));
// Controller
// add location
$lat = $user->getLat();
$lng = $user->getLng();
$point = new Point($lng, $lat, 4326);
$user->setLocation($point);
// user entity
/**
* @ORM\Entity
* @ORM\Table(name="tut_user")
* @UniqueEntity(fields="email", message="fos_user.email.already_used")
* @UniqueEntity(fields="username", message="fos_user.username.already_used")
*/
class User extends BaseUser {
/**
* @ORM\Column(type="point")
*/
protected $location;
public function getLocation() {
return $this->location;
}
public function setLocation(\CrEOF\Spatial\PHP\Types\Geography\Point $point) {
$this->location = $point;
}
}
Hi,
I am trying to use your lib in order to save the location of my entities. I tried to create a form for Symfony 2 that handle the POINT object but nothing happens. Even if I do in my controller :
$entity->getPoint()->setLatitude(5);
$this->getDoctrine()->getManager()->flush();
Nothing is being updated, so unfortunatly this prevent me to use the class. Is this because I use custom type? it seems that everything is implemented in the rules.
Hi,
is it intended, that points are set with a SRID of 0 in MySQL (or maybe not set at all)?
When I save a new Point with a given SRID to the database, the SRID is always 0 afterwards.
Greets,
spackmat
Hey!
I used your package to convert from binary to GeoJSON and back again, working great so far!
However, there was one line I had to modify in the core, so I guess it's a bug, perhaps I am just using the library incorrectly since I only use a couple of things from it, you decide =).
This returns something like 5,23523 50,1242124
The ,
needed to be a .
to make my DB stop returning errors when I tried to jam those coordinates in there, so I did a simple str_replace there (should have probably changed the toString method in the Point or something, but hey, this worked for my scenario.
Perhaps the package could support more methods like toGeoJSON and toSql, here is my very basic, initial code for doing that.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.