Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Fix line endings - PLEASE MERGE ASAP and read notes below

This changeset is far reaching and sets all files to have git friendly line endings. However, this also means
patches pre this commit will be hard to merge against the tree post this commit.

If you have trouble merging this commit then instead do the following to achieve the same effect:
- clone the repo as normal
- change autocrlf=true (or =input if you prefer) in your gitconfig file (~/.gitconfig on unix)
- blow away your repo, (eg rm -rf * ) it goes without saying to be careful and obviously don't delete the .git
dir
- get back to HEAD with: "git reset HEAD --hard"
- now "git status" should show you loads of changes, also "git diff -b" should show you that they are just line
ending changes
- add files and commit as normal. All files should now be in a git friendly line ending format
  • Loading branch information...
commit 5789d8b17280475075b0fba8b6412c90b8c7a38a 1 parent 6d2e91b
@ewildgoose ewildgoose authored
View
26 gmaps_api_key.yml.sample
@@ -1,14 +1,14 @@
-#Fill here the Google Maps API keys for your application
-#In this sample:
-#For development and test, we have only one possible host (localhost:3000), so there is only a single key associated with the mode.
-#In production, the app can be accessed through 2 different hosts: thepochisuperstarmegashow.com and exmaple.com. There then needs a 2-key hash. If you deployed to one host, only the API key would be needed (as in development and test).
-
-development:
- ABQIAAAAzMUFFnT9uH0xq39J0Y4kbhTJQa0g3IQ9GZqIMmInSLzwtGDKaBR6j135zrztfTGVOm2QlWnkaidDIQ
-
-test:
- ABQIAAAAzMUFFnT9uH0xq39J0Y4kbhTJQa0g3IQ9GZqIMmInSLzwtGDKaBR6j135zrztfTGVOm2QlWnkaidDIQ
-
-production:
- thepochisuperstarmegashow.com: ABQIAAAAzMUFFnT9uH0Sfg76Y4kbhTJQa0g3IQ9GZqIMmInSLzwtGDmlRT6e90j135zat56yhJKQlWnkaidDIQ
+#Fill here the Google Maps API keys for your application
+#In this sample:
+#For development and test, we have only one possible host (localhost:3000), so there is only a single key associated with the mode.
+#In production, the app can be accessed through 2 different hosts: thepochisuperstarmegashow.com and exmaple.com. There then needs a 2-key hash. If you deployed to one host, only the API key would be needed (as in development and test).
+
+development:
+ ABQIAAAAzMUFFnT9uH0xq39J0Y4kbhTJQa0g3IQ9GZqIMmInSLzwtGDKaBR6j135zrztfTGVOm2QlWnkaidDIQ
+
+test:
+ ABQIAAAAzMUFFnT9uH0xq39J0Y4kbhTJQa0g3IQ9GZqIMmInSLzwtGDKaBR6j135zrztfTGVOm2QlWnkaidDIQ
+
+production:
+ thepochisuperstarmegashow.com: ABQIAAAAzMUFFnT9uH0Sfg76Y4kbhTJQa0g3IQ9GZqIMmInSLzwtGDmlRT6e90j135zat56yhJKQlWnkaidDIQ
example.com: ABQIAAAAzMUFFnT9uH0Sfg98Y4kbhGFJQa0g3IQ9GZqIMmInSLrthJKGDmlRT98f4j135zat56yjRKQlWnkmod3TB
View
6 init.rb
@@ -1,3 +1,3 @@
-require 'ym4r_gm'
-
-
+require 'ym4r_gm'
+
+
View
228 javascript/markerGroup.js
@@ -1,114 +1,114 @@
-function GMarkerGroup(active, markers, markersById) {
- this.active = active;
- this.markers = markers || new Array();
- this.markersById = markersById || new Object();
-}
-
-GMarkerGroup.prototype = new GOverlay();
-
-GMarkerGroup.prototype.initialize = function(map) {
- this.map = map;
-
- if(this.active){
- for(var i = 0 , len = this.markers.length; i < len; i++) {
- this.map.addOverlay(this.markers[i]);
- }
- for(var id in this.markersById){
- this.map.addOverlay(this.markersById[id]);
- }
- }
-}
-
-//If not already done (ie if not inactive) remove all the markers from the map
-GMarkerGroup.prototype.remove = function() {
- this.deactivate();
-}
-
-GMarkerGroup.prototype.redraw = function(force){
- //Nothing to do : markers are already taken care of
-}
-
-//Copy the data to a new Marker Group
-GMarkerGroup.prototype.copy = function() {
- var overlay = new GMarkerGroup(this.active);
- overlay.markers = this.markers; //Need to do deep copy
- overlay.markersById = this.markersById; //Need to do deep copy
- return overlay;
-}
-
-//Inactivate the Marker group and clear the internal content
-GMarkerGroup.prototype.clear = function(){
- //deactivate the map first (which removes the markers from the map)
- this.deactivate();
- //Clear the internal content
- this.markers = new Array();
- this.markersById = new Object();
-}
-
-//Add a marker to the GMarkerGroup ; Adds it now to the map if the GMarkerGroup is active
-GMarkerGroup.prototype.addMarker = function(marker,id){
- if(id == undefined){
- this.markers.push(marker);
- }else{
- this.markersById[id] = marker;
- }
- if(this.active && this.map != undefined ){
- this.map.addOverlay(marker);
- }
-}
-
-//Open the info window (or info window tabs) of a marker
-GMarkerGroup.prototype.showMarker = function(id){
- var marker = this.markersById[id];
- if(marker != undefined){
- GEvent.trigger(marker,"click");
- }
-}
-
-//Activate (or deactivate depending on the argument) the GMarkerGroup
-GMarkerGroup.prototype.activate = function(active){
- active = (active == undefined) ? true : active;
- if(!active){
- if(this.active){
- if(this.map != undefined){
- for(var i = 0 , len = this.markers.length; i < len; i++){
- this.map.removeOverlay(this.markers[i])
- }
- for(var id in this.markersById){
- this.map.removeOverlay(this.markersById[id]);
- }
- }
- this.active = false;
- }
- }else{
- if(!this.active){
- if(this.map != undefined){
- for(var i = 0 , len = this.markers.length; i < len; i++){
- this.map.addOverlay(this.markers[i]);
- }
- for(var id in this.markersById){
- this.map.addOverlay(this.markersById[id]);
- }
- }
- this.active = true;
- }
- }
-}
-
-GMarkerGroup.prototype.centerAndZoomOnMarkers = function() {
- if(this.map != undefined){
- //merge markers and markersById
- var tmpMarkers = this.markers.slice();
- for (var id in this.markersById){
- tmpMarkers.push(this.markersById[id]);
- }
- if(tmpMarkers.length > 0){
- this.map.centerAndZoomOnMarkers(tmpMarkers);
- }
- }
-}
-
-//Deactivate the Group Overlay (convenience method)
-GMarkerGroup.prototype.deactivate = function(){
- this.activate(false);
-}
+function GMarkerGroup(active, markers, markersById) {
+ this.active = active;
+ this.markers = markers || new Array();
+ this.markersById = markersById || new Object();
+}
+
+GMarkerGroup.prototype = new GOverlay();
+
+GMarkerGroup.prototype.initialize = function(map) {
+ this.map = map;
+
+ if(this.active){
+ for(var i = 0 , len = this.markers.length; i < len; i++) {
+ this.map.addOverlay(this.markers[i]);
+ }
+ for(var id in this.markersById){
+ this.map.addOverlay(this.markersById[id]);
+ }
+ }
+}
+
+//If not already done (ie if not inactive) remove all the markers from the map
+GMarkerGroup.prototype.remove = function() {
+ this.deactivate();
+}
+
+GMarkerGroup.prototype.redraw = function(force){
+ //Nothing to do : markers are already taken care of
+}
+
+//Copy the data to a new Marker Group
+GMarkerGroup.prototype.copy = function() {
+ var overlay = new GMarkerGroup(this.active);
+ overlay.markers = this.markers; //Need to do deep copy
+ overlay.markersById = this.markersById; //Need to do deep copy
+ return overlay;
+}
+
+//Inactivate the Marker group and clear the internal content
+GMarkerGroup.prototype.clear = function(){
+ //deactivate the map first (which removes the markers from the map)
+ this.deactivate();
+ //Clear the internal content
+ this.markers = new Array();
+ this.markersById = new Object();
+}
+
+//Add a marker to the GMarkerGroup ; Adds it now to the map if the GMarkerGroup is active
+GMarkerGroup.prototype.addMarker = function(marker,id){
+ if(id == undefined){
+ this.markers.push(marker);
+ }else{
+ this.markersById[id] = marker;
+ }
+ if(this.active && this.map != undefined ){
+ this.map.addOverlay(marker);
+ }
+}
+
+//Open the info window (or info window tabs) of a marker
+GMarkerGroup.prototype.showMarker = function(id){
+ var marker = this.markersById[id];
+ if(marker != undefined){
+ GEvent.trigger(marker,"click");
+ }
+}
+
+//Activate (or deactivate depending on the argument) the GMarkerGroup
+GMarkerGroup.prototype.activate = function(active){
+ active = (active == undefined) ? true : active;
+ if(!active){
+ if(this.active){
+ if(this.map != undefined){
+ for(var i = 0 , len = this.markers.length; i < len; i++){
+ this.map.removeOverlay(this.markers[i])
+ }
+ for(var id in this.markersById){
+ this.map.removeOverlay(this.markersById[id]);
+ }
+ }
+ this.active = false;
+ }
+ }else{
+ if(!this.active){
+ if(this.map != undefined){
+ for(var i = 0 , len = this.markers.length; i < len; i++){
+ this.map.addOverlay(this.markers[i]);
+ }
+ for(var id in this.markersById){
+ this.map.addOverlay(this.markersById[id]);
+ }
+ }
+ this.active = true;
+ }
+ }
+}
+
+GMarkerGroup.prototype.centerAndZoomOnMarkers = function() {
+ if(this.map != undefined){
+ //merge markers and markersById
+ var tmpMarkers = this.markers.slice();
+ for (var id in this.markersById){
+ tmpMarkers.push(this.markersById[id]);
+ }
+ if(tmpMarkers.length > 0){
+ this.map.centerAndZoomOnMarkers(tmpMarkers);
+ }
+ }
+}
+
+//Deactivate the Group Overlay (convenience method)
+GMarkerGroup.prototype.deactivate = function(){
+ this.activate(false);
+}
View
234 javascript/ym4r-gm.js
@@ -1,117 +1,117 @@
-// JS helper functions for YM4R
-
-function addInfoWindowToMarker(marker,info,options){
- GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(info,options);});
- return marker;
-}
-
-function addInfoWindowTabsToMarker(marker,info,options){
- GEvent.addListener(marker, "click", function() {marker.openInfoWindowTabsHtml(info,options);});
- return marker;
-}
-
-function addPropertiesToLayer(layer,getTile,copyright,opacity,isPng){
- layer.getTileUrl = getTile;
- layer.getCopyright = copyright;
- layer.getOpacity = opacity;
- layer.isPng = isPng;
- return layer;
-}
-
-function addOptionsToIcon(icon,options){
- for(var k in options){
- icon[k] = options[k];
- }
- return icon;
-}
-
-function addCodeToFunction(func,code){
- if(func == undefined)
- return code;
- else{
- return function(){
- func();
- code();
- }
- }
-}
-
-function addGeocodingToMarker(marker,address){
- marker.orig_initialize = marker.initialize;
- orig_redraw = marker.redraw;
- marker.redraw = function(force){}; //empty the redraw method so no error when called by addOverlay.
- marker.initialize = function(map){
- new GClientGeocoder().getLatLng(address,
- function(latlng){
- if(latlng){
- marker.redraw = orig_redraw;
- marker.orig_initialize(map); //init before setting point
- marker.setPoint(latlng);
- }//do nothing
- });
- };
- return marker;
-}
-
-
-
-GMap2.prototype.centerAndZoomOnMarkers = function(markers) {
- var bounds = new GLatLngBounds(markers[0].getPoint(),
- markers[0].getPoint());
- for (var i=1, len = markers.length ; i<len; i++) {
- bounds.extend(markers[i].getPoint());
- }
-
- this.centerAndZoomOnBounds(bounds);
- }
-
-GMap2.prototype.centerAndZoomOnPoints = function(points) {
- var bounds = new GLatLngBounds(points[0],
- points[0]);
- for (var i=1, len = points.length ; i<len; i++) {
- bounds.extend(points[i]);
- }
-
- this.centerAndZoomOnBounds(bounds);
- }
-
-GMap2.prototype.centerAndZoomOnBounds = function(bounds) {
- var center = bounds.getCenter();
- this.setCenter(center, this.getBoundsZoomLevel(bounds));
-}
-
-//For full screen mode
-function setWindowDims(elem) {
- if (window.innerWidth){
- elem.style.height = (window.innerHeight) + 'px;';
- elem.style.width = (window.innerWidth) + 'px;';
- }else if (document.body.clientWidth){
- elem.style.width = (document.body.clientWidth) + 'px';
- elem.style.height = (document.body.clientHeight) + 'px';
- }
-}
-
-ManagedMarker = function(markers,minZoom,maxZoom) {
- this.markers = markers;
- this.minZoom = minZoom;
- this.maxZoom = maxZoom;
-}
-
-//Add the markers and refresh
-function addMarkersToManager(manager,managedMarkers){
- for(var i = 0, length = managedMarkers.length; i < length;i++) {
- mm = managedMarkers[i];
- manager.addMarkers(mm.markers,mm.minZoom,mm.maxZoom);
- }
- manager.refresh();
- return manager;
-}
-
-
-var INVISIBLE = new GLatLng(0,0); //almost always invisible
-
-if(self.Event && Event.observe){
- Event.observe(window, 'unload', GUnload);
-}else{
- window.onunload = GUnload;
-}
+// JS helper functions for YM4R
+
+function addInfoWindowToMarker(marker,info,options){
+ GEvent.addListener(marker, "click", function() {marker.openInfoWindowHtml(info,options);});
+ return marker;
+}
+
+function addInfoWindowTabsToMarker(marker,info,options){
+ GEvent.addListener(marker, "click", function() {marker.openInfoWindowTabsHtml(info,options);});
+ return marker;
+}
+
+function addPropertiesToLayer(layer,getTile,copyright,opacity,isPng){
+ layer.getTileUrl = getTile;
+ layer.getCopyright = copyright;
+ layer.getOpacity = opacity;
+ layer.isPng = isPng;
+ return layer;
+}
+
+function addOptionsToIcon(icon,options){
+ for(var k in options){
+ icon[k] = options[k];
+ }
+ return icon;
+}
+
+function addCodeToFunction(func,code){
+ if(func == undefined)
+ return code;
+ else{
+ return function(){
+ func();
+ code();
+ }
+ }
+}
+
+function addGeocodingToMarker(marker,address){
+ marker.orig_initialize = marker.initialize;
+ orig_redraw = marker.redraw;
+ marker.redraw = function(force){}; //empty the redraw method so no error when called by addOverlay.
+ marker.initialize = function(map){
+ new GClientGeocoder().getLatLng(address,
+ function(latlng){
+ if(latlng){
+ marker.redraw = orig_redraw;
+ marker.orig_initialize(map); //init before setting point
+ marker.setPoint(latlng);
+ }//do nothing
+ });
+ };
+ return marker;
+}
+
+
+
+GMap2.prototype.centerAndZoomOnMarkers = function(markers) {
+ var bounds = new GLatLngBounds(markers[0].getPoint(),
+ markers[0].getPoint());
+ for (var i=1, len = markers.length ; i<len; i++) {
+ bounds.extend(markers[i].getPoint());
+ }
+
+ this.centerAndZoomOnBounds(bounds);
+ }
+
+GMap2.prototype.centerAndZoomOnPoints = function(points) {
+ var bounds = new GLatLngBounds(points[0],
+ points[0]);
+ for (var i=1, len = points.length ; i<len; i++) {
+ bounds.extend(points[i]);
+ }
+
+ this.centerAndZoomOnBounds(bounds);
+ }
+
+GMap2.prototype.centerAndZoomOnBounds = function(bounds) {
+ var center = bounds.getCenter();
+ this.setCenter(center, this.getBoundsZoomLevel(bounds));
+}
+
+//For full screen mode
+function setWindowDims(elem) {
+ if (window.innerWidth){
+ elem.style.height = (window.innerHeight) + 'px;';
+ elem.style.width = (window.innerWidth) + 'px;';
+ }else if (document.body.clientWidth){
+ elem.style.width = (document.body.clientWidth) + 'px';
+ elem.style.height = (document.body.clientHeight) + 'px';
+ }
+}
+
+ManagedMarker = function(markers,minZoom,maxZoom) {
+ this.markers = markers;
+ this.minZoom = minZoom;
+ this.maxZoom = maxZoom;
+}
+
+//Add the markers and refresh
+function addMarkersToManager(manager,managedMarkers){
+ for(var i = 0, length = managedMarkers.length; i < length;i++) {
+ mm = managedMarkers[i];
+ manager.addMarkers(mm.markers,mm.minZoom,mm.maxZoom);
+ }
+ manager.refresh();
+ return manager;
+}
+
+
+var INVISIBLE = new GLatLng(0,0); //almost always invisible
+
+if(self.Event && Event.observe){
+ Event.observe(window, 'unload', GUnload);
+}else{
+ window.onunload = GUnload;
+}
View
214 lib/gm_plugin/control.rb
@@ -1,107 +1,107 @@
-module Ym4r
- module GmPlugin
- #Small map control. Report to the Google Maps API documentation for details.
- class GSmallMapControl
- include MappingObject
- def create
- "new GSmallMapControl()"
- end
- end
- #Large Map control. Report to the Google Maps API documentation for details.
- class GLargeMapControl
- include MappingObject
- def create
- "new GLargeMapControl()"
- end
- end
- #Small Zoom control. Report to the Google Maps API documentation for details.
- class GSmallZoomControl
- include MappingObject
- def create
- "new GSmallZoomControl()"
- end
- end
- #Scale control. Report to the Google Maps API documentation for details.
- class GScaleControl
- include MappingObject
- def create
- "new GScaleControl()"
- end
- end
- #Map type control. Report to the Google Maps API documentation for details.
- class GMapTypeControl
- include MappingObject
- def create
- "new GMapTypeControl()"
- end
- end
- #Map type control. Report to the Google Maps API documentation for details.
- class GHierarchicalMapTypeControl
- include MappingObject
- def create
- "new GHierarchicalMapTypeControl()"
- end
- end
- #Overview map control. Report to the Google Maps API documentation for details.
- class GOverviewMapControl
- include MappingObject
- def initialize(size = nil)
- @size = size
- end
- def create
- "new GOverviewMapControl(#{@size ? @size.create : ''})"
- end
- end
-
- # Local Search control. Report to the Google Maps API documentation for details.
- # The first argument of the constructor is one of the following: :top_right, :top_left, :bottom_right, :bottom_left.
- # The second and third arguments of the constructor are the offset width and height respectively in pixels.
- # The fourth argument is a javascript hash of valid Google local search control options
- # (ex. {suppressZoomToBounds : true, resultList : google.maps.LocalSearch.RESULT_LIST_INLINE,
- # suppressInitialResultSelection : true, searchFormHint : 'Local Search powered by Google',
- # linkTarget : GSearch.LINK_TARGET_BLANK})
- class GLocalSearchControl < Struct.new(:anchor, :offset_width, :offset_height, :options)
- include MappingObject
- def create
- if offset_width.nil?
- ow = 10
- else
- ow = offset_width
- end
- if offset_height.nil?
- oh = 20
- else
- oh = offset_height
- end
- js_anchor = if anchor == :top_right
- "G_ANCHOR_TOP_RIGHT"
- elsif anchor == :top_left
- "G_ANCHOR_TOP_LEFT"
- elsif anchor == :bottom_right
- "G_ANCHOR_BOTTOM_RIGHT"
- else
- "G_ANCHOR_BOTTOM_LEFT"
- end
- "new google.maps.LocalSearch(options), new GControlPosition(#{js_anchor}, new GSize(#{ow},#{oh}))"
- end
- end
-
- #An object representing a position of a control.
- #The first argument of the constructor is one of the following : :top_right, :top_left, :bottom_right, :bottom_left.
- class GControlPosition < Struct.new(:anchor,:offset)
- include MappingObject
- def create
- js_anchor = if anchor == :top_right
- "G_ANCHOR_TOP_RIGHT"
- elsif anchor == :top_left
- "G_ANCHOR_TOP_LEFT"
- elsif anchor == :bottom_right
- "G_ANCHOR_BOTTOM_RIGHT"
- else
- "G_ANCHOR_BOTTOM_LEFT"
- end
- "new GControlPosition(#{js_anchor},#{offset})"
- end
- end
- end
-end
+module Ym4r
+ module GmPlugin
+ #Small map control. Report to the Google Maps API documentation for details.
+ class GSmallMapControl
+ include MappingObject
+ def create
+ "new GSmallMapControl()"
+ end
+ end
+ #Large Map control. Report to the Google Maps API documentation for details.
+ class GLargeMapControl
+ include MappingObject
+ def create
+ "new GLargeMapControl()"
+ end
+ end
+ #Small Zoom control. Report to the Google Maps API documentation for details.
+ class GSmallZoomControl
+ include MappingObject
+ def create
+ "new GSmallZoomControl()"
+ end
+ end
+ #Scale control. Report to the Google Maps API documentation for details.
+ class GScaleControl
+ include MappingObject
+ def create
+ "new GScaleControl()"
+ end
+ end
+ #Map type control. Report to the Google Maps API documentation for details.
+ class GMapTypeControl
+ include MappingObject
+ def create
+ "new GMapTypeControl()"
+ end
+ end
+ #Map type control. Report to the Google Maps API documentation for details.
+ class GHierarchicalMapTypeControl
+ include MappingObject
+ def create
+ "new GHierarchicalMapTypeControl()"
+ end
+ end
+ #Overview map control. Report to the Google Maps API documentation for details.
+ class GOverviewMapControl
+ include MappingObject
+ def initialize(size = nil)
+ @size = size
+ end
+ def create
+ "new GOverviewMapControl(#{@size ? @size.create : ''})"
+ end
+ end
+
+ # Local Search control. Report to the Google Maps API documentation for details.
+ # The first argument of the constructor is one of the following: :top_right, :top_left, :bottom_right, :bottom_left.
+ # The second and third arguments of the constructor are the offset width and height respectively in pixels.
+ # The fourth argument is a javascript hash of valid Google local search control options
+ # (ex. {suppressZoomToBounds : true, resultList : google.maps.LocalSearch.RESULT_LIST_INLINE,
+ # suppressInitialResultSelection : true, searchFormHint : 'Local Search powered by Google',
+ # linkTarget : GSearch.LINK_TARGET_BLANK})
+ class GLocalSearchControl < Struct.new(:anchor, :offset_width, :offset_height, :options)
+ include MappingObject
+ def create
+ if offset_width.nil?
+ ow = 10
+ else
+ ow = offset_width
+ end
+ if offset_height.nil?
+ oh = 20
+ else
+ oh = offset_height
+ end
+ js_anchor = if anchor == :top_right
+ "G_ANCHOR_TOP_RIGHT"
+ elsif anchor == :top_left
+ "G_ANCHOR_TOP_LEFT"
+ elsif anchor == :bottom_right
+ "G_ANCHOR_BOTTOM_RIGHT"
+ else
+ "G_ANCHOR_BOTTOM_LEFT"
+ end
+ "new google.maps.LocalSearch(options), new GControlPosition(#{js_anchor}, new GSize(#{ow},#{oh}))"
+ end
+ end
+
+ #An object representing a position of a control.
+ #The first argument of the constructor is one of the following : :top_right, :top_left, :bottom_right, :bottom_left.
+ class GControlPosition < Struct.new(:anchor,:offset)
+ include MappingObject
+ def create
+ js_anchor = if anchor == :top_right
+ "G_ANCHOR_TOP_RIGHT"
+ elsif anchor == :top_left
+ "G_ANCHOR_TOP_LEFT"
+ elsif anchor == :bottom_right
+ "G_ANCHOR_BOTTOM_RIGHT"
+ else
+ "G_ANCHOR_BOTTOM_LEFT"
+ end
+ "new GControlPosition(#{js_anchor},#{offset})"
+ end
+ end
+ end
+end
View
236 lib/gm_plugin/geocoding.rb
@@ -1,118 +1,118 @@
-require 'open-uri'
-require 'rexml/document'
-
-module Ym4r
- module GmPlugin
- module Geocoding
-
- GEO_SUCCESS = 200
- GEO_MISSING_ADDRESS = 601
- GEO_UNKNOWN_ADDRESS = 602
- GEO_UNAVAILABLE_ADDRESS = 603
- GEO_BAD_KEY = 610
- GEO_TOO_MANY_QUERIES = 620
- GEO_SERVER_ERROR = 500
-
- #Gets placemarks by querying the Google Maps Geocoding service with the +request+ string. Options can either an explicity GMaps API key (<tt>:key</tt>) or a host, (<tt>:host</tt>).
- def self.get(request,options = {})
- api_key = ApiKey.get(options)
- sensor = options[:sensor] || false
- output = options[:output] || "kml"
- output_encoding = options[:output_encoding] || "utf-8"
- url = "http://maps.google.com/maps/geo?q=#{URI.encode(request)}&key=#{api_key}&sensor=#{sensor}&output=#{output}&oe=#{output_encoding}"
-
- res = open(url).read
-
- case output.to_sym
- when :json
- res = eval(res.gsub(":","=>")) #!!!EVAL EVAL EVAL EVAL!!! hopefully we can trust google...
- placemarks = Placemarks.new(res['name'],res['Status']['code'])
- if res['Placemark']
- placemark = res['Placemark']
-
- placemark.each do |data|
-
- data_country = data['Country']['CountryNameCode'] rescue ""
- data_administrative = data['Country']['AdministrativeArea']['AdministrativeAreaName'] rescue ""
- data_sub_administrative = data['Country']['AdministrativeArea']['SubAdministrativeArea']['SubAdministrativeAreaName'] rescue ""
- data_locality = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['LocalityName'] rescue ""
- data_dependent_locality = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocality']['DependentLocalityName'] rescue ""
- data_thoroughfare = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocality']['Thoroughfare']['ThoroughfareName'] rescue ""
- data_postal_code = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocality']['Thoroughfare']['PostalCode']['PostalCodeNumber'] rescue ""
- lon, lat = data['Point']['coordinates'][0,2]
- data_accuracy = data['Accuracy']
- unless data_accuracy.nil?
- data_accuracy = data_accuracy.to_i
- end
-
- placemarks << Geocoding::Placemark.new(data['address'],
- data_country,
- data_administrative,
- data_sub_administrative,
- data_locality,
- data_dependent_locality,
- data_thoroughfare,
- data_postal_code,
- lon, lat, data_accuracy)
-
- end
- end
- when :kml, :xml
-
- doc = REXML::Document.new(res)
-
- response = doc.elements['//Response']
- placemarks = Placemarks.new(response.elements['name'].text,response.elements['Status/code'].text.to_i)
- response.elements.each(".//Placemark") do |placemark|
- data = placemark.elements
- data_country = data['.//CountryNameCode']
- data_administrative = data['.//AdministrativeAreaName']
- data_sub_administrative = data['.//SubAdministrativeAreaName']
- data_locality = data['.//LocalityName']
- data_dependent_locality = data['.//DependentLocalityName']
- data_thoroughfare = data['.//ThoroughfareName']
- data_postal_code = data['.//PostalCodeNumber']
- lon, lat = data['.//coordinates'].text.split(",")[0..1].collect {|l| l.to_f }
- data_accuracy = data['.//*[local-name()="AddressDetails"]'].attributes['Accuracy']
- unless data_accuracy.nil?
- data_accuracy = data_accuracy.to_i
- end
- placemarks << Geocoding::Placemark.new(data['address'].text,
- data_country.nil? ? "" : data_country.text,
- data_administrative.nil? ? "" : data_administrative.text,
- data_sub_administrative.nil? ? "" : data_sub_administrative.text,
- data_locality.nil? ? "" : data_locality.text,
- data_dependent_locality.nil? ? "" : data_dependent_locality.text,
- data_thoroughfare.nil? ? "" : data_thoroughfare.text,
- data_postal_code.nil? ? "" : data_postal_code.text,
- lon, lat, data_accuracy )
- end
- end
-
- placemarks
- end
-
- #Group of placemarks returned by the Geocoding service. If the result is valid the +status+ attribute should be equal to <tt>Geocoding::GE0_SUCCESS</tt>
- class Placemarks < Array
- attr_accessor :name,:status
-
- def initialize(name,status)
- super(0)
- @name = name
- @status = status
- end
- end
-
- #A result from the Geocoding service.
- class Placemark < Struct.new(:address,:country_code,:administrative_area,:sub_administrative_area,:locality,:dependent_locality,:thoroughfare,:postal_code,:longitude,:latitude,:accuracy)
- def lonlat
- [longitude,latitude]
- end
-
- def latlon
- [latitude,longitude]
- end
- end
- end
- end
-end
+require 'open-uri'
+require 'rexml/document'
+
+module Ym4r
+ module GmPlugin
+ module Geocoding
+
+ GEO_SUCCESS = 200
+ GEO_MISSING_ADDRESS = 601
+ GEO_UNKNOWN_ADDRESS = 602
+ GEO_UNAVAILABLE_ADDRESS = 603
+ GEO_BAD_KEY = 610
+ GEO_TOO_MANY_QUERIES = 620
+ GEO_SERVER_ERROR = 500
+
+ #Gets placemarks by querying the Google Maps Geocoding service with the +request+ string. Options can either an explicity GMaps API key (<tt>:key</tt>) or a host, (<tt>:host</tt>).
+ def self.get(request,options = {})
+ api_key = ApiKey.get(options)
+ sensor = options[:sensor] || false
+ output = options[:output] || "kml"
+ output_encoding = options[:output_encoding] || "utf-8"
+ url = "http://maps.google.com/maps/geo?q=#{URI.encode(request)}&key=#{api_key}&sensor=#{sensor}&output=#{output}&oe=#{output_encoding}"
+
+ res = open(url).read
+
+ case output.to_sym
+ when :json
+ res = eval(res.gsub(":","=>")) #!!!EVAL EVAL EVAL EVAL!!! hopefully we can trust google...
+ placemarks = Placemarks.new(res['name'],res['Status']['code'])
+ if res['Placemark']
+ placemark = res['Placemark']
+
+ placemark.each do |data|
+
+ data_country = data['Country']['CountryNameCode'] rescue ""
+ data_administrative = data['Country']['AdministrativeArea']['AdministrativeAreaName'] rescue ""
+ data_sub_administrative = data['Country']['AdministrativeArea']['SubAdministrativeArea']['SubAdministrativeAreaName'] rescue ""
+ data_locality = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['LocalityName'] rescue ""
+ data_dependent_locality = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocality']['DependentLocalityName'] rescue ""
+ data_thoroughfare = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocality']['Thoroughfare']['ThoroughfareName'] rescue ""
+ data_postal_code = data['Country']['AdministrativeArea']['SubAdministrativeArea']['Locality']['DependentLocality']['Thoroughfare']['PostalCode']['PostalCodeNumber'] rescue ""
+ lon, lat = data['Point']['coordinates'][0,2]
+ data_accuracy = data['Accuracy']
+ unless data_accuracy.nil?
+ data_accuracy = data_accuracy.to_i
+ end
+
+ placemarks << Geocoding::Placemark.new(data['address'],
+ data_country,
+ data_administrative,
+ data_sub_administrative,
+ data_locality,
+ data_dependent_locality,
+ data_thoroughfare,
+ data_postal_code,
+ lon, lat, data_accuracy)
+
+ end
+ end
+ when :kml, :xml
+
+ doc = REXML::Document.new(res)
+
+ response = doc.elements['//Response']
+ placemarks = Placemarks.new(response.elements['name'].text,response.elements['Status/code'].text.to_i)
+ response.elements.each(".//Placemark") do |placemark|
+ data = placemark.elements
+ data_country = data['.//CountryNameCode']
+ data_administrative = data['.//AdministrativeAreaName']
+ data_sub_administrative = data['.//SubAdministrativeAreaName']
+ data_locality = data['.//LocalityName']
+ data_dependent_locality = data['.//DependentLocalityName']
+ data_thoroughfare = data['.//ThoroughfareName']
+ data_postal_code = data['.//PostalCodeNumber']
+ lon, lat = data['.//coordinates'].text.split(",")[0..1].collect {|l| l.to_f }
+ data_accuracy = data['.//*[local-name()="AddressDetails"]'].attributes['Accuracy']
+ unless data_accuracy.nil?
+ data_accuracy = data_accuracy.to_i
+ end
+ placemarks << Geocoding::Placemark.new(data['address'].text,
+ data_country.nil? ? "" : data_country.text,
+ data_administrative.nil? ? "" : data_administrative.text,
+ data_sub_administrative.nil? ? "" : data_sub_administrative.text,
+ data_locality.nil? ? "" : data_locality.text,
+ data_dependent_locality.nil? ? "" : data_dependent_locality.text,
+ data_thoroughfare.nil? ? "" : data_thoroughfare.text,
+ data_postal_code.nil? ? "" : data_postal_code.text,
+ lon, lat, data_accuracy )
+ end
+ end
+
+ placemarks
+ end
+
+ #Group of placemarks returned by the Geocoding service. If the result is valid the +status+ attribute should be equal to <tt>Geocoding::GE0_SUCCESS</tt>
+ class Placemarks < Array
+ attr_accessor :name,:status
+
+ def initialize(name,status)
+ super(0)
+ @name = name
+ @status = status
+ end
+ end
+
+ #A result from the Geocoding service.
+ class Placemark < Struct.new(:address,:country_code,:administrative_area,:sub_administrative_area,:locality,:dependent_locality,:thoroughfare,:postal_code,:longitude,:latitude,:accuracy)
+ def lonlat
+ [longitude,latitude]
+ end
+
+ def latlon
+ [latitude,longitude]
+ end
+ end
+ end
+ end
+end
View
144 lib/gm_plugin/helper.rb
@@ -1,72 +1,72 @@
-
-Ym4r::GmPlugin::GPolyline.class_eval do
- #Creates a GPolyline object from a georuby line string. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.
- def self.from_georuby(line_string,color = nil,weight = nil,opacity = nil)
- GPolyline.new(line_string.points.collect { |point| GLatLng.new([point.y,point.x])},color,weight,opacity)
- end
-end
-
-Ym4r::GmPlugin::GMarker.class_eval do
- #Creates a GMarker object from a georuby point. Accepts the same options as the GMarker constructor. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.
- def self.from_georuby(point,options = {})
- GMarker.new([point.y,point.x],options)
- end
-end
-
-Ym4r::GmPlugin::GLatLng.class_eval do
- #Creates a GLatLng object from a georuby point. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.
- def self.from_georuby(point,unbounded = nil)
- GLatLng.new([point.y,point.x],unbounded)
- end
-end
-
-Ym4r::GmPlugin::GLatLngBounds.class_eval do
- #Creates a GLatLng object from a georuby point. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.
- def self.from_georuby(envelope)
- GLatLngBounds.new(GLatLng.from_georuby(envelope.lower_corner),
- GLatLng.from_georuby(envelope.upper_corner))
- end
-end
-
-Ym4r::GmPlugin::GPolygon.class_eval do
- #Creates a GPolygon object from a georuby polygon or line string. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.
- def self.from_georuby(ls_or_p, stroke_color="#000000",stroke_weight=1,stroke_opacity=1.0,color="#ff0000",opacity=1.0)
- if ls_or_p.is_a?(GeoRuby::SimpleFeatures::LineString)
- GPolygon.new(ls_or_p.collect { |point| GLatLng.new([point.y,point.x])},stroke_color,stroke_weight,stroke_opacity,color,opacity)
- else
- GPolygon.new(ls_or_p[0].collect { |point| GLatLng.new([point.y,point.x])},stroke_color,stroke_weight,stroke_opacity,color,opacity)
- end
- end
-end
-
-Ym4r::GmPlugin::GPolylineEncoded.class_eval do
- def self.from_georuby(line_string, color = nil, weight = nil, opacity = nil)
- encoded_points = GMapPolylineEncoder.new.encode(
- line_string.points.collect {|p| [p.y, p.x]})
- GPolylineEncoded.new(
- :points => encoded_points[:points],
- :levels => encoded_points[:levels],
- :num_levels => encoded_points[:numLevels],
- :zoom_factor => encoded_points[:zoomFactor],
- :color => color,
- :weight => weight,
- :opacity => opacity
- )
- end
-end
-
-Ym4r::GmPlugin::GPolygonEncoded.class_eval do
- def self.from_georuby(ls_or_p, stroke_color="#000000",stroke_weight=1,stroke_opacity=1.0,color="#ff0000",opacity=1.0)
- if ls_or_p.is_a?(GeoRuby::SimpleFeatures::LineString)
- GPolygonEncoded.new(
- GPolylineEncoded.from_georuby(ls_or_p, stroke_color, stroke_weight, stroke_opacity),
- color.nil?, color, opacity, stroke_weight > 0)
- else
- polylines = ls_or_p.rings.collect do |line_string|
- GPolylineEncoded.from_georuby(line_string, stroke_color,
- stroke_weight, stroke_opacity)
- end
- GPolygonEncoded.new(polylines, true, color, opacity, true)
- end
- end
-end
+
+Ym4r::GmPlugin::GPolyline.class_eval do
+ #Creates a GPolyline object from a georuby line string. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.
+ def self.from_georuby(line_string,color = nil,weight = nil,opacity = nil)
+ GPolyline.new(line_string.points.collect { |point| GLatLng.new([point.y,point.x])},color,weight,opacity)
+ end
+end
+
+Ym4r::GmPlugin::GMarker.class_eval do
+ #Creates a GMarker object from a georuby point. Accepts the same options as the GMarker constructor. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.
+ def self.from_georuby(point,options = {})
+ GMarker.new([point.y,point.x],options)
+ end
+end
+
+Ym4r::GmPlugin::GLatLng.class_eval do
+ #Creates a GLatLng object from a georuby point. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.
+ def self.from_georuby(point,unbounded = nil)
+ GLatLng.new([point.y,point.x],unbounded)
+ end
+end
+
+Ym4r::GmPlugin::GLatLngBounds.class_eval do
+ #Creates a GLatLng object from a georuby point. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.
+ def self.from_georuby(envelope)
+ GLatLngBounds.new(GLatLng.from_georuby(envelope.lower_corner),
+ GLatLng.from_georuby(envelope.upper_corner))
+ end
+end
+
+Ym4r::GmPlugin::GPolygon.class_eval do
+ #Creates a GPolygon object from a georuby polygon or line string. Assumes the points of the line strings are stored in Longitude(x)/Latitude(y) order.
+ def self.from_georuby(ls_or_p, stroke_color="#000000",stroke_weight=1,stroke_opacity=1.0,color="#ff0000",opacity=1.0)
+ if ls_or_p.is_a?(GeoRuby::SimpleFeatures::LineString)
+ GPolygon.new(ls_or_p.collect { |point| GLatLng.new([point.y,point.x])},stroke_color,stroke_weight,stroke_opacity,color,opacity)
+ else
+ GPolygon.new(ls_or_p[0].collect { |point| GLatLng.new([point.y,point.x])},stroke_color,stroke_weight,stroke_opacity,color,opacity)
+ end
+ end
+end
+
+Ym4r::GmPlugin::GPolylineEncoded.class_eval do
+ def self.from_georuby(line_string, color = nil, weight = nil, opacity = nil)
+ encoded_points = GMapPolylineEncoder.new.encode(
+ line_string.points.collect {|p| [p.y, p.x]})
+ GPolylineEncoded.new(
+ :points => encoded_points[:points],
+ :levels => encoded_points[:levels],
+ :num_levels => encoded_points[:numLevels],
+ :zoom_factor => encoded_points[:zoomFactor],
+ :color => color,
+ :weight => weight,
+ :opacity => opacity
+ )
+ end
+end
+
+Ym4r::GmPlugin::GPolygonEncoded.class_eval do
+ def self.from_georuby(ls_or_p, stroke_color="#000000",stroke_weight=1,stroke_opacity=1.0,color="#ff0000",opacity=1.0)
+ if ls_or_p.is_a?(GeoRuby::SimpleFeatures::LineString)
+ GPolygonEncoded.new(
+ GPolylineEncoded.from_georuby(ls_or_p, stroke_color, stroke_weight, stroke_opacity),
+ color.nil?, color, opacity, stroke_weight > 0)
+ else
+ polylines = ls_or_p.rings.collect do |line_string|
+ GPolylineEncoded.from_georuby(line_string, stroke_color,
+ stroke_weight, stroke_opacity)
+ end
+ GPolygonEncoded.new(polylines, true, color, opacity, true)
+ end
+ end
+end
View
74 lib/gm_plugin/key.rb
@@ -1,37 +1,37 @@
-module Ym4r
- module GmPlugin
- class GMapsAPIKeyConfigFileNotFoundException < StandardError
- end
-
- class AmbiguousGMapsAPIKeyException < StandardError
- end
-
- #Class fo the manipulation of the API key
- class ApiKey
- #Read the API key config for the current ENV
- unless File.exist?(RAILS_ROOT + '/config/gmaps_api_key.yml')
- raise GMapsAPIKeyConfigFileNotFoundException.new("File RAILS_ROOT/config/gmaps_api_key.yml not found")
- else
- env = ENV['RAILS_ENV'] || RAILS_ENV
- GMAPS_API_KEY = YAML.load_file(RAILS_ROOT + '/config/gmaps_api_key.yml')[env]
- end
-
- def self.get(options = {})
- if options.has_key?(:key)
- options[:key]
- elsif GMAPS_API_KEY.is_a?(Hash)
- #For this environment, multiple hosts are possible.
- #:host must have been passed as option
- if options.has_key?(:host)
- GMAPS_API_KEY[options[:host]]
- else
- raise AmbiguousGMapsAPIKeyException.new(GMAPS_API_KEY.keys.join(","))
- end
- else
- #Only one possible key: take it and ignore the :host option if it is there
- GMAPS_API_KEY
- end
- end
- end
- end
-end
+module Ym4r
+ module GmPlugin
+ class GMapsAPIKeyConfigFileNotFoundException < StandardError
+ end
+
+ class AmbiguousGMapsAPIKeyException < StandardError
+ end
+
+ #Class fo the manipulation of the API key
+ class ApiKey
+ #Read the API key config for the current ENV
+ unless File.exist?(RAILS_ROOT + '/config/gmaps_api_key.yml')
+ raise GMapsAPIKeyConfigFileNotFoundException.new("File RAILS_ROOT/config/gmaps_api_key.yml not found")
+ else
+ env = ENV['RAILS_ENV'] || RAILS_ENV
+ GMAPS_API_KEY = YAML.load_file(RAILS_ROOT + '/config/gmaps_api_key.yml')[env]
+ end
+
+ def self.get(options = {})
+ if options.has_key?(:key)
+ options[:key]
+ elsif GMAPS_API_KEY.is_a?(Hash)
+ #For this environment, multiple hosts are possible.
+ #:host must have been passed as option
+ if options.has_key?(:host)
+ GMAPS_API_KEY[options[:host]]
+ else
+ raise AmbiguousGMapsAPIKeyException.new(GMAPS_API_KEY.keys.join(","))
+ end
+ else
+ #Only one possible key: take it and ignore the :host option if it is there
+ GMAPS_API_KEY
+ end
+ end
+ end
+ end
+end
View
252 lib/gm_plugin/layer.rb
@@ -1,126 +1,126 @@
-module Ym4r
- module GmPlugin
- #Map types of the map
- class GMapType
- include MappingObject
-
- G_NORMAL_MAP = Variable.new("G_NORMAL_MAP")
- G_SATELLITE_MAP = Variable.new("G_SATELLITE_MAP")
- G_HYBRID_MAP = Variable.new("G_HYBRID_MAP")
- G_PHYSICAL_MAP = Variable.new("G_PHYSICAL_MAP")
-
- attr_accessor :layers, :name, :projection, :options
-
- #The options can be any of the GMapType options detailed in the documentation + a <tt>:projection</tt>.
- def initialize(layers, name, options = {})
- @layers = layers
- @name = name
- @projection = options.delete(:projection) || GMercatorProjection.new
- @options = options
- end
-
- def create
- "new GMapType(#{MappingObject.javascriptify_variable(Array(layers))}, #{MappingObject.javascriptify_variable(projection)}, #{MappingObject.javascriptify_variable(name)}, #{MappingObject.javascriptify_variable(options)})"
- end
- end
-
- #Represents a mercator projection for zoom levels 0 to 17 (more than that by passing an argument to the constructor)
- class GMercatorProjection
- include MappingObject
-
- attr_accessor :n
-
- def initialize(n = nil)
- @n = n
- end
-
- def create
- if n.nil?
- return "G_NORMAL_MAP.getProjection()"
- else
- "new GMercatorProjection(#{@n})"
- end
- end
- end
-
- #Abstract Tile layer. Subclasses must implement a get_tile_url method.
- class GTileLayer
- include MappingObject
-
- attr_accessor :opacity, :zoom_range, :copyright, :format
-
- #Options are the following, with default values:
- #:zoom_range (0..17), :copyright ({'prefix' => '', 'copyright_texts' => [""]}), :opacity (1.0), :format ("png")
- def initialize(options = {})
- @opacity = options[:opacity] || 1.0
- @zoom_range = options[:zoom_range] || (0..17)
- @copyright = options[:copyright] || {'prefix' => '', 'copyright_texts' => [""]}
- @format = (options[:format] || "png").to_s
- end
-
- def create
- "addPropertiesToLayer(new GTileLayer(new GCopyrightCollection(\"\"),#{zoom_range.begin},#{zoom_range.end}),#{get_tile_url},function(a,b) {return #{MappingObject.javascriptify_variable(@copyright)};}\n,function() {return #{@opacity};},function(){return #{@format == "png"};})"
- end
-
- #for subclasses to implement
- def get_tile_url
- end
- end
-
- #Represents a pre tiled layer, taking images directly from a server, without using a server script.
- class PreTiledLayer < GTileLayer
- attr_accessor :base_url
-
- #Possible options are the same as for the GTileLayer constructor
- def initialize(base_url,options = {})
- super(options)
- @base_url = base_url
- end
-
- #Returns the code to determine the url to fetch the tile. Follows the convention adopted by the tiler: {base_url}/tile_{b}_{a.x}_{a.y}.{format}
- def get_tile_url
- "function(a,b) { return '#{@base_url}/tile_' + b + '_' + a.x + '_' + a.y + '.#{format}';}"
- end
- end
-
- #Represents a pretiled layer (it actually does not really matter where the tiles come from). Calls an action on the server to get back the tiles. It passes the action arguments x, y (coordinates of the tile) and z (zoom level). It can be used, for example, to return default tiles when the requested tile is not present.
- class PreTiledLayerFromAction < PreTiledLayer
- def get_tile_url
- "function(a,b) { return '#{base_url}?x=' + a.x + '&y=' + a.y + '&z=' + b ;}"
- end
- end
-
- #Represents a TileLayer where the tiles are generated dynamically from a WMS server (MapServer, GeoServer,...)
- #You need to include the JavaScript file wms-gs.js for this to work
- #see http://docs.codehaus.org/display/GEOSDOC/Google+Maps
- class WMSLayer < GTileLayer
- attr_accessor :base_url, :layers, :styles, :merc_proj, :use_geographic
-
- #Options are the same as with GTileLayer + :styles (""), :merc_proj (:mapserver), :use_geographic (false)
- def initialize(base_url, layers, options = {})
- super(options)
- @base_url = base_url.gsub(/\?$/,"") #standardize the url
- @layers = layers
- @styles = options[:styles] || ""
- merc_proj = options[:merc_proj] || :mapserver
- @merc_proj = if merc_proj == :mapserver
- "54004"
- elsif merc_proj == :geoserver
- "41001"
- else
- merc_proj.to_s
- end
- @use_geographic = options.has_key?(:use_geographic)? options[:use_geographic] : false
- puts format
- end
-
- def get_tile_url
- "getTileUrlForWMS"
- end
-
- def create
- "addWMSPropertiesToLayer(#{super},#{MappingObject.javascriptify_variable(@base_url)},#{MappingObject.javascriptify_variable(@layers)},#{MappingObject.javascriptify_variable(@styles)},#{MappingObject.javascriptify_variable(format)},#{MappingObject.javascriptify_variable(@merc_proj)},#{MappingObject.javascriptify_variable(@use_geographic)})"
- end
- end
- end
-end
+module Ym4r
+ module GmPlugin
+ #Map types of the map
+ class GMapType
+ include MappingObject
+
+ G_NORMAL_MAP = Variable.new("G_NORMAL_MAP")
+ G_SATELLITE_MAP = Variable.new("G_SATELLITE_MAP")
+ G_HYBRID_MAP = Variable.new("G_HYBRID_MAP")
+ G_PHYSICAL_MAP = Variable.new("G_PHYSICAL_MAP")
+
+ attr_accessor :layers, :name, :projection, :options
+
+ #The options can be any of the GMapType options detailed in the documentation + a <tt>:projection</tt>.
+ def initialize(layers, name, options = {})
+ @layers = layers
+ @name = name
+ @projection = options.delete(:projection) || GMercatorProjection.new
+ @options = options
+ end
+
+ def create
+ "new GMapType(#{MappingObject.javascriptify_variable(Array(layers))}, #{MappingObject.javascriptify_variable(projection)}, #{MappingObject.javascriptify_variable(name)}, #{MappingObject.javascriptify_variable(options)})"
+ end
+ end
+
+ #Represents a mercator projection for zoom levels 0 to 17 (more than that by passing an argument to the constructor)
+ class GMercatorProjection
+ include MappingObject
+
+ attr_accessor :n
+
+ def initialize(n = nil)
+ @n = n
+ end
+
+ def create
+ if n.nil?
+ return "G_NORMAL_MAP.getProjection()"
+ else
+ "new GMercatorProjection(#{@n})"
+ end
+ end
+ end
+
+ #Abstract Tile layer. Subclasses must implement a get_tile_url method.
+ class GTileLayer
+ include MappingObject
+
+ attr_accessor :opacity, :zoom_range, :copyright, :format
+
+ #Options are the following, with default values:
+ #:zoom_range (0..17), :copyright ({'prefix' => '', 'copyright_texts' => [""]}), :opacity (1.0), :format ("png")
+ def initialize(options = {})
+ @opacity = options[:opacity] || 1.0
+ @zoom_range = options[:zoom_range] || (0..17)
+ @copyright = options[:copyright] || {'prefix' => '', 'copyright_texts' => [""]}
+ @format = (options[:format] || "png").to_s
+ end
+
+ def create
+ "addPropertiesToLayer(new GTileLayer(new GCopyrightCollection(\"\"),#{zoom_range.begin},#{zoom_range.end}),#{get_tile_url},function(a,b) {return #{MappingObject.javascriptify_variable(@copyright)};}\n,function() {return #{@opacity};},function(){return #{@format == "png"};})"
+ end
+
+ #for subclasses to implement
+ def get_tile_url
+ end
+ end
+
+ #Represents a pre tiled layer, taking images directly from a server, without using a server script.
+ class PreTiledLayer < GTileLayer
+ attr_accessor :base_url
+
+ #Possible options are the same as for the GTileLayer constructor
+ def initialize(base_url,options = {})
+ super(options)
+ @base_url = base_url
+ end
+
+ #Returns the code to determine the url to fetch the tile. Follows the convention adopted by the tiler: {base_url}/tile_{b}_{a.x}_{a.y}.{format}
+ def get_tile_url
+ "function(a,b) { return '#{@base_url}/tile_' + b + '_' + a.x + '_' + a.y + '.#{format}';}"
+ end
+ end
+
+ #Represents a pretiled layer (it actually does not really matter where the tiles come from). Calls an action on the server to get back the tiles. It passes the action arguments x, y (coordinates of the tile) and z (zoom level). It can be used, for example, to return default tiles when the requested tile is not present.
+ class PreTiledLayerFromAction < PreTiledLayer
+ def get_tile_url
+ "function(a,b) { return '#{base_url}?x=' + a.x + '&y=' + a.y + '&z=' + b ;}"
+ end
+ end
+
+ #Represents a TileLayer where the tiles are generated dynamically from a WMS server (MapServer, GeoServer,...)
+ #You need to include the JavaScript file wms-gs.js for this to work
+ #see http://docs.codehaus.org/display/GEOSDOC/Google+Maps
+ class WMSLayer < GTileLayer
+ attr_accessor :base_url, :layers, :styles, :merc_proj, :use_geographic
+
+ #Options are the same as with GTileLayer + :styles (""), :merc_proj (:mapserver), :use_geographic (false)
+ def initialize(base_url, layers, options = {})
+ super(options)
+ @base_url = base_url.gsub(/\?$/,"") #standardize the url
+ @layers = layers
+ @styles = options[:styles] || ""
+ merc_proj = options[:merc_proj] || :mapserver
+ @merc_proj = if merc_proj == :mapserver
+ "54004"
+ elsif merc_proj == :geoserver
+ "41001"
+ else
+ merc_proj.to_s
+ end
+ @use_geographic = options.has_key?(:use_geographic)? options[:use_geographic] : false
+ puts format
+ end
+
+ def get_tile_url
+ "getTileUrlForWMS"
+ end
+
+ def create
+ "addWMSPropertiesToLayer(#{super},#{MappingObject.javascriptify_variable(@base_url)},#{MappingObject.javascriptify_variable(@layers)},#{MappingObject.javascriptify_variable(@styles)},#{MappingObject.javascriptify_variable(format)},#{MappingObject.javascriptify_variable(@merc_proj)},#{MappingObject.javascriptify_variable(@use_geographic)})"
+ end
+ end
+ end
+end
View
602 lib/gm_plugin/map.rb
@@ -1,301 +1,301 @@
-module Ym4r
- module GmPlugin
- #Representing the Google Maps API class GMap2.
- class GMap
- include MappingObject
-
- #A constant containing the declaration of the VML namespace, necessary to display polylines under IE.
- VML_NAMESPACE = "xmlns:v=\"urn:schemas-microsoft-com:vml\""
-
- #The id of the DIV that will contain the map in the HTML page.
- attr_reader :container
-
- #By default the map in the HTML page will be globally accessible with the name +map+.
- def initialize(container, variable = "map")
- @container = container
- @variable = variable
- @init = []
- @init_end = [] #for stuff that must be initialized at the end (controls)
- @init_begin = [] #for stuff that must be initialized at the beginning (center + zoom)
- @global_init = []
- end
-
- #Deprecated. Use the static version instead.
- def header(with_vml = true)
- GMap.header(:with_vml => with_vml)
- end
-
- #Outputs the header necessary to use the Google Maps API, by including the JS files of the API, as well as a file containing YM4R/GM helper functions. By default, it also outputs a style declaration for VML elements. This default can be overriddent by passing <tt>:with_vml => false</tt> as option to the method. You can also pass a <tt>:host</tt> option in order to select the correct API key for the location where your app is currently running, in case the current environment has multiple possible keys. Usually, in this case, you should pass it <tt>@request.host</tt>. If you have defined only one API key for the current environment, the <tt>:host</tt> option is ignored. Finally you can override all the key settings in the configuration by passing a value to the <tt>:key</tt> key. You can pass a language for the map type buttons with the <tt>:hl</tt> option (possible values are: Japanese (ja), French (fr), German (de), Italian (it), Spanish (es), Catalan (ca), Basque (eu) and Galician (gl): no values means english). Finally, you can pass <tt>:local_search => true</tt> to get the header css and js information needed for the local search control. If you do want local search you must also add <tt>:local_search => true</tt> to the @map.control_init method.
- def self.header(options = {})
- options[:with_vml] = true unless options.has_key?(:with_vml)
- options[:hl] ||= ''
- options[:local_search] = false unless options.has_key?(:local_search)
- options[:sensor] = false unless options.has_key?(:sensor)
- options[:version] ||= "2.x"
- api_key = ApiKey.get(options)
- a = "<script src=\"http://maps.google.com/maps?file=api&amp;v=#{options[:version]}&amp;key=#{api_key}&amp;hl=#{options[:hl]}&amp;sensor=#{options[:sensor]}\" type=\"text/javascript\"></script>\n"
- a << "<script src=\"#{ActionController::Base.relative_url_root}/javascripts/ym4r-gm.js\" type=\"text/javascript\"></script>\n" unless options[:without_js]
- a << "<!--[if IE]>\n<style type=\"text/css\">\n v\\:* { behavior:url(#default#VML);}\n</style>\n<![endif]-->\n" if options[:with_vml]
- a << "<script src=\"http://www.google.com/uds/api?file=uds.js&amp;v=1.0\" type=\"text/javascript\"></script>" if options[:local_search]
- a << "<script src=\"http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js\" type=\"text/javascript\"></script>\n" if options[:local_search]
- a << "<style type=\"text/css\">@import url(\"http://www.google.com/uds/css/gsearch.css\");@import url(\"http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css\");}</style>" if options[:local_search]
- a
- end
-
- #Outputs the <div id=...></div> which has been configured to contain the map. You can pass <tt>:width</tt> and <tt>:height</tt> as options to output this in the style attribute of the DIV element (you could also achieve the same effect by putting the dimension info into a CSS or using the instance method GMap#header_width_height). You can aslo pass <tt>:class</tt> to set the classname of the div.
- # To include initial content in the div, such as a loading message, you
- # may pass a <tt>:content</tt> option specifying a string, or other
- # object, such as a REXML fragment, that responds to #to_s.
- def div(options = {})
- attributes = "id=\"#{@container}\" "
- if options.has_key?(:height) && options.has_key?(:width)
- width = options.delete(:width)
- if width.is_a?(Integer) or width =~ /^[0-9]+$/
- width = width.to_s + "px"
- end
- height = options.delete(:height)
- if height.is_a?(Integer) or height =~ /^[0-9]+$/
- height = height.to_s + "px"
- end
- attributes += "style=\"width:#{width};height:#{height}\" "
- end
- if options.has_key?(:class)
- attributes += options.keys.map {|opt| "#{opt}=\"#{options[opt]}\"" }.join(" ")
- end
- "<div #{attributes}>#{options[:content].to_s}</div>"
- end
-
- #Outputs a style declaration setting the dimensions of the DIV container of the map. This info can also be set manually in a CSS.
- def header_width_height(width,height)
- "<style type=\"text/css\">\n##{@container} { height: #{height}px;\n width: #{width}px;\n}\n</style>"
- end
-
- #Records arbitrary JavaScript code and outputs it during initialization inside the +load+ function.
- def record_init(code)
- @init << code
- end
-
- #Initializes the controls: you can pass a hash with keys <tt>:small_map</tt>, <tt>:large_map</tt>, <tt>:small_zoom</tt>, <tt>:scale</tt>, <tt>:map_type</tt>, <tt>:overview_map</tt> and hash of options controlling its display (<tt>:hide</tt> and <tt>:size</tt>), <tt>:local_search</tt>, <tt>:local_search_options</tt>, and <tt>:show_on_focus</tt>
- def control_init(controls = {})
- @init_end << add_control(GSmallMapControl.new) if controls[:small_map]
- @init_end << add_control(GLargeMapControl.new) if controls[:large_map]
- @init_end << add_control(GSmallZoomControl.new) if controls[:small_zoom]
- @init_end << add_control(GScaleControl.new) if controls[:scale]
- @init_end << add_control(GMapTypeControl.new) if controls[:map_type]
- @init_end << add_control(GHierarchicalMapTypeControl.new) if controls[:hierarchical_map_type]
- if controls[:overview_map]
- if controls[:overview_map].is_a?(Hash)
- hide = controls[:overview_map][:hide]
- size = controls[:overview_map][:size]
- end
- overview_control = GOverviewMapControl.new(size)
- @global_init << overview_control.declare("#{@variable}_ovm") if hide
- @init_end << add_control(overview_control)
- @init_end << "#{overview_control.variable}.hide(true);" if hide
- end
- @init_end << add_control(GLocalSearchControl.new(controls[:anchor], controls[:offset_width], controls[:offset_height], controls[:local_search_options])) if controls[:local_search]
- if controls[:show_on_focus] # Should be last
- @init_end << "#{@variable}.hideControls();"
- event_init(self, :mouseover, "function(){#{@variable}.showControls();}")
- event_init(self, :mouseout, "function(){#{@variable}.hideControls();}")
- end
- end
-
- #Initializes the interface configuration: double-click zoom, dragging, continuous zoom,... You can pass a hash with keys <tt>:dragging</tt>, <tt>:info_window</tt>, <tt>:double_click_zoom</tt>, <tt>:continuous_zoom</tt> and <tt>:scroll_wheel_zoom</tt>. The values should be true or false. Check the google maps API doc to know what the default values are.
- def interface_init(interface = {})
- if !interface[:dragging].nil?
- if interface[:dragging]
- @init << enableDragging()
- else
- @init << disableDragging()
- end
- end
- if !interface[:info_window].nil?
- if interface[:info_window]
- @init << enableInfoWindow()
- else
- @init << disableInfoWindow()
- end
- end
- if !interface[:double_click_zoom].nil?
- if interface[:double_click_zoom]
- @init << enableDoubleClickZoom()
- else
- @init << disableDoubleClickZoom()
- end
- end
- if !interface[:continuous_zoom].nil?
- if interface[:continuous_zoom]
- @init << enableContinuousZoom()
- else
- @init << disableContinuousZoom()
- end
- end
- if !interface[:scroll_wheel_zoom].nil?
- if interface[:scroll_wheel_zoom]
- @init << enableScrollWheelZoom()
- else
- @init << disableScrollWheelZoom()
- end
- end
- end
-
- #Initializes the initial center and zoom of the map. +center+ can be both a GLatLng object or a 2-float array.
- def center_zoom_init(center, zoom)
- if center.is_a?(GLatLng)
- @init_begin << set_center(center,zoom)
- else
- @init_begin << set_center(GLatLng.new(center),zoom)
- end
- end
-
- #Center and zoom based on the coordinates passed as argument (either 2D arrays or GLatLng objects)
- def center_zoom_on_points_init(*points)
- if(points.length > 0)
- if(points[0].is_a?(Array))
- points = points.collect { |point| GLatLng.new(point) }
- end
- @init_begin << center_and_zoom_on_points(points)
- end
- end
-
- #Center and zoom based on the bbox corners. Pass a GLatLngBounds object, an array of 2D coordinates (sw and ne) or an array of GLatLng objects (sw and ne).
- def center_zoom_on_bounds_init(latlngbounds)
- if(latlngbounds.is_a?(Array))
- if latlngbounds[0].is_a?(Array)
- latlngbounds = GLatLngBounds.new(GLatLng.new(latlngbounds[0]),GLatLng.new(latlngbounds[1]))
- elsif latlngbounds[0].is_a?(GLatLng)
- latlngbounds = GLatLngBounds.new(*latlngbounds)
- end
- end
- #else it is already a latlngbounds object
-
- @init_begin << center_and_zoom_on_bounds(latlngbounds)
- end
-
- #Initializes the map by adding an overlay (marker or polyline).
- def overlay_init(overlay)
- @init << add_overlay(overlay)
- end
-
- #Sets up a new map type. If +add+ is false, all the other map types of the map are wiped out. If you want to access the map type in other methods, you should declare the map type first (with +declare_init+).
- def add_map_type_init(map_type, add = true)
- unless add
- @init << get_map_types.set_property(:length,0)
- end
- @init << add_map_type(map_type)
- end
- #for legacy purpose
- alias :map_type_init :add_map_type_init
-
- #Sets the map type displayed by default after the map is loaded. It should be known from the map (ie either the default map types or a user-defined map type added with <tt>add_map_type_init</tt>). Use <tt>set_map_type_init(GMapType::G_SATELLITE_MAP)</tt> or <tt>set_map_type_init(GMapType::G_HYBRID_MAP)</tt> to initialize the map with repsecitvely the Satellite view and the hybrid view.
- def set_map_type_init(map_type)
- @init << set_map_type(map_type)
- end
-
- #Locally declare a MappingObject with variable name "name"
- def declare_init(variable, name)
- @init << variable.declare(name)
- end
-
- #Records arbitrary JavaScript code and outputs it during initialization outside the +load+ function (ie globally).
- def record_global_init(code)
- @global_init << code
- end
-
- #Deprecated. Use icon_global_init instead.
- def icon_init(icon , name)
- icon_global_init(icon , name)
- end
-
- #Initializes an icon and makes it globally accessible through the JavaScript variable of name +variable+.
- def icon_global_init(icon , name, options = {})
- declare_global_init(icon,name,options)
- end
-
- #Registers an event
- def event_init(object,event,callback)
- @init << "GEvent.addListener(#{object.to_javascript},\"#{MappingObject.javascriptify_method(event.to_s)}\",#{callback});"
- end
-
- #Registers an event globally
- def event_global_init(object,event,callback)
- @global_init << "GEvent.addListener(#{object.to_javascript},\"#{MappingObject.javascriptify_method(event.to_s)}\",#{callback});"
- end
-
- #Declares the overlay globally with name +name+
- def overlay_global_init(overlay,name, options = {})
- declare_global_init(overlay,name, options)
- @init << add_overlay(overlay)
- end
-
- #Globally declare a MappingObject with variable name "name". Option <tt>:local_construction</tt> should be passed if the construction has to be done inside the onload callback method (for exsample if it depends on the GMap to be initialized)
- def declare_global_init(variable,name, options = {})
- unless options[:local_construction]
- @global_init << "var #{variable.assign_to(name)}"
- else
- @global_init << "var #{name};"
- @init << variable.assign_to(name)
- end
- end
-
- #Outputs the initialization code for the map. By default, it outputs the script tags, performs the initialization in response to the onload event of the window and makes the map globally available. If you pass +true+ to the option key <tt>:full</tt>, the map will be setup in full screen, in which case it is not necessary (but not harmful) to set a size for the map div.
- def to_html(options = {})
- no_load = options[:no_load]
- no_script_tag = options[:no_script_tag]
- no_declare = options[:no_declare]
- no_global = options[:no_global]
- fullscreen = options[:full]
- load_pr = options[:proto_load] #to prevent some problems when the onload event callback from Prototype is used
-
- html = ""
- html << "<script type=\"text/javascript\">\n" if !no_script_tag
- #put the functions in a separate javascript file to be included in the page
- html << @global_init * "\n"
- html << "var #{@variable};\n" if !no_declare and !no_global
- if !no_load
- if load_pr
- html << "Event.observe(window,'load',"
- else
- html << "window.onload = addCodeToFunction(window.onload,"
- end
- html << "function() {\n"
- end
-
- html << "if (GBrowserIsCompatible()) {\n"
-
- if fullscreen
- #Adding the initial resizing and setting up the event handler for
- #future resizes
- html << "setWindowDims(document.getElementById('#{@container}'));\n"
- html << "if (window.attachEvent) { window.attachEvent(\"onresize\", function() {setWindowDims(document.getElementById('#{@container}'));})} else {window.addEventListener(\"resize\", function() {setWindowDims(document.getElementById('#{@container}')); } , false);}\n"
- end
-
- if !no_declare and no_global
- html << "#{declare(@variable)}\n"
- else
- html << "#{assign_to(@variable)}\n"
- end
- html << @init_begin * "\n"
- html << @init * "\n"
- html << @init_end * "\n"
- html << "\n}\n"
- html << "});\n" if !no_load
- html << "</script>" if !no_script_tag
-
- if fullscreen
- #setting up the style in case of full screen
- html << "<style>html, body {width: 100%; height: 100%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px} ##{@container} {margin: 0px;} </style>"
- end
-
- html
- end
-
- #Outputs in JavaScript the creation of a GMap2 object
- def create
- "new GMap2(document.getElementById(\"#{@container}\"))"
- end
- end
- end
-end
-
+module Ym4r
+ module GmPlugin
+ #Representing the Google Maps API class GMap2.
+ class GMap
+ include MappingObject
+
+ #A constant containing the declaration of the VML namespace, necessary to display polylines under IE.
+ VML_NAMESPACE = "xmlns:v=\"urn:schemas-microsoft-com:vml\""
+
+ #The id of the DIV that will contain the map in the HTML page.
+ attr_reader :container
+
+ #By default the map in the HTML page will be globally accessible with the name +map+.
+ def initialize(container, variable = "map")
+ @container = container
+ @variable = variable
+ @init = []
+ @init_end = [] #for stuff that must be initialized at the end (controls)
+ @init_begin = [] #for stuff that must be initialized at the beginning (center + zoom)
+ @global_init = []
+ end
+
+ #Deprecated. Use the static version instead.
+ def header(with_vml = true)
+ GMap.header(:with_vml => with_vml)
+ end
+
+ #Outputs the header necessary to use the Google Maps API, by including the JS files of the API, as well as a file containing YM4R/GM helper functions. By default, it also outputs a style declaration for VML elements. This default can be overriddent by passing <tt>:with_vml => false</tt> as option to the method. You can also pass a <tt>:host</tt> option in order to select the correct API key for the location where your app is currently running, in case the current environment has multiple possible keys. Usually, in this case, you should pass it <tt>@request.host</tt>. If you have defined only one API key for the current environment, the <tt>:host</tt> option is ignored. Finally you can override all the key settings in the configuration by passing a value to the <tt>:key</tt> key. You can pass a language for the map type buttons with the <tt>:hl</tt> option (possible values are: Japanese (ja), French (fr), German (de), Italian (it), Spanish (es), Catalan (ca), Basque (eu) and Galician (gl): no values means english). Finally, you can pass <tt>:local_search => true</tt> to get the header css and js information needed for the local search control. If you do want local search you must also add <tt>:local_search => true</tt> to the @map.control_init method.
+ def self.header(options = {})
+ options[:with_vml] = true unless options.has_key?(:with_vml)
+ options[:hl] ||= ''
+ options[:local_search] = false unless options.has_key?(:local_search)
+ options[:sensor] = false unless options.has_key?(:sensor)
+ options[:version] ||= "2.x"
+ api_key = ApiKey.get(options)
+ a = "<script src=\"http://maps.google.com/maps?file=api&amp;v=#{options[:version]}&amp;key=#{api_key}&amp;hl=#{options[:hl]}&amp;sensor=#{options[:sensor]}\" type=\"text/javascript\"></script>\n"
+ a << "<script src=\"#{ActionController::Base.relative_url_root}/javascripts/ym4r-gm.js\" type=\"text/javascript\"></script>\n" unless options[:without_js]
+ a << "<!--[if IE]>\n<style type=\"text/css\">\n v\\:* { behavior:url(#default#VML);}\n</style>\n<![endif]-->\n" if options[:with_vml]
+ a << "<script src=\"http://www.google.com/uds/api?file=uds.js&amp;v=1.0\" type=\"text/javascript\"></script>" if options[:local_search]
+ a << "<script src=\"http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js\" type=\"text/javascript\"></script>\n" if options[:local_search]
+ a << "<style type=\"text/css\">@import url(\"http://www.google.com/uds/css/gsearch.css\");@import url(\"http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css\");}</style>" if options[:local_search]
+ a
+ end
+
+ #Outputs the <div id=...></div> which has been configured to contain the map. You can pass <tt>:width</tt> and <tt>:height</tt> as options to output this in the style attribute of the DIV element (you could also achieve the same effect by putting the dimension info into a CSS or using the instance method GMap#header_width_height). You can aslo pass <tt>:class</tt> to set the classname of the div.
+ # To include initial content in the div, such as a loading message, you
+ # may pass a <tt>:content</tt> option specifying a string, or other
+ # object, such as a REXML fragment, that responds to #to_s.
+ def div(options = {})
+ attributes = "id=\"#{@container}\" "
+ if options.has_key?(:height) && options.has_key?(:width)
+ width = options.delete(:width)
+ if width.is_a?(Integer) or width =~ /^[0-9]+$/
+ width = width.to_s + "px"
+ end
+ height = options.delete(:height)
+ if height.is_a?(Integer) or height =~ /^[0-9]+$/
+ height = height.to_s + "px"
+ end
+ attributes += "style=\"width:#{width};height:#{height}\" "
+ end
+ if options.has_key?(:class)
+ attributes += options.keys.map {|opt| "#{opt}=\"#{options[opt]}\"" }.join(" ")
+ end
+ "<div #{attributes}>#{options[:content].to_s}</div>"
+ end
+
+ #Outputs a style declaration setting the dimensions of the DIV container of the map. This info can also be set manually in a CSS.
+ def header_width_height(width,height)
+ "<style type=\"text/css\">\n##{@container} { height: #{height}px;\n width: #{width}px;\n}\n</style>"
+ end
+
+ #Records arbitrary JavaScript code and outputs it during initialization inside the +load+ function.
+ def record_init(code)
+ @init << code
+ end
+
+ #Initializes the controls: you can pass a hash with keys <tt>:small_map</tt>, <tt>:large_map</tt>, <tt>:small_zoom</tt>, <tt>:scale</tt>, <tt>:map_type</tt>, <tt>:overview_map</tt> and hash of options controlling its display (<tt>:hide</tt> and <tt>:size</tt>), <tt>:local_search</tt>, <tt>:local_search_options</tt>, and <tt>:show_on_focus</tt>
+ def control_init(controls = {})
+ @init_end << add_control(GSmallMapControl.new) if controls[:small_map]
+ @init_end << add_control(GLargeMapControl.new) if controls[:large_map]
+ @init_end << add_control(GSmallZoomControl.new) if controls[:small_zoom]
+ @init_end << add_control(GScaleControl.new) if controls[:scale]
+ @init_end << add_control(GMapTypeControl.new) if controls[:map_type]
+ @init_end << add_control(GHierarchicalMapTypeControl.new) if controls[:hierarchical_map_type]
+ if controls[:overview_map]
+ if controls[:overview_map].is_a?(Hash)
+ hide = controls[:overview_map][:hide]
+ size = controls[:overview_map][:size]
+ end
+ overview_control = GOverviewMapControl.new(size)
+ @global_init << overview_control.declare("#{@variable}_ovm") if hide
+ @init_end << add_control(overview_control)
+ @init_end << "#{overview_control.variable}.hide(true);" if hide
+ end
+ @init_end << add_control(GLocalSearchControl.new(controls[:anchor], controls[:offset_width], controls[:offset_height], controls[:local_search_options])) if controls[:local_search]
+ if controls[:show_on_focus] # Should be last
+ @init_end << "#{@variable}.hideControls();"
+ event_init(self, :mouseover, "function(){#{@variable}.showControls();}")
+ event_init(self, :mouseout, "function(){#{@variable}.hideControls();}")
+ end
+ end
+
+ #Initializes the interface configuration: double-click zoom, dragging, continuous zoom,... You can pass a hash with keys <tt>:dragging</tt>, <tt>:info_window</tt>, <tt>:double_click_zoom</tt>, <tt>:continuous_zoom</tt> and <tt>:scroll_wheel_zoom</tt>. The values should be true or false. Check the google maps API doc to know what the default values are.
+ def interface_init(interface = {})
+ if !interface[:dragging].nil?
+ if interface[:dragging]
+ @init << enableDragging()
+ else
+ @init << disableDragging()
+ end
+ end
+ if !interface[:info_window].nil?
+ if interface[:info_window]
+ @init << enableInfoWindow()
+ else
+ @init << disableInfoWindow()
+ end
+ end
+ if !interface[:double_click_zoom].nil?
+ if interface[:double_click_zoom]
+ @init << enableDoubleClickZoom()
+ else
+ @init << disableDoubleClickZoom()
+ end
+ end
+ if !interface[:continuous_zoom].nil?
+ if interface[:continuous_zoom]
+ @init << enableContinuousZoom()
+ else
+ @init << disableContinuousZoom()
+ end
+ end
+ if !interface[:scroll_wheel_zoom].nil?
+ if interface[:scroll_wheel_zoom]
+ @init << enableScrollWheelZoom()
+ else
+ @init << disableScrollWheelZoom()
+ end
+ end
+ end
+
+ #Initializes the initial center and zoom of the map. +center+ can be both a GLatLng object or a 2-float array.
+ def center_zoom_init(center, zoom)
+ if center.is_a?(GLatLng)
+ @init_begin << set_center(center,zoom)
+ else
+ @init_begin << set_center(GLatLng.new(center),zoom)
+ end
+ end
+
+ #Center and zoom based on the coordinates passed as argument (either 2D arrays or GLatLng objects)
+ def center_zoom_on_points_init(*points)
+ if(points.length > 0)
+ if(points[0].is_a?(Array))
+ points = points.collect { |point| GLatLng.new(point) }
+ end
+ @init_begin << center_and_zoom_on_points(points)
+ end
+ end
+
+ #Center and zoom based on the bbox corners. Pass a GLatLngBounds object, an array of 2D coordinates (sw and ne) or an array of GLatLng objects (sw and ne).
+ def center_zoom_on_bounds_init(latlngbounds)
+ if(latlngbounds.is_a?(Array))
+ if latlngbounds[0].is_a?(Array)
+ latlngbounds = GLatLngBounds.new(GLatLng.new(latlngbounds[0]),GLatLng.new(latlngbounds[1]))
+ elsif latlngbounds[0].is_a?(GLatLng)
+ latlngbounds = GLatLngBounds.new(*latlngbounds)
+ end
+ end
+ #else it is already a latlngbounds object
+
+ @init_begin << center_and_zoom_on_bounds(latlngbounds)
+ end
+
+ #Initializes the map by adding an overlay (marker or polyline).
+ def overlay_init(overlay)
+ @init << add_overlay(overlay)
+ end
+
+ #Sets up a new map type. If +add+ is false, all the other map types of the map are wiped out. If you want to access the map type in other methods, you should declare the map type first (with +declare_init+).
+ def add_map_type_init(map_type, add = true)
+ unless add
+ @init << get_map_types.set_property(:length,0)
+ end
+ @init << add_map_type(map_type)
+ end
+ #for legacy purpose
+ alias :map_type_init :add_map_type_init
+
+ #Sets the map type displayed by default after the map is loaded. It should be known from the map (ie either the default map types or a user-defined map type added with <tt>add_map_type_init</tt>). Use <tt>set_map_type_init(GMapType::G_SATELLITE_MAP)</tt> or <tt>set_map_type_init(GMapType::G_HYBRID_MAP)</tt> to initialize the map with repsecitvely the Satellite view and the hybrid view.
+ def set_map_type_init(map_type)
+ @init << set_map_type(map_type)
+ end
+
+ #Locally declare a MappingObject with variable name "name"
+ def declare_init(variable, name)
+ @init << variable.declare(name)
+ end
+
+ #Records arbitrary JavaScript code and outputs it during initialization outside the +load+ function (ie globally).
+ def record_global_init(code)
+ @global_init << code
+ end
+
+ #Deprecated. Use icon_global_init instead.
+ def icon_init(icon , name)
+ icon_global_init(icon , name)
+ end
+
+ #Initializes an icon and makes it globally accessible through the JavaScript variable of name +variable+.
+ def icon_global_init(icon , name, options = {})
+ declare_global_init(icon,name,options)
+ end
+
+ #Registers an event
+ def event_init(object,event,callback)
+ @init << "GEvent.addListener(#{object.to_javascript},\"#{MappingObject.javascriptify_method(event.to_s)}\",#{callback});"
+ end
+
+ #Registers an event globally
+ def event_global_init(object,event,callback)
+ @global_init << "GEvent.addListener(#{object.to_javascript},\"#{MappingObject.javascriptify_method(event.to_s)}\",#{callback});"
+ end
+
+ #Declares the overlay globally with name +name+
+ def overlay_global_init(overlay,name, options = {})
+ declare_global_init(overlay,name, options)
+ @init << add_overlay(overlay)
+ end
+
+ #Globally declare a MappingObject with variable name "name". Option <tt>:local_construction</tt> should be passed if the construction has to be done inside the onload callback method (for exsample if it depends on the GMap to be initialized)
+ def declare_global_init(variable,name, options = {})
+ unless options[:local_construction]
+ @global_init << "var #{variable.assign_to(name)}"
+ else
+ @global_init << "var #{name};"
+ @init << variable.assign_to(name)
+ end
+ end
+
+ #Outputs the initialization code for the map. By default, it outputs the script tags, performs the initialization in response to the onload event of the window and makes the map globally available. If you pass +true+ to the option key <tt>:full</tt>, the map will be setup in full screen, in which case it is not necessary (but not harmful) to set a size for the map div.
+ def to_html(options = {})
+ no_load = options[:no_load]
+ no_script_tag = options[:no_script_tag]
+ no_declare = options[:no_declare]
+ no_global = options[:no_global]
+ fullscreen = options[:full]
+ load_pr = options[:proto_load] #to prevent some problems when the onload event callback from Prototype is used
+
+ html = ""
+ html << "<script type=\"text/javascript\">\n" if !no_script_tag
+ #put the functions in a separate javascript file to be included in the page
+ html << @global_init * "\n"
+ html << "var #{@variable};\n" if !no_declare and !no_global
+ if !no_load
+ if load_pr
+ html << "Event.observe(window,'load',"
+ else
+ html << "window.onload = addCodeToFunction(window.onload,"
+ end
+ html << "function() {\n"
+ end
+
+ html << "if (GBrowserIsCompatible()) {\n"
+
+ if fullscreen
+ #Adding the initial resizing and setting up the event handler for
+ #future resizes
+ html << "setWindowDims(document.getElementById('#{@container}'));\n"
+ html << "if (window.attachEvent) { window.attachEvent(\"onresize\", function() {setWindowDims(document.getElementById('#{@container}'));})} else {window.addEventListener(\"resize\", function() {setWindowDims(document.getElementById('#{@container}')); } , false);}\n"
+ end
+
+ if !no_declare and no_global
+ html << "#{declare(@variable)}\n"
+ else
+ html << "#{assign_to(@variable)}\n"
+ end
+ html << @init_begin * "\n"
+ html << @init * "\n"
+ html << @init_end * "\n"
+ html << "\n}\n"
+ html << "});\n" if !no_load
+ html << "</script>" if !no_script_tag
+
+ if fullscreen
+ #setting up the style in case of full screen
+ html << "<style>html, body {width: 100%; height: 100%} body {margin-top: 0px; margin-right: 0px; margin-left: 0px; margin-bottom: 0px} ##{@container} {margin: 0px;} </style>"
+ end
+
+ html
+ end
+
+ #Outputs in JavaScript the creation of a GMap2 object
+ def create
+ "new GMap2(document.getElementById(\"#{@container}\"))"
+ end
+ end
+ end
+end
+
View
256 lib/gm_plugin/mapping.rb
@@ -1,128 +1,128 @@
-module Ym4r
- module GmPlugin
- #The module where all the Ruby-to-JavaScript conversion takes place. It is included by all the classes in the YM4R library.
- module MappingObject
- #The name of the variable in JavaScript space.
- attr_reader :variable
-
- #Creates javascript code for missing methods + takes care of listeners
- def method_missing(name,*args)
- str_name = name.to_s
- if str_name =~ /^on_(.*)/
- if args.length != 1
- raise ArgumentError("Only 1 argument is allowed on on_ methods");
- else
- Variable.new("GEvent.addListener(#{to_javascript},\"#{MappingObject.javascriptify_method($1)}\",#{args[0]})")
- end
- else
- args.collect! do |arg|
- MappingObject.javascriptify_variable(arg)
- end
- Variable.new("#{to_javascript}.#{MappingObject.javascriptify_method(str_name)}(#{args.join(",")})")
- end
- end
-
- #Creates javascript code for array or hash indexing
- def [](index) #index could be an integer or string
- return Variable.new("#{to_javascript}[#{MappingObject.javascriptify_variable(index)}]")
- end
-
- #Transforms a Ruby object into a JavaScript string : MAppingObject, String, Array, Hash and general case (using to_s)
- def self.javascriptify_variable(arg)
- if arg.is_a?(MappingObject)
- arg.to_javascript
- elsif arg.is_a?(String)
- "\"#{MappingObject.escape_javascript(arg)}\""
- elsif arg.is_a?(Array)
- "[" + arg.collect{ |a| MappingObject.javascriptify_variable(a)}.join(",") + "]"
- elsif arg.is_a?(Hash)
- "{" + arg.to_a.collect do |v|
- "#{MappingObject.javascriptify_method(v[0].to_s)} : #{MappingObject.javascriptify_variable(v[1])}"
- end.join(",") + "}"
- elsif arg.nil?
- "undefined"
- else
- arg.to_s
- end
- end
-
- #Escape string to be used in JavaScript. Lifted from rails.
- def self.escape_javascript(javascript)
- javascript.gsub(/\r\n|\n|\r/, "\\n").gsub("\"") { |m| "\\#{m}" }
- end
-
- #Transform a ruby-type method name (like add_overlay) to a JavaScript-style one (like addOverlay).
- def self.javascriptify_method(method_name)
- method_name.gsub(/_(\w)/){|s| $1.upcase}
- end
-
- #Declares a Mapping Object bound to a JavaScript variable of name +variable+.
- def declare(variable)
- @variable = variable
- "var #{@variable} = #{create};"
- end
-
- #declare with a random variable name
- def declare_random(init,size = 8)
- s = init.clone
- 6.times { s << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }
- declare(s)
- end
-
- #Checks if the MappinObject has been declared
- def declared?
- !@variable.nil?
- end
-
- #Binds a Mapping object to a previously declared JavaScript variable of name +variable+.
- def assign_to(variable)
- @variable = variable
- "#{@variable} = #{create};"
- end
-
- #Assign the +value+ to the +property+ of the MappingObject
- def set_property(property, value)
- "#{to_javascript}.#{MappingObject.javascriptify_method(property.to_s)} = #{MappingObject.javascriptify_variable(value)}"
- end
-
- #Returns the code to get a +property+ from the MappingObject
- def get_property(property)
- Variable.new("#{to_javascript}.#{MappingObject.javascriptify_method(property.to_s)}")
- end
-
- #Returns a Javascript code representing the object
- def to_javascript
- unless @variable.nil?
- @variable
- else
- create
- end
- end
-
- #Creates a Mapping Object in JavaScript.
- #To be implemented by subclasses if needed
- def create
- end
- end
-
- #Used to bind a ruby variable to an already existing JavaScript one. It doesn't have to be a variable in the sense "var variable" but it can be any valid JavaScript expression that has a value.
- class Variable
- include MappingObject
-
- def initialize(variable)
- @variable = variable
- end
- #Returns the javascript expression contained in the object.
- def create
- @variable
- end
- #Returns the expression inside the Variable followed by a ";"
- def to_s
- @variable + ";"
- end
-
- UNDEFINED = Variable.new("undefined")
- end
- end
-end
-
+module Ym4r
+ module GmPlugin
+ #The module where all the Ruby-to-JavaScript conversion takes place. It is included by all the classes in the YM4R library.
+ module MappingObject
+ #The name of the variable in JavaScript space.
+ attr_reader :variable
+
+ #Creates javascript code for missing methods + takes care of listeners
+ def method_missing(name,*args)
+ str_name = name.to_s
+ if str_name =~ /^on_(.*)/
+ if args.length != 1
+ raise ArgumentError("Only 1 argument is allowed on on_ methods");
+ else
+ Variable.new("GEvent.addListener(#{to_javascript},\"#{MappingObject.javascriptify_method($1)}\",#{args[0]})")
+ end
+ else
+ args.collect! do |arg|
+ MappingObject.javascriptify_variable(arg)
+ end
+ Variable.new("#{to_javascript}.#{MappingObject.javascriptify_method(str_name)}(#{args.join(",")})")
+ end
+ end
+
+ #Creates javascript code for array or hash indexing
+ def [](index) #index could be an integer or string
+ return Variable.new("#{to_javascript}[#{MappingObject.javascriptify_variable(index)}]")
+ end
+
+ #Transforms a Ruby object into a JavaScript string : MAppingObject, String, Array, Hash and general case (using to_s)
+ def self.javascriptify_variable(arg)
+ if arg.is_a?(MappingObject)
+ arg.to_javascript
+ elsif arg.is_a?(String)
+ "\"#{MappingObject.escape_javascript(arg)}\""
+ elsif arg.is_a?(Array)
+ "[" + arg.collect{ |a| MappingObject.javascriptify_variable(a)}.join(",") + "]"
+ elsif arg.is_a?(Hash)
+ "{" + arg.to_a.collect do |v|
+ "#{MappingObject.javascriptify_method(v[0].to_s