Geo::Google::MapObject(3pm) | User Contributed Perl Documentation | Geo::Google::MapObject(3pm) |
Geo::Google::MapObject - Code to help with managing the server side of the Google Maps API
Version 0.06
use HTML::Template::Pluggable; use HTML::Template::Plugin::Dot; use Geo::Google::MapObject; my $map = Geo::Google::MapObject->new( key => 'ABQFbHAATHwok56Qe3MBtg0s7lgkHBS9HKneet7v0OIFhIwnBhTEGCHLTRRRBa_lUOCy1fDamS5PQt8qULYfYQ', zoom => 13, size => '512x400', maptype => 'terrain', markers=> [ { location=>'51.242844,0.011716', color=>'green', label=>'P', title=>'Periapt Technologies', href=>'http://www.periapt.co.uk' }, { location=>'51.243757,0.006051', color=>'red', label=>'C', title=>'Crown Roast Butchers', href=>'http://www.crownroast.co.uk/' }, ] ); my $template = HTML::Template::Pluggable->new(file=>'map.tmpl'); $template->param(map=>$map); return $template->output;
This module is intended to provide a server side solution to working with the Google Maps API. In particular an object of this class encapsulates a "map" object that provides support for the static maps API, the javascript maps API, AJAX calls and non-javascript fallback data; but without making many assumptions about the surrounding framework. We do assume that a template framework with support for a "dot" notation is being used, for example HTML::Template::Pluggable. An important commitment of the module is support for graceful and consistent fallback to a functional non-javascript web page.
The javascript and static Google map APIs do not behave in quite the same way when zoom and center are not specified. Specifically it works quite well with the static maps (<http://code.google.com/apis/maps/documentation/staticmaps/#ImplicitPositioning>) but not so well with the javascript API. To compensate for this the module gives a choice between: specifying the center and zoom levels; allowing the APIs and client side code to do whatever they think best; using a built in algorithm to calculate a sensible zoom and center; and finally supplying ones own algorithm to calculate a sensible zoom and center.
Supported arguments are
var mapping = new Array(G_NORMAL_MAP, G_SATELLITE_MAP, G_PHYSICAL_MAP, G_HYBRID_MAP); var maptype = mapping[data.maptype];
This function tales a reference to an array of marker specifications and a maximum zoom level and returns a pair consisting of a suggested zoom level and a center.
The algorithm works by iteratively building the following objects:
($ctheta, $cphi) = mid point of ($ctheta, $cphi) and the new point $radius = $radius + 0.5 * distance between ($ctheta, $cphi) and the new point
I doubt that this algorithm is optimal but it seems quick, uses only one pass through the markers and can be seen in action at <http://testmaps.periapt.co.uk>. Also if you have a better one you can specify it by passing a suitable CODE ref or blessed scalar to the "autozoom" parameter of the constructor.
Returns a URL suitable for use with the static maps API based upon the arguments passed to the constructor.
Returns a URL suitable for use in loading the dynamic map API.
This returns the marker array ref.
This function uses the JSON module to return a JSON representation of the object. It removes the API key as that should not be required by any javascript client side code. If any marker object has a title attribute, then that attribute is encoded so it will display correctly during mouse overs.
This returns the width of the image or undef if none has been set.
This returns the height of the image or undef if none has been set.
This module only covers the server side of a two way conversation between server and a talkative client. As such the tutorial must also consider HTML and javascript. Also to understand this tutorial we assume at least passing familiarity with the following:
We probably have a template file, map.tmpl, some thing like the following:
<html> <head> <title>Test Map Tutorial</title> <!-- This way we tell the javascript what URL to contact the server with. --> <link href="/map_json" id="get_init_data"/> <!-- This will be filled in with the correct URL to load the Google maps javascript API. --> <script type="text/javascript" src="<TMPL_VAR NAME="maps.javascript_url()">"></script> <!-- This will load the yui API. If you use a different javascript API this would obviously change. --> <script type="text/javascript" src="http://yui.yahooapis.com/2.8.0r4/build/yahoo-dom-event/yahoo-dom-event.js"></script> <script type="text/javascript" src="http://yui.yahooapis.com/2.8.0r4/build/connection/connection.js"></script> <script type="text/javascript" src="http://yui.yahooapis.com/2.8.0r4/build/json/json-min.js"></script> <!-- This loads our javascript code. --> <script type="text/javascript" src="/js/maps.js"></script> </head> <body> <!-- This div will be completely replaced by the Google API and is identified by #map_canvas. --> <div id="map_canvas"> <!-- This image will be loaded by the static Google map API. It will be available whilst the javascript based map is loading and if javascript is turned off --> <div><img alt="Test map" src="<TMPL_VAR NAME="maps.static_map_url()">" width="<TMPL_VAR NAME="maps.width()">" height="<TMPL_VAR NAME="maps.height()">" /> </div> <!-- The following will be used if javascript is disabled. We can use it display information that would normally be obtained by hovering over or clicking on markers on the dynamic map display. --> <noscript> <table> <TMPL_LOOP NAME="maps.markers()"> <tr> <td class="google_<TMPL_VAR NAME="this.color">"><TMPL_VAR NAME="this.label"></td> <td> <TMPL_IF NAME="this.href"> <a href="<TMPL_VAR NAME="this.href">"> </TMPL_IF> <TMPL_VAR NAME="this.title"> <TMPL_IF NAME="this.href"> </a> </TMPL_IF> </td> </tr> </TMPL_LOOP> </table> </noscript> </div> <!-- end of #map_canvas --> </body> </html>
The code to actually produce the web page must look something like this:
use HTML::Template::Pluggable; use HTML::Template::Plugin::Dot; use Geo::Google::MapObject; my $t = HTML::Template::Pluggable->new(filename => 'map.tmpl'); my $map = Geo::Google::MapObject->new(....); $t->param(maps=>$map); print $t->output;
This is all that would be needed in a javascript free environment. With javascript enabled the client is going to ask for the same data in a JSON format (at least we are only supporting JSON). The code to service that request will look something like:
use Geo::Google::MapObject; my $map = Geo::Google::MapObject->new(....); print $map->json;
As indicated in the markup above we are expecting the javascript to be in a file called maps.js. We expect it to look something like the following:
function mapInitialize() { /* Read the "link" element that tells us how to contact the server. See markup above. */ var get_init_data = YAHOO.util.Dom.get('get_init_data').href; /* Build the AJAX callback object consisting of three parts. */ var callback = { /* Part I: Function called in the event of a successful call. */ success: function(o) { /* Convert the JSON response into a javascript object. This structure corresponds to the Geo::Google::MapObject in perl as intermediated by its "json" method. */ var data = YAHOO.lang.JSON.parse(o.responseText); if (GBrowserIsCompatible()) { /* Build up the Map object which will replace #map_canvas in the above markup. */ var mapopt = {}; if (data.size) { mapopt.size = new GSize(parseInt(data.size.width), parseInt(data.size.height)); } var markers = data.markers; var map = new GMap2(YAHOO.util.Dom.get("map_canvas"), mapopt); var maptype = null; if (data.maptype) { maptype = o.argument[parseInt(data.maptype)]; } var zoom = null; if (data.zoom) { zoom = parseInt(data.zoom); } var center = markers[0].location; if (data.center) { center = data.center; } map.setCenter(GLatLng.fromUrlValue(center), zoom, maptype); map.setUIToDefault(); /* Now for each marker build and add a GMarker object */ for(var i = 0; i < markers.length; i++) { var opt = {title: markers[i].title}; if (!markers[i].href) { opt.clickable = false; } if (markers[i].icon) { opt.icon = new GIcon(G_DEFAULT_ICON, markers[i].icon); if (markers[i].shadow) { opt.icon.shadow = markers[i].shadow; } } var mark = new GMarker(GLatLng.fromUrlValue(markers[i].location), opt); if (markers[i].href) { mark.href = markers[i].href; GEvent.addListener(mark, "click", function(){window.location=this.href;}); } map.addOverlay(mark); } } }, /* End of Part I */ /* Part II: Function called in the event of failure */ failure: function(o) {alert(o.statusText);}, /* Part III: Data that is passed to the success function. We are using this to map from numerical maptypes that Geo::Google::MapObject has passed us to the forms used in Google maps API. */ argument: [G_NORMAL_MAP, G_SATELLITE_MAP, G_PHYSICAL_MAP, G_HYBRID_MAP] }; /* End of constructing the AJAX callback object. */ /* This calls the server which should hopefully kick off callback.success with lots of lovely data. */ var transaction = YAHOO.util.Connect.asyncRequest('GET', get_init_data, callback, null); } /* end of mapInitialize function */ /* This will make sure that we call the above function at a good time. */ YAHOO.util.Event.onDOMReady(mapInitialize); /* We still have to do the memory cleanup ourselves. */ YAHOO.util.Event.addListener(window, 'unload', 'GUnload');
There are lots of variations that can be done with this. The Geo::Google::MapObject object will pass on all fields it does not recognize via the "json" function and these can be used by the javascript in whatever way required. Similarly fields added to the marker specification will be passed by the "markers" function and can be used in the template in whatever way required.
You can also make the markers draggable and have the act of dragging a marker update data on the server. There is an example of where this has been done at <http://testmaps.periapt.co.uk>. The details of how this is done depend intrinsically on the implementation of the data storage on the server. I would suggest that in general the steps required to make the markers draggable might be as follows:
<link href="/move_marker" id="move_marker"/>
An advantage of using these link elements is that you might have multiple maps to manage. By using the link elements to communicate with the client side, a lot more code and templates can be reused.
var move_marker = YAHOO.util.Dom.get('move_marker').href;
var opt = {title: markers[i].title, draggable: true};
mark.label = markers[i].label;
GEvent.addListener(mark, "dragend", function(latlng) { var location = latlng.toUrlValue(12); var postdata = "id="+this.label+"&location="+location; YAHOO.util.Connect.asyncRequest('POST', move_marker, { success: function(o){}, failure: function(o) {alert(o.statusText);}, argument: [] }, postdata); });
Geo::Google::MapObject requires no configuration files or environment variables.
None reported.
Please report any bugs or feature requests to "bug-geo-google-mapobject@rt.cpan.org", or through the web interface at <http://rt.cpan.org>.
Thanks to Andreas Koenig for pointing out that this module had an issue with "Build.PL".
Nicholas Bamber "<nicholas@periapt.co.uk>"
Copyright (c) 2009, Nicholas Bamber "<nicholas@periapt.co.uk>". All rights reserved.
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "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 SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.
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 SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (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 SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
2018-03-30 | perl v5.26.1 |