Home | Docs | Issue Tracker | FAQ | Download | |
Author: | Daniel Morissette |
---|---|
Contact: | dmorissette at mapgears.com |
Author: | Yewondwossen Assefa |
Contact: | yassefa at dmsolutions.ca |
Author: | Alan Boudreault |
Contact: | aboudreault at mapgears.com |
Revision: | $Revision$ |
Date: | $Date$ Note If you are using MapServer 5.6 and older, please refer to the PHP MapScript 5.6 documentation instead. Note If you are migrating your existing application that is based on MapServer 5.6 or older, to MapServer 6.0 or beyond, please read the PHP MapScript Migration Guide for important changes. |
Contents
This is a PHP module that makes MapServer’s MapScript functionalities available in a PHP Dynamically Loadable Library. In simple terms, this module will allow you to use the powerful PHP scripting language to dynamically create and modify map images in MapServer.
PHP 5.2.0 or more recent is required; since MapServer 6.0, support for PHP 4, PHP 5.0 and PHP 5.1 have been dropped. PHP MapScript was originally developed for PHP 3.0.14, and after MapServer 3.5 support for PHP 3 was dropped.
The module has been tested and used on Linux, Solaris, *BSD, and Windows.
The following MapServer constants are available:
The following class objects are available through PHP MapScript.
Class Objects can be returned by the layerObj class, or can be created using:
new classObj(layerObj layer [, classObj class])
or using the old constructor
classObj ms_newClassObj(layerObj layer [, classObj class])
The second argument class is optional. If given, the new class created will be a copy of this class.
Type | Name | Note |
---|---|---|
string | group | |
string | keyimage | |
labelObj | label | Removed (6.2) - use addLabel, getLabel, ... |
double | maxscaledenom | |
hashTableObj | metadata | |
double | minscaledenom | |
string | name | |
int | numlabels | read-only (since 6.2) |
int | numstyles | read-only |
int | status | MS_ON, MS_OFF or MS_DELETE |
string | template | |
string | title | |
int | type |
Add a labelObj to the classObj and return its index in the labels array.
New in version 6.2.
Return a reference to the labelObj at index in the labels array.
See the labelObj section for more details on multiple class labels.
New in version 6.2.
Fetch class metadata entry by name. Returns “” if no entry matches the name. Note that the search is case sensitive.
Note
getMetaData’s query is case sensitive.
Remove the labelObj at index from the labels array and return a reference to the labelObj. numlabels is decremented, and the array is updated.
New in version 6.2.
Update a class from a string snippet. Returns MS_SUCCESS/MS_FAILURE.
/*set the color */
$oClass->updateFromString('CLASS STYLE COLOR 255 0 255 END END');
Type | Name |
---|---|
double | buffer |
double | maxdistance |
string | region |
Instances of colorObj are always embedded inside other classes.
Type | Name |
---|---|
int | red |
int | green |
int | blue |
Instances of errorObj are created internally by MapServer as errors happen. Errors are managed as a chained list with the first item being the most recent error. The head of the list can be fetched using ms_GetErrorObj(), and the list can be cleared using ms_ResetErrorList()
Type | Name |
---|---|
int | code //See error code constants above |
string | message |
string | routine |
This example draws a map and reports all errors generated during the draw() call, errors can potentially come from multiple layers.
ms_ResetErrorList();
$img = $map->draw();
$error = ms_GetErrorObj();
while($error && $error->code != MS_NOERR)
{
printf("Error in %s: %s<br>\n", $error->routine, $error->message);
$error = $error->next();
}
The grid is always embedded inside a layer object defined as a grid (layer->connectiontype = MS_GRATICULE) (for more docs : https://github.com/mapserver/mapserver/wiki/MapServerGrid)
A layer can become a grid layer by adding a grid object to it using : ms_newGridObj(layerObj layer)
$oLayer = ms_newlayerobj($oMap);
$oLayer->set("name", "GRID");
ms_newgridobj($oLayer);
$oLayer->grid->set("labelformat", "DDMMSS");
Type | Name |
---|---|
string | labelformat |
double | maxacrs |
double | maxinterval |
double | maxsubdivide |
double | minarcs |
double | mininterval |
double | minsubdivide |
Instance of hashTableObj is always embedded inside the classObj, layerObj, mapObj and webObj. It is uses a read only.
$hashTable = $oLayer->metadata;
$key = null;
while ($key = $hashTable->nextkey($key))
echo "Key: ".$key." value: ".$hashTable->get($key)."<br/>";
Type | Name | Note |
---|---|---|
int | width | read-only |
int | height | read-only |
int | resolution | read-only |
int | resolutionfactor | read-only |
string | imagepath | |
string | imageurl |
Accessible only through the mapObj (map->getLabel()).
Type | Name | Note |
---|---|---|
int | classindex | read-only |
int | featuresize | read-only |
int | layerindex | read-only |
int | markerid | read-only |
int | numstyles | read-only |
int | shapeindex | read-only |
int | status | read-only |
string | text | read-only |
int | tileindex | read-only |
None
Accessible only through the mapObj (map->labelcache). This object is only used to give the possiblity to free the label cache (map->labelcache->freeCache())
Type | Name |
---|---|
int | align |
double | angle |
int | anglemode |
int | antialias |
int | autominfeaturesize |
colorObj | backgroundcolor (deprecated since 6.0) |
colorObj | backgroundshadowcolor (deprecated since 6.0) |
int | backgroundshadowsizex (deprecated since 6.0) |
int | backgroundshadowsizey (deprecated since 6.0) |
int | buffer |
colorObj | color |
string | encoding |
string | font |
int | force |
int | maxlength |
int | maxsize |
int | mindistance |
int | minfeaturesize |
int | minlength |
int | minsize |
int | numstyles |
int | offsetx |
int | offsety |
colorObj | outlinecolor |
int | outlinewidth |
int | partials |
int | position |
int | priority |
int | repeatdistance |
colorObj | shadowcolor |
int | shadowsizex |
int | shadowsizey |
int | size |
int | type |
int | wrap |
Get the attribute binding for a specified label property. Returns NULL if there is no binding for this property.
Example:
$oLabel->setbinding(MS_LABEL_BINDING_COLOR, "FIELD_NAME_COLOR");
echo $oLabel->getbinding(MS_LABEL_BINDING_COLOR); // FIELD_NAME_COLOR
Remove the attribute binding for a specfiled style property.
Example:
$oStyle->removebinding(MS_LABEL_BINDING_COLOR);
Set the attribute binding for a specified label property.
Example:
$oLabel->setbinding(MS_LABEL_BINDING_COLOR, "FIELD_NAME_COLOR");
This would bind the color parameter with the data (ie will extract the value of the color from the field called “FIELD_NAME_COLOR”
Layer Objects can be returned by the mapObj class, or can be created using:
layerObj ms_newLayerObj(MapObj map [, layerObj layer])
A second optional argument can be given to ms_newLayerObj() to create the new layer as a copy of an existing layer. If a layer is given as argument then all members of a this layer will be copied in the new layer created.
Type | Name | Note |
---|---|---|
int | annotate | |
hashTableObj | bindvals | |
string | classgroup | |
string | classitem | |
clusterObj | cluster | |
string | connection | |
int | connectiontype | read-only, use setConnectionType() to set it |
string | data | |
int | debug | |
int | dump | deprecated since 6.0 |
string | filteritem | |
string | footer | |
gridObj | grid | only available on a layer defined as grid (MS_GRATICULE) |
string | group | |
string | header | |
int | index | read-only |
int | labelcache | |
string | labelitem | |
double | labelmaxscaledenom | |
double | labelminscaledenom | |
string | labelrequires | |
string | mask | |
int | maxfeatures | |
double | maxscaledenom | |
hashTableObj | metadata | |
double | minscaledenom | |
string | name | |
int | num_processing | |
int | numclasses | read-only |
colorObj | offsite | |
int | opacity | |
projectionObj | projection | |
int | postlabelcache | |
string | requires | |
int | sizeunits | |
int | startindex | |
int | status | MS_ON, MS_OFF, MS_DEFAULT or MS_DELETE |
string | styleitem | |
double | symbolscaledenom | |
string | template | |
string | tileindex | |
string | tileitem | |
double | tolerance | |
int | toleranceunits | |
int | transform | |
int | type |
Fetch layer metadata entry by name. Returns “” if no entry matches the name. Note that the search is case sensitive.
Note
getMetaData’s query is case sensitive.
If the resultObj passed has a valid resultindex, retrieve shapeObj from a layer’s resultset. (You get it from the resultObj returned by getResult() for instance). Otherwise, it will do a single query on the layer to fetch the shapeindex
$map = new mapObj("gmap75.map");
$l = $map->getLayerByName("popplace");
$l->queryByRect($map->extent);
for ($i=0; $i<$l->getNumResults();$i++){
$s = $l->getShape($l->getResult($i));
echo $s->getValue($l,"Name");
echo "\n";
}
Called after msWhichShapes has been called to actually retrieve shapes within a given area. Returns a shape object or NULL on error.
$map = ms_newmapobj("d:/msapps/gmap-ms40/htdocs/gmap75.map");
$layer = $map->getLayerByName('road');
$status = $layer->open();
$status = $layer->whichShapes($map->extent);
while ($shape = $layer->nextShape())
{
echo $shape->index ."<br>\n";
}
$layer->close();
Add the string to the processing string list for the layer. The layer->num_processing is incremented by 1. Returns MS_SUCCESS or MS_FAILURE on error.
$oLayer->setprocessing("SCALE_1=AUTO");
$oLayer->setprocessing("SCALE_2=AUTO");
Same as setProjection(), but takes an OGC WKT projection definition string as input.
Note
setWKTProjection requires GDAL support
Update a layer from a string snippet. Returns MS_SUCCESS/MS_FAILURE.
/*modify the name */
$oLayer->updateFromString('LAYER NAME land_fn2 END');
/*add a new class*/
$oLayer->updateFromString('LAYER CLASS STYLE COLOR 255 255 0 END END END');
Type | Name | Note |
---|---|---|
int | height | |
colorObj | imagecolor | |
int | keysizex | |
int | keysizey | |
int | keyspacingx | |
int | keyspacingy | |
labelObj | label | |
colorObj | outlinecolor | Color of outline of box, -1 for no outline |
int | position | for embeded legends, MS_UL, MS_UC, ... |
int | postlabelcache | MS_TRUE, MS_FALSE |
int | status | MS_ON, MS_OFF, MS_EMBED |
string | template | |
int | width |
Type | Name | Note |
---|---|---|
int | numpoints | read-only |
Add a point to the end of line. Returns MS_SUCCESS/MS_FAILURE.
Note
the 3rd parameter m is used for measured shape files only. It is not mandatory.
Add a point to the end of line. Returns MS_SUCCESS/MS_FAILURE.
Note
the 4th parameter m is used for measured shape files only. It is not mandatory.
new mapObj(string map_file_name [, string new_map_path])
or using the old constructors
Note
By default, the SYMBOLSET, FONTSET, and other paths in the mapfile are relative to the mapfile location. If new_map_path is provided then this directory will be used as the base path for all the rewlative paths inside the mapfile.
Type | Name | Note |
---|---|---|
double | cellsize | |
int | debug | |
double | defresolution | pixels per inch, defaults to 72 |
rectObj | extent; | |
string | fontsetfilename | read-only, set by setFontSet() |
int | height | see setSize() |
colorObj | imagecolor | |
int | keysizex | |
int | keysizey | |
int | keyspacingx | |
int | keyspacingy | |
labelcacheObj | labelcache | no members. Used only to free the label cache (map->labelcache->free() |
legendObj | legend | |
string | mappath | |
int | maxsize | |
hashTableObj | metadata | |
string | name | |
int | numlayers | read-only |
outputformatObj | outputformat | |
projectionObj | projection | |
querymapObj | querymap | |
referenceMapObj | reference | |
double | resolution | pixels per inch, defaults to 72 |
scalebarObj | scalebar | |
double | scaledenom | read-only, set by drawMap() |
string | shapepath | |
int | status | |
string | symbolsetfilename | read-only, set by setSymbolSet() |
int | units | map units type |
webObj | web | |
int | width | see setSize() |
Returns a labelcacheMemberObj from the map given an index value (0=first label). Labelcache has to be enabled.
while ($oLabelCacheMember = $oMap->getLabel($i)) {
/* do something with the labelcachemember */
++$i;
}
Fetch metadata entry by name (stored in the WEB object in the map file). Returns “” if no entry matches the name.
Note
getMetaData’s query is case sensitive.
Process legend template files and return the result in a buffer.
See also
Process query template files and return the result in a buffer. Second argument generateimages is not mandatory. If not given it will be set to TRUE.
See also
Process the template file specified in the web object and return the result in a buffer. The processing consists of opening the template file and replace all the tags found in it. Only tags that have an equivalent element in the map object are replaced (ex [scaledenom]). The are two exceptions to the previous statement :
$tmparray["my_tag"] = "value_of_my_tag";
$map->processtemplate($tmparray, MS_FALSE);
Selects the output format to be used in the map. Returns MS_SUCCESS/MS_FAILURE.
Note
the type used should correspond to one of the output formats declared in the map file. The type argument passed is compared with the mimetype parameter in the output format structure and then to the name parameter in the structure.
Set map projection and coordinate system. Returns MS_SUCCESS or MS_FAILURE on error.
Parameters are given as a single string of comma-delimited PROJ.4 parameters. The argument : bSetUnitsAndExtents is used to automatically update the map units and extents based on the new projection. Possible values are MS_TRUE and MS_FALSE. By defualt it is set at MS_FALSE.
Same as setProjection(), but takes an OGC WKT projection definition string as input. Returns MS_SUCCESS or MS_FAILURE on error.
Note
setWKTProjection requires GDAL support
Zoom to a given XY postion. Returns MS_SUCCESS or MS_FAILURE on error.
Set the map extents to a given extents. Returns MS_SUCCESS or MS_FAILURE on error.
Zoom in or out to a given XY position so that the map is displayed at specified scale. Returns MS_SUCCESS or MS_FAILURE on error.
Instance of outputformatObj is always embedded inside the mapObj. It is uses a read only.
No constructor available (coming soon, see ticket 979)
Type | Name | Note |
---|---|---|
string | driver | |
string | extension | |
int | imagemode | MS_IMAGEMODE_* value. |
string | mimetype | |
string | name | |
int | renderer | |
int | transparent |
Add or Modify the format option list. return true on success.
$oMap->outputformat->setOption("OUTPUT_TYPE", "RASTER");
new OWSRequestObj()
or using the old constructor
request = ms_newOwsrequestObj();
Create a new ows request object.
Type | Name |
---|---|
int | numparams (read-only) |
int | type (read-only): MS_GET_REQUEST or MS_POST_REQUEST |
Add a request parameter, even if the parameter key was previousely set. This is useful when multiple parameters with the same key are required. For example :
$request->addparameter('SIZE', 'x(100)');
$request->addparameter('SIZE', 'y(100)');
Set a request parameter. For example :
$request->setparameter('REQUEST', 'GetMap');
Type | Name | Note |
---|---|---|
double | x | |
double | y | |
double | z | used for 3d shape files. set to 0 for other types |
double | m | used only for measured shape files - set to 0 for other types |
Set X,Y coordinate values.
Note
the 3rd parameter m is used for measured shape files only. It is not mandatory.
Set X,Y,Z coordinate values.
Note
the 4th parameter m is used for measured shape files only. It is not mandatory.
new projectionObj(string projectionString)
or using the old constructor
ProjectionObj ms_newProjectionObj(string projectionString)
Creates a projection object based on the projection string passed as argument.
$projInObj = ms_newprojectionobj("proj=latlong")
will create a geographic projection class.
The following example will convert a lat/long point to an LCC projection:
$projInObj = ms_newprojectionobj("proj=latlong");
$projOutObj = ms_newprojectionobj("proj=lcc,ellps=GRS80,lat_0=49,".
"lon_0=-95,lat_1=49,lat_2=77");
$poPoint = ms_newpointobj();
$poPoint->setXY(-92.0, 62.0);
$poPoint->project($projInObj, $projOutObj);
Type | Name | Note |
---|---|---|
colorObj | color | |
int | height | |
int | width | |
int | style | MS_NORMAL, MS_HILITE, MS_SELECTED |
rectObj are sometimes embedded inside other objects. New ones can also be created with:
new rectObj()
or using the old constructor
RectObj ms_newRectObj()
Note
the members (minx, miny, maxx ,maxy) are initialized to -1;
Type | Name |
---|---|
double | minx |
double | miny |
double | maxx |
double | maxy |
Type | Name |
---|---|
ColorObj | color |
int | height |
rectObj | extent |
string | image |
int | marker |
string | markername |
int | markersize |
int | maxboxsize |
int | minboxsize |
ColorObj | outlinecolor |
int | status |
int | width |
Type | Name | Note |
---|---|---|
int | classindex | read-only |
int | resultindex | read-only |
int | shapeindex | read-only |
int | tileindex | read-only |
None
Type | Name | Note |
---|---|---|
int | align | |
colorObj | backgroundcolor | |
colorObj | color | |
int | height | |
colorObj | imagecolor | |
int | intervals | |
labelObj | label | |
colorObj | outlinecolor | |
int | position | for embeded scalebars, MS_UL, MS_UC, ... |
int | postlabelcache | |
int | status | MS_ON, MS_OFF, MS_EMBED |
int | style | |
int | units | |
int | width |
new shapeFileObj(string filename, int type)
or using the old constructor
shapefileObj ms_newShapefileObj(string filename, int type)
Opens a shapefile and returns a new object to deal with it. Filename should be passed with no extension. To create a new file (or overwrite an existing one), type should be one of MS_SHP_POINT, MS_SHP_ARC, MS_SHP_POLYGON or MS_SHP_MULTIPOINT. Pass type as -1 to open an existing file for read-only access, and type=-2 to open an existing file for update (append).
Type | Name | Note |
---|---|---|
rectObj | bounds | read-only |
int | numshapes | read-only |
string | source | read-only |
int | type | read-only |
Free the object properties and break the internal references. Note that you have to unset the php variable to free totally the resources.
Note
The shape file is closed (and changes committed) when the object is destroyed. You can explicitly close and save the changes by calling $shapefile->free(); unset($shapefile), which will also free the php object.
new shapeObj(int type)
or using the old constructor
ShapeObj ms_newShapeObj(int type)
‘type’ is one of MS_SHAPE_POINT, MS_SHAPE_LINE, MS_SHAPE_POLYGON or MS_SHAPE_NULL
ShapeObj ms_shapeObjFromWkt(string wkt)
Creates new shape object from WKT string.
Type | Name | Note |
---|---|---|
rectObj | bounds | read-only |
int | classindex | |
int | index | |
int | numlines | read-only |
int | numvalues | read-only |
int | tileindex | read-only |
string | text | |
int | type | read-only |
array | values | read-only |
The values array is an associative array with the attribute values for this shape. It is set only on shapes obtained from layer->getShape(). The key to the values in the array is the attribute name, e.g.
$population = $shape->values["Population"];
Instances of styleObj are always embedded inside a classObj or labelObj.
new styleObj(classObj class [, styleObj style])
// or
new styleObj(labelObj label [, styleObj style])
or using the old constructor (do not support a labelObj at first argument)
styleObj ms_newStyleObj(classObj class [, styleObj style])
The second argument ‘style’ is optional. If given, the new style created will be a copy of the style passed as argument.
Type | Name | Note |
---|---|---|
double | angle | |
int | antialias | |
colorObj | backgroundcolor | |
colorObj | color | |
double | maxsize | |
double | maxvalue | |
double | maxwidth | |
double | minsize | |
double | minvalue | |
double | minwidth | |
int | offsetx | |
int | offsety | |
int | opacity | only supported for the AGG driver |
colorObj | outlinecolor | |
string | rangeitem | |
double | size | |
int | symbol | |
string | symbolname | |
double | width |
Get the attribute binding for a specfiled style property. Returns NULL if there is no binding for this property.
$oStyle->setbinding(MS_STYLE_BINDING_COLOR, "FIELD_NAME_COLOR");
echo $oStyle->getbinding(MS_STYLE_BINDING_COLOR); // FIELD_NAME_COLOR
string getGeomTransform()
Remove the attribute binding for a specfiled style property. Added in MapServer 5.0.
$oStyle->removebinding(MS_STYLE_BINDING_COLOR);
Set the attribute binding for a specfiled style property. Added in MapServer 5.0.
$oStyle->setbinding(MS_STYLE_BINDING_COLOR, "FIELD_NAME_COLOR");
This would bind the color parameter with the data (ie will extract the value of the color from the field called “FIELD_NAME_COLOR”
int setGeomTransform(string value)
new symbolObj(mapObj map, string symbolname)
or using the old constructor
int ms_newSymbolObj(mapObj map, string symbolname)
Creates a new symbol with default values in the symbolist.
Note
Using the new constructor, the symbol is automatically returned. The old constructor returns the id of the new symbol.
If a symbol with the same name exists, it (or its id) will be returned. To get a symbol object using the old constructor, you need to use a method on the map object:
$nId = ms_newSymbolObj($map, "symbol-test");
$oSymbol = $map->getSymbolObjectById($nId);
Type | Name | Note |
---|---|---|
int | antialias | |
string | character | |
int | filled | |
string | font | |
string | imagepath | read-only |
int | inmapfile | If set to TRUE, the symbol will be saved inside the mapfile. |
int | patternlength | read-only |
int | position | |
string | name | |
int | numpoints | read-only |
double | sizex | |
double | sizey | |
int | transparent | |
int | transparentcolor |
Set the points of the symbol. Note that the values passed is an array containing the x and y values of the points. Returns MS_SUCCESS/MS_FAILURE. Example:
$array[0] = 1 # x value of the first point
$array[1] = 0 # y values of the first point
$array[2] = 1 # x value of the 2nd point
....
$nId = ms_newsymbolobj($gpoMap, "mydash"); $oSymbol = $gpoMap->getsymbolobjectbyid($nId); $oSymbol->set("filled", MS_TRUE); $oSymbol->set("sizex", 1); $oSymbol->set("sizey", 1); $oSymbol->set("inmapfile", MS_TRUE); $aPoints[0] = 1; $aPoints[1] = 1; $oSymbol->setpoints($aPoints); $aPattern[0] = 10; $aPattern[1] = 5; $aPattern[2] = 5; $aPattern[3] = 10; $oSymbol->setpattern($aPattern); $style->set("symbolname", "mydash");
$nId = ms_newSymbolObj($gpoMap, "ttfSymbol"); $oSymbol = $gpoMap->getSymbolObjectById($nId); $oSymbol->set("type", MS_SYMBOL_TRUETYPE); $oSymbol->set("filled", true); $oSymbol->set("character", "D"); $oSymbol->set("font", "ttfFontName");
Type | Name | Note |
---|---|---|
string | browseformat | |
string | empty | read-only |
string | error | read-only |
rectObj | extent | read-only |
string | footer | |
string | header | |
string | imagepath | |
string | imageurl | |
string | legendformat | |
string | log | |
double | maxscaledenom | |
string | maxtemplate | |
hashTableObj | metadata | |
double | minscaledenom | |
string | mintemplate | |
string | queryformat | |
string | template | |
string | temppath |
Normally, you should not have to worry about the memory management because php has a garbage collector and will free resources for you. If you write only small scripts that don’t do a lot of processing, it’s not worth to care about that. Everything will be freed at the end of the script.
However, it may be useful to free resources during the execution if the script executes many tasks. To do so, you’ll have to call the free() method of the mapscript objects and unset the php variables. The purpose of the free methods is to break the circular references between an object and its properties to allow the zend engine to free the resources.
Here’s an example of a script that doesn’t free things during the execution:
$map = new mapObj("mapfile.map");
$of = $map->outputformat;
echo $map->extent->minx." - ".$map->extent->miny." - ".$map->extent->maxx.
" - ".$map->extent->maxy."\n";
echo "Outputformat name: $of->name\n";
unset($of);
unset($map); // Even if we unset the php variables, resources wont be freed
// Resources will be only freed at the end of the script
and the same script that frees resources as soon as it can
$map = new mapObj("mapfile.map");
$of = $map->outputformat;
echo $map->extent->minx." - ".$map->extent->miny." - ".$map->extent->maxx." - ".$map->extent->maxy."\n";
echo "Outputformat name: $of->name\n";
unset($of);
$map->free(); // break the circular references
// at this place, the outputformat ($of) and the rect object ($map->extent) resources are freed
unset($map);
// the map object is immediately freed after the unset (before the end of the script)