Thursday, 2 May 2013

MapGuide tidbits: MgByteReader and friends

This one's a bit of a post for newbies, so you can skip it if you already know this stuff :)

If you look at the various bits of the MapGuide API, you'll probably see lots of references to MgByteReader lying around. An API will either return one or require one as part of its method parameters.

What is a MgByteReader? A MgByteReader is basically a MapGuide analogue to your Stream class in .net/Java and serves the same purpose: an unified I/O abstraction for things that can be fed into the MapGuide API and things that are returned from the MapGuide API. Things like.

  • Images (of rendered maps/selections)
  • Resource Data files (to download/upload)
  • XML files (to/from the repository)
  • DWF files (for DWF ePlots)
So if you're given an MgByteReader from a particular API, what can I do with it? Similarly, if an API requires passing in a MgByteReader, how can I make one?

Here's a diagram I made up that should explain everything to you.




Since MgByteReader is basically a stream, you might be wondering if the .net/Java/PHP wrappers to the MapGuide API provides any adapters to allow MgByteReader objects to be consumed as Stream objects, so you don't have to do any manual conversion. For PHP and Java, you're out of luck. You'll have to dump the MgByteReader into a supported form as per the above diagram, and then work from there.

For .net however, I've already solved this problem for you :) If you're using the Maestro API (that wraps both the official MapGuide API and the mapagent interface), for APIs that return MgByteReader objects Maestro provides wrapper APIs that return System.IO.Stream objects instead. Similarly for APIs that take MgByteReader parameters, Maestro's wrapper API takes System.IO.Stream objects.

If you're not using Maestro, there's a MgReadOnlyStream class I wrote for mg-desktop that can easily be reused for your own .net applications if you require a System.IO.Stream adapter. MgReadOnlyStream provides mg-desktop an easy way to convert the output of a rendering service API into something that requires a System.IO.Stream (eg. a System.Drawing.Image). That's pretty much the gist of how our mg-desktop viewer works, taking MgByteReader objects from the rendering service, wrapping it into a MgReadOnlyStream and feeding that to a System.Drawing.Image, to then be painted onto a WinForms control surface.

Hope this helps.

Sunday, 28 April 2013

MapGuide tidbits: OpenLayers in relation to Fusion

I'd had been holding off on this particular post for quite some time because what is written below wasn't exactly true or applicable until MapGuide RFC 132 was implemented. Now that the RFC is completed, the time to publish this post is more suitable.

As some of you know, Fusion is built on top of the powerful OpenLayers library.

But what you may not know (and probably want to know) are the specifics.

What version of OpenLayers?

Believe it or not, I myself do not know what version of OpenLayers is currently bundled with the Fusion that comes with MapGuide Open Source 2.5 (or older releases). Our bundled copy in Fusion has the release version number scrubbed out by SVN making it hard to determine the actual version number.

I strongly believe it is OpenLayers 2.10 due to the lack of touch event support.

For the next release of MapGuide Open Source (2.6) the answer will be crystal clear: Fusion will be using OpenLayers 2.12. What OpenLayers 2.12 brings to the table for Fusion will be the topic of another post.

What OpenLayers build profile?

As some of you may know, OpenLayers is not a monolithic library. It can be customized with various build profiles to include/exclude certain parts of the OpenLayers library. What that means in practice is that some parts of the OpenLayers API may not be available to be used in Fusion because we use our own custom build profile for OpenLayers. Our custom build profile is defined in fusion.cfg, there you can see what parts of the OpenLayers API we've included and what parts we've excluded.

Now sadly, the way OpenLayers is set up within the fusion source tree (before RFC 132) is that we are keeping in a "built" version of OpenLayers.js and have customizations done on that one file. This makes customizing your own OpenLayers build for use with Fusion much more harder as our current audit trail of Fusion-specific customizations is very hard to track. This means that customizing your own OpenLayers for Fusion may not be as simple as:
  1. Download the OpenLayers zip/tarball
  2. Build it with your desired build profile
  3. Overwrite Fusion's OpenLayers.js with your built copy.
For the Fusion that will come MapGuide Open Source 2.6, this will be much more clearer. We'll be reserving a section of the Fusion repo, for Fusion-specific customizations to individual js files in OpenLayers such that customizing your own OpenLayers becomes:
  1. Download the OpenLayers 2.12 zip/tarball
  2. Overlay the directory (where you unzip/untared) with our Fusion-specific modified files
  3. Build OpenLayers with your desired build profile
  4. Overwrite Fusion's OpenLayers.js with your built copy
  5. Re-build and re-minify Fusion with your custom OpenLayers.
This way, the OpenLayers build you customize will retain our Fusion-specific changes where necessary, and allows you to tap into parts of OpenLayers that we may have excluded from our custom build.

Thursday, 25 April 2013

MapGuide tidbits: Is your FDO provider smart enough when handling SQL?

So if you saw my previous MapGuide/pgRouting example, I mentioned that the whole example was only possible because any SQL queries (that involves geometry columns or expressions) that we send off to PostgreSQL through the MapGuide API, the FDO provider correctly translates such column values back into FDO geometry values and not as un-readable BLOBs.

Although we can't directly create a layer off of such a query, we can still feed the query result into a temporary SDF/SHP/SQLite feature source and create a layer off of that instead, which is how we got to display the shortest path results in MapGuide from a pgRouting SQL query.

So how do you know if your FDO provider:

 a) Supports SQL?
 b) Is smart enough to translate any geometry values in a SQL query result into FDO geometries and not un-usable BLOBs?

Simply connect to this database through the FDO provider with FDO Toolbox and launch a Data Query.

Do you see a SQL query mode in the Data Query tab? Then the provider supports SQL commands

When you run a SQL query in the Data Query tab, do you see WKT in the geometry column in the results pane?


If so, the provider is probably correctly translating these values back into FDO geometries.

But just to be sure, can you see the result visually?


If so, then there is no doubt that your provider is smart enough, and when the FDO provider can handle such cases, you can pretty much tap into whatever spatial functionality your underlying database has to offer through SQL if the standard MapGuide/FDO APIs do not fit the bill, as was the case in our MapGuide/pgRouting example.

Announcing: FDO Toolbox 1.2

As suggested in my previous release, every time a new version of FDO is released, we should have a complementary version of FDO Toolbox using it.

Since FDO 3.8 is now final (and used by MapGuide Open Source 2.5), here's a new complementary version of FDO Toolbox using it.

A summary of changes include:

  • FDO Toolbox now uses FDO 3.8 final
  • FDO Toolbox includes a custom build of the PostgreSQL FDO provider (r6796), allowing FDO Toolbox to create PostGIS 2.0 data stores (as the FDO 3.8 final provider cannot do this).
  • Fix a potential infinite loop in the spatial context creation/updating logic during Bulk Copy.
  • Fix "Create class if not exist" checkbox not being enabled under certain conditions in the "New Copy Task" dialog.

Thursday, 18 April 2013

MapGuide and pgRouting: A shortest path example

Ok folks, here's how you do this

For a little back-story, since reading Jo Cook's pgRouting example with MapServer, I wanted to do an equivalent one for MapGuide just to see for myself (and many others) if the MapGuide and pgRouting combination was indeed possible.

This blog post will show you a basic PHP proof of concept example of pgRouting integration with MapGuide using the following stack:
  • MapGuide Open Source 2.5
  • PostgreSQL 9.2
  • PostGIS 2.0.3
  • pgRouting 1.0.7
For different versions of PostGIS and/or pgRouting, you may have to adjust some of the code shown here.

This example has only been tested on Windows, but assuming you satsify the above pre-requisites I couldn't see why this example won't work for Linux as well.

You can find the code and sample package here for reference. This example works with both the AJAX and Fusion viewers

Getting the source data

This example uses the GeoBase "National Road Network" dataset for British Columbia (nrn_rrn_bc_shp_en.zip). This is the same reference dataset used in the pgRouting tutorial.

Creating the PostGIS database

Using pgAdmin or the command-line tools, create a new database "pgrouting_example" using "template_postgis_20". 

In case you're wondering, FDO Toolbox does not support creating a PostGIS 2.0 data store because the provider's data store and spatial index creation logic hasn't been updated for PostGIS 2.0. If you're using the PostgreSQL FDO provider that has this changeset compiled in, then you have this support. This change didn't make it for the PostgreSQL provider in FDO 3.8, so as it stands MapGuide Open Source 2.5 can connect to PostGIS 2.0 databases but not create them, which is still okay for this example as we're using external tools to set it up.

Enabling pgRouting

The pgrouting_example database is PostGIS-enabled, but not pgRouting-enabled. Execute this SQL on that database to enable pgRouting support:

CREATE EXTENSION pgrouting

Loading our Roads Shape File

We use the shp2pgsql utility to load our roads shape file into PostGIS

Why don't we eat our own dogfood and use FDO Toolbox to do this? Again, some shortcomings:
  • FDO Toolbox bulk copies geometries as-is, multi-linestrings don't get converted to linestrings. This is important for pgRouting in terms of building a routable network as you'll see in the next step
  • FDO Toolbox lacks PostGIS 2.0 support in its bundled FDO provider (as mentioned above).
So for now, we'll have to do with shp2pgsql

For our example dataset, the shape file in question is NRN_BC_9_0_ROADSEG.shp. The necessary command to load this into our PostGIS database (using the postgres db account) is:

shp2pgsql -s 4617 -I -S NRN_BC_9_0_ROADSEG.shp roads | psql -d pgrouting_example -U postgres

4617 is the SRID to load these geometries in. The "-S" switch instructs the tool to generate simple geometries instead of MULTI geometries, ensuring our lines are put into PostGIS as LINESTRING geometries and not MULTILINESTRING geometries. You'll see why this is important in the next step.

Making this data routable

We now need to extend our imported roads table to support pgRouting, we need to add the following columns:
  • source (integer, the source node id)
  • target (integer, the target node id)
  • length (double precision, the geometric length of the road line segment)
The following SQL creates these columns

alter table roads add column source integer;
alter table roads add column target integer;
alter table roads add column length double precision;

Then we use the pgr_assign_vertex_id function in pgRouting to populate the columns we just added. This function only works on linestrings and not multi-linestrings. This is why we use shp2pgsql, which can do this necessary conversion. This function was called assign_vertex_id in older versions of pgRouting. We call it like so:

select pgr_assign_vertex_id('roads', 0.00000001, 'geom', 'gid');

The 0.00000001 value is the "snap tolerance", since this dataset is in latitudes and longitudes (thus degree-based units) we need a really fine-grained value. This value varies from dataset to dataset.

This command will take a few minutes. Then we need to set the length column:

update roads set length = st_length(geom);

And finally, apply the necessary indexes for good performance (no need for a spatial index, as shp2pgsql already created one):

create index source_idx on roads(source);
create index target_idx on roads(target);

Consuming PostGIS from MapGuide

As mentioned, as of MapGuide Open Source 2.5, the bundled PostgreSQL FDO provider supports connecting to PostGIS 2.0 databases. It just can't create them, which is okay because the MapGuide API does not support Feature Source creation for RDBMS providers anyways. So setting up the Feature Source and layers is fairly straight-forward. 

But to save time and words on this post, just load in the referenced sample package, and tweak the credentials of Library://pg_routing/Data/postgis.FeatureSource to match your PostgreSQL credentials as required.

The sample package has two maps, a normal map (for consumption with the AJAX viewer) and a "Web Mercator" projected version (for consumption with Fusion with an OpenStreetMap backdrop).

Installing the sample application

Assuming the standard installation directory of C:\Program Files\OSGeo\MapGuide, extract the sample application to the C:\Program Files\OSGeo\MapGuide\Web\www directory.

The extracted directory should look like this

Running the sample application

The sample application works with both the AJAX viewer and Fusion viewer. Load them like so:

AJAX Viewer: 

http://localhost/mapguide/mapviewerajax/?WEBLAYOUT=Library://pg_routing/Layouts/pgrouting_basic.WebLayout&LOCALE=en

Fusion: 

http://localhost/mapguide/fusion/templates/mapguide/slate/index.html?ApplicationDefinition=Library://pg_routing/Layouts/pgrouting_fusion.ApplicationDefinition&locale=en

Plug in the port numbers as necessary into the URL for Apache configurations

The Demo

Regardless of the viewer, the Task Pane will be loaded with the main page of the sample application.


Now this is a proof of concept, so the UI is very simplistic and barebones and requires you to enter the source and target node ids to compute the shortest path. Ideally, you would record the start/end points with the digitizing viewer API, tap into PostGIS trickery server-side to "snap" to the nearest road segments, extract the relevant source and target IDs and calculate shortest path from there.

In our case, this has to be done manually, so select the road segment closest to your start point and observe its "source" property value.


Repeat for the selected road segment closest to your end point. But this time, observe its "target" property value.


Once you've noted both ids, plug them into the form, click the "Calculate" button and pgRouting will do its magic!


So what does the "Calculate" button do exactly? It does this:

1. Creates a temporary MapGuide Feature Source (SDF) to store the shortest path result

2. Creates a MgLayer pointing to the shortest path result Feature Source

3. Use MgFeatureService.ExecuteSqlQuery() to execute the following SQL:

select gid, geom from roads 
            join (select * from shortest_path('select gid as id, source::integer, target::integer, length::double precision as cost from roads', source_id, target_id, false, false)) as route 
            on roads.gid = route.edge_id

The key thing to take from this, is that any PostGIS geometry columns in that SQL query will be correctly interpreted as FDO geometry values in the MgSqlDataReader we get back. If what I just said didn't ignite any light bulbs, well then it should!

Because this means for cases where our standard MapGuide Data Access APIs doesn't support or cover, we can always use MgFeatureService.ExecuteSqlQuery() as an "escape hatch" API to tap into the full set of geospatial/routing functionality offered by pgRouting/PostGIS and if any such SQL queries involve geometry columns, we can trust the PostgreSQL FDO provider to properly translate such values back as FDO geometry values in the returning SQL reader (and not as unrecognizable BLOBs), allowing us to do geometry operations on such results with the MapGuide API.

Does this technique only work for the PostgresSQL provider? No, the King.Oracle provider is also known to properly translate FDO geometry values from raw SQL query results via FDO. MySQL, SQL Server and SQLite are currently unknown. Please do comment if you know if this technique also works on these providers.

Now we can't create a Layer Definition off of a SQL query result (wouldn't that be a nice feature to have?), so we do the next best thing, which is to:

4. Copy the SQL reader contents into our temporary SDF feature source (that's why we created it). On subsequent calculations, the temporary SDF feature source is cleared first before copying in the new results from the SQL reader.

5. Save the MgMap and output a client-side JS call to refresh the map.

So that's the jist of this example. You can read the PHP code in the sample for all the gory details.

Caveats (or: pgRouting-isms)

EDIT: Thanks to dkastl for pointing out the very high tolerance value I had previously in my pgr_assign_vertex_id() example. A proper tolerance value will ensure proper display of routing results. Consider what was previously written below as a case of what happens if you specify a tolerance value that's too high.

If I haven't made it clear, this is a proof of concept example. There's some data/pgRouting related things that baffle me. For example, zoom in closer to that shortest path. Why is it broken off in some parts?


This shortest path result is straight from the pgRouting shortest_path() function.

Is the source data bad? Did I set up the network routing information incorrectly? Is my pgRouting SQL query bad? Did I base this example off of semi-inaccurate/outdated tutorial documentation? Is it a bug in pgRouting itself?

These are questions a more seasoned expert on pgRouting could probably explain. But if you do know why such results would be the case, I'd like to know through the comments on this post.

But besides that, the root question of whether MapGuide be integrated with pgRouting has been answered.

With an emphatic YES!

Wednesday, 17 April 2013

Yes it's possible!




I'll be showing you how shortly. Stay tuned.

Thursday, 11 April 2013

MapGuide tidibts: Stylization error logging

Ever look at an image of a map, and you know something is not right? You look at the error logs and you don't see anything amiss?

Try setting this value in serverconfig.ini:

LogsDetail = MappingService:2

What does this setting do? It sets the logging detail for Mapping Service related operations to Trace, Warnings and Errors

When an error occurs during individual feature stylization, caught exceptions are logged as warnings, which sort of makes sense as MapGuide would be pretty flimsy if the rendering bailed out on the first bad feature it encounters during stylization.

What this means however is that if errors do occur on individual feature stylization you won't see anything in the logs because the default logging level is Errors only.

What could trigger such errors that won't be logged by default? Things involving FDO expressions in any styling or symbolization property in your Layer Definition.

  • Malformed FDO expression syntax
  • Calls to non-existent FDO expression functions
  • References to non-existent feature properties
Applying the above setting will reveal such errors.

Be warned though, logging can be extremely noisy as stylization errors for each feature are logged. So use this setting with care (obviously turn it on for debugging purposes, and turn it off when done).