1 /* Copyright (c) 2009 Arnaud Renevier, Inc, published under the modified BSD
4 // drag feature with tolerance
5 OpenLayers.Control.SypDragFeature = OpenLayers.Class (OpenLayers.Control.DragFeature, {
11 downFeature: function(pixel) {
12 OpenLayers.Control.DragFeature.prototype.downFeature.apply(this, arguments);
13 this.dragStart = (new Date()).getTime();
14 this.startPixel = pixel;
17 doneDragging: function(pixel) {
18 OpenLayers.Control.DragFeature.prototype.doneDragging.apply(this, arguments);
20 var passesTimeTolerance =
21 (new Date()).getTime() > this.dragStart + this.timeTolerance;
23 var xDiff = this.startPixel.x - pixel.x;
24 var yDiff = this.startPixel.y - pixel.y;
26 var passesPixelTolerance =
27 Math.sqrt(Math.pow(xDiff,2) + Math.pow(yDiff,2)) > this.pixelTolerance;
29 if(passesTimeTolerance && passesPixelTolerance){
30 this.onComplete(this.feature, pixel);
32 var feature = this.feature;
33 var res = this.map.getResolution();
34 this.feature.geometry.move(res * (this.startPixel.x - this.lastPixel.x),
35 res * (this.lastPixel.y - this.startPixel.y));
36 this.layer.drawFeature(this.feature);
38 this.layer.drawFeature(this.feature, "select");
41 moveFeature: function(pixel) {
42 OpenLayers.Control.DragFeature.prototype.moveFeature.apply(this, arguments);
43 this.layer.drawFeature(this.feature, "temporary");
46 overFeature: function (feature) {
47 // can only drag and drop currently selected feature
48 if (feature != Admin.currentFeature) {
51 OpenLayers.Control.DragFeature.prototype.overFeature.apply(this, arguments);
54 CLASS_NAME: "OpenLayers.Control.SypDragFeature"
59 ICON: "media/marker-normal.png",
60 SELECT_ICON: "media/marker-selected.png",
61 TEMPORARY_ICON: "media/marker-temp.png",
68 selFeatureControl: null,
69 moveFeatureControl: null,
70 addFeatureControl: null,
73 currentFeatureLocation: null,
76 this.map = new OpenLayers.Map ("map", {
78 new OpenLayers.Control.Navigation (),
79 new OpenLayers.Control.PanZoom ()
81 projection: new OpenLayers.Projection("EPSG:900913"),
82 displayProjection: new OpenLayers.Projection("EPSG:4326")
85 this.baseLayer = this.createBaseLayer ();
86 this.map.addLayer(this.baseLayer);
88 this.map.setCenter(new OpenLayers.LonLat(0, 0), 0);
89 if (sypSettings.loggedUser) {
90 this.dataLayer = this.createDataLayer (sypSettings.loggedUser);
91 this.map.addLayer(this.dataLayer);
97 this.addFeatureControl.deactivate();
98 this.moveFeatureControl.deactivate();
99 this.selFeatureControl.activate();
100 this.checkForFeatures();
101 $("#newfeature_button").show().val(SypStrings.AddItem);
102 $("#newfeature_button").unbind("click").click(function () {
103 Admin.addNewFeature();
107 createBaseLayer: function () {
108 return new OpenLayers.Layer.OSM("OSM");
111 createDataLayer: function (user) {
112 var styleMap = new OpenLayers.StyleMap (
114 externalGraphic: this.Markers.ICON,
115 graphicHeight: this.Markers.HEIGHT || 32
118 externalGraphic: this.Markers.TEMPORARY_ICON,
119 graphicHeight: this.Markers.HEIGHT || 32
122 externalGraphic: this.Markers.SELECT_ICON,
123 graphicHeight: this.Markers.HEIGHT || 32
126 var layer = new OpenLayers.Layer.GML("KML", "items.php?from_user=" + encodeURIComponent(user),
129 format: OpenLayers.Format.KML,
130 projection: this.map.displayProjection,
131 eventListeners: { scope: this,
132 loadend: this.dataLayerEndLoad
137 this.selFeatureControl = this.createSelectFeatureControl(layer)
138 this.map.addControl(this.selFeatureControl);
139 this.moveFeatureControl = this.createMoveFeatureControl(layer)
140 this.map.addControl(this.moveFeatureControl);
141 this.addFeatureControl = this.createNewfeatureControl();
142 this.map.addControl(this.addFeatureControl);
147 createMoveFeatureControl: function (layer) {
148 var control = new OpenLayers.Control.SypDragFeature(
154 createSelectFeatureControl: function (layer) {
155 var control = new OpenLayers.Control.SelectFeature(
157 onSelect: OpenLayers.Function.bind(this.onFeatureSelect, this)
162 createNewfeatureControl: function () {
163 var control = new OpenLayers.Control ();
164 var handler = new OpenLayers.Handler.Click(control, {
165 'click': OpenLayers.Function.bind(FeatureMgr.add, FeatureMgr)
167 control.handler = handler;
171 onFeatureSelect: function (feature) {
172 this.showEditor(feature);
174 this.selFeatureControl.deactivate();
175 this.moveFeatureControl.activate();
178 closeEditor: function() {
179 if ($("#editor").css("display") == "none") {
182 if (this.currentFeature && this.currentFeature.layer) {
183 this.selFeatureControl.unselect(this.currentFeature);
185 this.currentFeature = null;
186 this.currentFeatureLocation = null;
187 $("#img").removeAttr('src');
188 $("#img").parent().html($("#img").parent().html());
189 $("#img").parent().show();
190 $("#title, #description").val("");
192 // do it once before hidding and once after hidding to work in all cases
193 $("#title, #description").val("");
194 $("#image_file").parent().html($("#image_file").parent().html());
195 $(document).unbind("keydown");
196 this.checkForFeatures();
200 showEditor: function (feature) {
201 $("#newfeature_button").hide();
202 userMgr.closeAddUser();
209 $(document).unbind("keydown").keydown(function(e) {
210 if (e.keyCode == 27) {
211 Admin.cancelCurrentFeature()
215 this.currentFeature = feature;
216 this.currentFeatureLocation = new OpenLayers.Pixel(feature.geometry.x, feature.geometry.y);
218 $("#instructions").text(SypStrings.DragDropHowto);
219 $("#title").val(feature.attributes.name);
220 var fullDesc = $(feature.attributes.description).parent();
221 $("#description").val(fullDesc.find('p').text());
222 var src = fullDesc.find('img').attr('src');
224 $("#img").parent().show();
225 $("#img").attr('src', src);
226 $("#image_file").parent().hide();
227 $("#image_delete").show();
229 $("#img").parent().hide();
230 $("#image_file").parent().show();
231 $("#image_delete").hide();
233 $("#title").select().focus();
236 dataLayerEndLoad: function() {
237 // only set zoom extent once
238 this.dataLayer.events.unregister('loadend', this, this.dataLayerEndLoad);
239 this.dataLayer.events.register('loadend', this, this.checkForFeatures);
241 if (!this.checkForFeatures()) {
246 var orig = this.Utils.mbr (this.dataLayer);
247 var centerBounds = new OpenLayers.Bounds();
249 var mapProj = map.getProjectionObject();
250 var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
252 var bottomLeft = new OpenLayers.LonLat(orig[0],orig[1]);
253 bottomLeft = bottomLeft.transform(sypOrigProj, mapProj);
254 var topRight = new OpenLayers.LonLat(orig[2],orig[3])
255 topRight = topRight.transform(sypOrigProj, mapProj);
257 centerBounds.extend(bottomLeft);
258 centerBounds.extend(topRight);
259 map.zoomToExtent(centerBounds);
262 checkForFeatures: function () {
263 var features = this.dataLayer.features;
264 if (features.length != 0) {
265 $("#instructions").text(SypStrings.SelectHowto);
267 return !!features.length;
270 addNewFeature: function () {
271 userMgr.closeAddUser();
274 $(document).unbind("keydown");
277 $(document).unbind("keydown").keydown(function(e) {
278 if (e.keyCode == 27) {
284 $("#newfeature_button").val("annuler");
285 $("#newfeature_button").unbind("click").click(cancel);
287 $("#instructions").text(SypStrings.AddHowto);
288 this.selFeatureControl.deactivate();
289 this.addFeatureControl.activate();
293 cancelCurrentFeature: function() {
294 if (AjaxMgr.running) {
297 var feature = this.currentFeature;
300 FeatureMgr.move (feature, this.currentFeatureLocation);
302 this.dataLayer.removeFeatures([feature]);
309 reloadLayer: function (layer) {
310 layer.destroyFeatures();
311 layer.loaded = false;
316 /* minimum bounds rectangle containing all feature locations.
317 * FIXME: if two features are close, but separated by 180th meridian,
318 * their mbr will span the whole earth. Actually, 179° lon and -170°
319 * lon are considerated very near.
321 mbr: function (layer) {
325 var mapProj = map.getProjectionObject();
326 var sypOrigProj = new OpenLayers.Projection("EPSG:4326");
328 for (var i =0; i < layer.features.length; i++) {
329 if (layer.features[i].cluster) {
330 features = features.concat(layer.features[i].cluster);
332 features = features.concat(layer.features);
341 if (features.length == 0) {
342 // keep default values
343 } else if (features.length == 1) {
344 // in case there's only one feature, we show an area of at least
346 var pos = features[0].geometry.getBounds().getCenterLonLat().clone();
347 var lonlat = pos.transform(mapProj, sypOrigProj);
349 minlon = Math.max (lonlat.lon - 2, -180);
350 maxlon = Math.min (lonlat.lon + 2, 180);
351 minlat = Math.max (lonlat.lat - 2, -90);
352 maxlat = Math.min (lonlat.lat + 2, 90);
354 for (var i = 0; i < features.length; i++) {
355 var pos = features[i].geometry.getBounds().getCenterLonLat().clone();
356 var lonlat = pos.transform(mapProj, sypOrigProj);
357 minlon = Math.min (lonlat.lon, minlon);
358 minlat = Math.min (lonlat.lat, minlat);
359 maxlon = Math.max (lonlat.lon, maxlon);
360 maxlat = Math.max (lonlat.lat, maxlat);
364 return [minlon, minlat, maxlon, maxlat];
369 escapeHTML: function (str) {
374 replace(/&/gm, '&').
375 replace(/'/gm, ''').
376 replace(/"/gm, '"').
377 replace(/>/gm, '>').
378 replace(/</gm, '<');
381 startsWith: function (str, prefix) {
382 return (str.slice(0, prefix.length) == prefix);
385 indexOf: function (array, item) {
386 if (array.indexOf !== undefined) {
387 return array.indexOf(item);
389 return OpenLayers.Util.indexOf(array, item);
402 var pos = map.getLonLatFromViewPortPx(evt.xy);
403 feature = this.update (null, pos, "", "", "");
404 Admin.addFeatureControl.deactivate();
405 Admin.selFeatureControl.select(feature);
408 move: function (feature, aLocation) {
409 if (!feature || !aLocation) {
412 var curLoc = feature.geometry;
413 feature.geometry.move(aLocation.x - curLoc.x, aLocation.y - curLoc.y);
414 feature.layer.drawFeature(feature);
417 update: function(feature, lonlat, imgurl, title, description) {
418 var point = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat);
420 feature = new OpenLayers.Feature.Vector(point);
421 Admin.dataLayer.addFeatures([feature]);
423 this.move (feature, point);
425 feature.attributes.name = title;
426 feature.attributes.description = "<p>" + Admin.Utils.escapeHTML(description) + "</p>"
427 + "<img src=\"" + imgurl + "\">"
431 del: function (feature) {
432 var form = $("#feature_delete");
433 form.find('input[name="fid"]').val(feature.fid);
436 oncomplete: OpenLayers.Function.bind(this.ajaxReply, this),
437 onsend: function() { $("#editor_throbber").css("visibility", "visible"); }
441 save: function (feature) {
442 var x = feature.geometry.x;
443 var y = feature.geometry.y;
445 var mapProj = feature.layer.map.getProjectionObject();
446 var lonlat = new OpenLayers.LonLat(x, y).
448 new OpenLayers.Projection("EPSG:4326"));
449 var form = $("#feature_update");
450 form.find('input[name="lon"]').val(lonlat.lon);
451 form.find('input[name="lat"]').val(lonlat.lat);
452 form.find('input[name="fid"]').val(feature.fid);
453 form.find('input[name="keep_img"]').val(
454 $("#img").attr("src") ? "yes": "no"
458 form.find('input[name="request"]').val("update");
460 form.find('input[name="request"]').val("add");
464 oncomplete: OpenLayers.Function.bind(this.ajaxReply, this),
465 onsend: function() { $("#editor_throbber").css("visibility", "visible"); }
469 ajaxReply: function (data) {
470 $("#editor_throbber").css("visibility", "hidden");
472 this.commError(SypStrings.ServerError);
476 var xml = new OpenLayers.Format.XML().read(data);
478 switch (xml.documentElement.nodeName.toLowerCase()) {
480 switch (xml.documentElement.getAttribute("reason")) {
483 $("#cookie_warning").show();
485 Admin.cancelCurrentFeature();
490 this.commError(SypStrings.ServerError);
494 this.commError(SypStrings.UnreferencedError);
495 Admin.reloadLayer(Admin.dataLayer);
499 this.commError(SypStrings.NochangeError);
503 this.commError(SypStrings.RequestError);
507 this.commError(SypStrings.ToobigError);
508 $("#image_file").parent().html($("#image_file").parent().html());
509 $("#image_file").focus();
512 this.commError(SypStrings.NotimageError);
513 $("#image_file").parent().html($("#image_file").parent().html());
514 $("#image_file").focus();
517 this.commError(SypStrings.UnconsistentError);
523 switch (xml.documentElement.getAttribute("request")) {
525 this.commSuccess(SypStrings.DelSucces);
526 var someFeature = false;
528 $.each($(xml).find("FEATURE,feature"), function () {
530 var id = parseFloat($(this).find("ID:first,id:first").text());
531 if ((id === null) || isNaN (id)) {
534 var features = Admin.dataLayer.features;
535 for (var idx = 0; idx < features.length; idx++) {
536 if (features[idx].fid == id) {
537 Admin.dataLayer.removeFeatures([features[idx]]);
541 if (someFeature == false) {
542 this.commError(SypStrings.UnconsistentError);
549 var someFeature = false;
551 $.each($(xml).find("FEATURE,feature"), function () {
553 var id = parseFloat($(this).find("ID:first,id:first").text());
554 if ((id === null) || isNaN (id)) {
558 var lon = parseFloat($(this).find("LON:first,lon:first").text());
559 if ((typeof (lon) != "number") || isNaN (lon) ||
560 (lon < -180) || (lon > 180)) {
564 var lat = parseFloat($(this).find("LAT:first,lat:first").text());
565 if ((typeof (lat) != "number") || isNaN (lat) ||
566 (lat < -90) || (lat > 90)) {
570 var mapProj = Admin.map.getProjectionObject();
571 var lonlat = new OpenLayers.LonLat (lon, lat).
572 transform( new OpenLayers.Projection("EPSG:4326"), mapProj);
574 var imgurl = $(this).find("IMGURL:first,imgurl:first").text();
575 var title = $(this).find("HEADING:first,heading:first").text();
576 var description = $(this).find("DESCRIPTION:first,description:first").text();
578 feature = self.update (Admin.currentFeature, lonlat, imgurl, title, description);
582 if (someFeature == false) {
583 this.commError(SypStrings.UnconsistentError);
585 this.commSuccess(SypStrings.UpdateSucces);
591 this.commError(SypStrings.UnconsistentError);
596 this.commError(SypStrings.UnconsistentError);
601 commSuccess: function (message) {
602 $("#server_comm").text(message);
603 $("#server_comm").removeClass("error success").addClass("success");
606 commError: function (message) {
607 $("#server_comm").text(message);
608 $("#server_comm").removeClass("error success").addClass("error");
612 /* maintains a queue of ajax queries, so I'm sure they all execute in the same
613 * order they were defined */
619 add: function(query) {
620 this._queue.push(query);
621 if (this._queue.length > 1) {
624 this._runQuery(query);
628 _runQuery: function(query) {
630 $('#api_frame').one("load", function() {
631 self.running = false;
633 if (typeof (query.oncomplete) == "function") {
636 if (this.contentDocument) {
637 body = this.contentDocument.body;
638 } else if (this.contentWindow) {
639 body = this.contentWindow.document.body;
641 body = document.frames[this.id].document.body;
645 query.oncomplete(body.innerHTML);
647 query.oncomplete(null);
651 query.form.attr("action", "api.php");
652 query.form.attr("target", "api_frame");
653 query.form.attr("method", "post");
655 query.form.get(0).submit();
656 if (typeof (query.onsend) == "function") {
661 _reqEnd: function() {
663 if (this._queue.length > 0) {
664 this._reqEnd(this._queue[0]);
672 $("#login_form").submit(this.submit);
673 $("#user").focus().select();
678 $("#login_area").show();
679 $("#password").val("");
680 $("#user").val(sypSettings.loggedUser).focus().select();
683 submit: function () {
685 pwdMgr.commError("");
687 form: $("#login_form"),
689 $("#pwd_throbber").css("visibility", "visible");
690 $("#login_error").hide();
692 // we need a timeout; otherwise those fields will not be submitted
693 window.setTimeout(function() {
694 // removes focus from #password before disabling it. Otherwise, opera
695 // prevents re-focusing it after re-enabling it.
696 $("#user, #password").blur();
697 $("#login_submit, #user, #password").attr("disabled", "disabled");
700 oncomplete: OpenLayers.Function.bind(pwdMgr.ajaxReply, pwdMgr)
707 ajaxReply: function (data) {
708 $("#pwd_throbber").css("visibility", "hidden");
709 // here, we need a timeout because onsend timeout sometimes has not been triggered yet
710 window.setTimeout(function() {
711 $("#login_submit, #user, #password").removeAttr("disabled");
715 this.commError(SypStrings.ServerError);
716 $("#login_error").show();
717 window.setTimeout(function() {
718 $("#user").focus().select();
722 var xml = new OpenLayers.Format.XML().read(data);
724 switch (xml.documentElement.nodeName.toLowerCase()) {
726 switch (xml.documentElement.getAttribute("reason")) {
728 this.commError(SypStrings.ServerError);
731 this.commError(SypStrings.UnauthorizedError);
734 this.commError(SypStrings.RequestError);
737 this.commError(SypStrings.UnconsistentError);
740 $("#login_error").show();
741 window.setTimeout(function() {
742 $("#user").focus().select();
746 $("#login_area").hide();
748 user = $(xml).find("USER,user").text();
749 sypSettings.loggedUser = user;
751 if (sypSettings.loggedUser == "admin") {
755 if (Admin.selFeatureControl) {
756 Admin.selFeatureControl.destroy();
758 if (Admin.moveFeatureControl) {
759 Admin.moveFeatureControl.destroy();
761 if (Admin.addFeatureControl) {
762 Admin.addFeatureControl.destroy();
764 if (Admin.dataLayer) {
765 Admin.dataLayer.destroy();
768 Admin.dataLayer = Admin.createDataLayer(user);
769 Admin.map.addLayer(Admin.dataLayer);
774 this.commError(SypStrings.UnconsistentError);
779 commError: function (message) {
780 $("#login_error").text(message);
782 $("#login_error").show();
784 $("#login_error").hide();
790 _adduserDisplayed: false,
791 _deluserDisplayed: false,
794 if (sypSettings.loggedUser != "admin") {
798 $("#add_user").show();
800 $("#add_user").click(function () {
801 userMgr.toggleAddUser();
804 $("#newuser_close").click(function () {
805 userMgr.closeAddUser()
807 $("#newuser").submit(function() {
816 if (this._adduserDisplayed) {
819 $("#add_user").unbind("click");
820 $("#add_user").hide();
821 $("#newuser_close").unbind("click");
822 $("#newuser").unbind("submit");
825 toggleAddUser: function() {
826 if (this._adduserDisplayed) {
833 showAddUser: function() {
834 if (!Admin.cancelCurrentFeature()) {
838 $(document).unbind("keydown").keydown(function(e) {
839 if (e.keyCode == 27) {
840 userMgr.closeAddUser()
846 $("#newuser_area").show();
847 $("#newuser_name, #newuser_password, #newuser_password_confirm").val("");
848 $("#newuser_name, #newuser_password, #newuser_password_confirm, #newuser_submit").removeAttr('disabled');
849 $("#newuser_name").focus();;
852 this._adduserDisplayed = true;
855 closeAddUser: function() {
856 $("#newuser_area").hide();
857 $(document).unbind("keydown");
858 this._adduserDisplayed = false;
862 var newuser_name = $("#newuser_name").val();
864 this.commError(SypStrings.newUserNonameError);
865 $("#newuser_name").focus();
869 var newuser_pass = $("#newuser_password").val();
870 var newuser_pass_confirm = $("#newuser_password_confirm").val();
871 if (newuser_pass != newuser_pass_confirm) {
872 this.commError(SypStrings.newUserPasswordmatchError);
873 $("#newuser_password").focus().select();
881 oncomplete: OpenLayers.Function.bind(this.ajaxReply, this),
882 onsend: function() { $("#newuser_throbber").css("visibility", "visible"); }
886 ajaxReply: function (data) {
887 $("#newuser_throbber").css("visibility", "hidden");
889 this.commError(SypStrings.ServerError);
893 var xml = new OpenLayers.Format.XML().read(data);
894 switch (xml.documentElement.nodeName.toLowerCase()) {
896 switch (xml.documentElement.getAttribute("reason")) {
899 $("#cookie_warning").show();
904 this.commError(SypStrings.ServerError);
905 $("#newuser_name").focus().select();
908 this.commError(SypStrings.RequestError);
909 $("#newuser_name").focus().select();
911 case "newuser_exists":
912 this.commError(SypStrings.newUserExistsError);
913 $("#newuser_name").focus().select();
916 this.commError(SypStrings.UnconsistentError);
917 $("#newuser_name").focus().select();
922 switch (xml.documentElement.getAttribute("request")) {
924 this.commSuccess(SypStrings.newUserSuccess);
925 $("#newuser_name, #newuser_password, #newuser_password_confirm, #newuser_submit").attr('disabled', 'disabled');
928 this.commError(SypStrings.UnconsistentError);
929 $("newuser_name").focus().select();
934 this.commError(SypStrings.UnconsistentError);
935 $("newuser_name").focus().select();
940 commSuccess: function (message) {
941 $("#newuser_comm").text(message);
942 $("#newuser_comm").removeClass("error success").addClass("success");
945 commError: function (message) {
946 $("#newuser_comm").text(message);
947 $("#newuser_comm").removeClass("error success").addClass("error");
951 $(window).load(function () {
952 // if using .ready, ie triggers an error when trying to access
953 // document.namespaces
955 $("#newfeature_button").click(function () {
956 Admin.addNewFeature();
958 $("#editor_close").click(function () {
959 Admin.cancelCurrentFeature()
961 $("#feature_update").submit(function() {
963 FeatureMgr.save(Admin.currentFeature);
967 $("#feature_delete").submit(function() {
969 FeatureMgr.del(Admin.currentFeature);
973 $("#image_delete").click(function() {
974 $("#img").removeAttr('src');
975 // needs to rebuild element otherwise some browsers still
977 $("#img").parent().html($("#img").parent().html());
978 $("#img").parent().hide();
979 $("#image_delete").hide();
980 $("#image_file").parent().show();