//Näkyvyysvakiot var V_OFF = 0; var V_SHOWN = 1; var V_HIDDEN = 2; var gpsUpdateRate = 1000; var wmscustomer = "infogis-pvp"; /************************************************************************************* WGS84-objekti, joka pitää sisällään kaikki esitystavat. *************************************************************************************/ var wgs84Format = function(initD) { this.d = {lat: 0, lon: 0}; this.dm = {lat: [0,0], lon: [0,0]}; this.dms = {lat: [0,0,0], lon: [0,0,0]}; this.dir = {lat: "", lon: ""}; this.set = function(lat, lon, type, dirs) { if(type == "DMS") { this.dms.lat = lat; this.dms.lon = lon; this.d.lat = lat[0] + (lat[1]+lat[2]/60)/60; this.d.lon = lon[0] + (lon[1]+lon[2]/60)/60; } else if(type == "DM") { this.dm.lat = lat; this.dm.lon = lon; this.d.lat = lat[0] + lat[1]/60; this.d.lon = lon[0] + lon[1]/60; } else { type = "D"; this.d.lat = lat; this.d.lon = lon; } if((dirs && dirs[0] == "W") || (!dirs && this.d.lat < 0)) { this.dir.lat = "W"; } else { this.dir.lat = "E"; } if(this.d.lat < 0) this.d.lat *= -1; if((dirs && dirs[1] == "S") || (!dirs && this.d.lon < 0)) { this.dir.lon = "S"; } else { this.dir.lon = "N"; } if(this.d.lon < 0) this.d.lon *= -1; if(type != "DM") { var tmpS = new String(this.d.lat); var tmpDeg = parseInt(tmpS.split(".")[0]); this.dm.lat = [tmpDeg, (this.d.lat - tmpDeg) * 60]; tmpS = new String(this.d.lon); tmpDeg = parseInt(tmpS.split(".")[0]); this.dm.lon = [tmpDeg, (this.d.lon - tmpDeg) * 60]; } if(type != "DMS") { var tmpS = new String(this.dm.lat[1]); var tmpDeg = parseInt(tmpS.split(".")[0]); this.dms.lat = [this.dm.lat[0], tmpDeg, (this.dm.lat[1] - tmpDeg) * 60]; tmpS = new String(this.dm.lon[1]); tmpDeg = parseInt(tmpS.split(".")[0]); this.dms.lon = [this.dm.lon[0], tmpDeg, (this.dm.lon[1] - tmpDeg) * 60]; } }; if(initD) { this.set(initD.clone().lat, initD.clone().lon); } }; var CommonCoordObj = function(title, proj, opt) { var opt = opt || {}; this.proj = proj || "EPSG:2393"; this.decims = opt.decims || 0; this.title = title; this.transTo = opt.transTo || function(coord, inProj) { return coord.clone().transform(new OpenLayers.Projection(inProj), new OpenLayers.Projection(this.proj)); }; this.transOut = opt.transFrom || function(coord, outProj) { return coord.transform(new OpenLayers.Projection(this.proj), new OpenLayers.Projection(outProj)); }; this.set = opt.set || function(coord, inProj) { var sCoord = this.transTo(coord, inProj); var inps = $("#ik"+this.title).children("input"); if(sCoord) { $(inps[0]).val(sCoord.lat.toFixed(this.decims)); $(inps[1]).val(sCoord.lon.toFixed(this.decims)); } else { $(inps[0]).val(""); $(inps[1]).val(""); } }; this.get = opt.get || function() { var inps = $("#ik"+this.title).children("input"); var gCoord = new OpenLayers.LonLat($(inps[1]).val(), $(inps[0]).val()); return gCoord; } }; /************************************************************************************* Feature-handlerin handle-eventin ylikirjoitus. Kohteet poimitaan geometrian mukaan käyttäen apuna toleranssia (10*resoluutio), renderöijältä pyynnin sijaan. *************************************************************************************/ OpenLayers.Handler.Feature.prototype.handle = function(evt) { if(this.feature && !this.feature.layer) { // feature has been destroyed this.feature = null; } var type = evt.type; var handled = false; var previouslyIn = !!(this.feature); // previously in a feature var click = (type == "click" || type == "dblclick" || type == "touchstart"); var tmpXY = evt.xy.clone(); var tmpLonLat = this.map.getLonLatFromPixel(tmpXY); if(type == "mousedown") this.ikMouseDown = tmpXY; if(type == "mouseup" && this.ikMouseDown && this.ikMouseDown.x == tmpXY.x && this.ikMouseDown.y == tmpXY.y) this.map.ikMapWrap.loadTrgtClick(tmpLonLat); if(type == "touchstart") this.map.ikMapWrap.loadTrgtHover(tmpLonLat); if(type == "touchmove" && this.map.ikMapWrap.hoverLoad) this.map.ikMapWrap.hoverLoad.cancel(); var iktolerance = this.map.getResolution() * 10; var iklayers = this.layer.layers; var ikfeatures = []; var found = null; for(var l in iklayers) { var iklayer = iklayers[l]; for(var f in iklayer.features) { var feat = iklayer.features[f]; if(feat.geometry.atPoint(this.map.getLonLatFromPixel(evt.xy), iktolerance, iktolerance)) { ikfeatures.push(feat); } } } if(ikfeatures.length > 0) { var tmpFeatArray = []; var tmpGeom = new OpenLayers.Geometry.Point(tmpLonLat.lon, tmpLonLat.lat); ikfeatures.reverse(); for(var i in ikfeatures) { var ikfeature = ikfeatures[i]; var dist = iktolerance; if(ikfeature.layer.name != "points" && ikfeature.layer.name != "user") { dist = iktolerance / 2; } if(ikfeature.geometry.distanceTo(tmpGeom, {edge: false}) < dist) { found = ikfeature; } } } this.feature = found; if(this.feature && !this.feature.layer) { // feature has been destroyed this.feature = null; } if(this.lastFeature && !this.lastFeature.layer) { // last feature has been destroyed this.lastFeature = null; } if(this.feature) { if(type === "touchstart") { // stop the event to prevent Android Webkit from // "flashing" the map div OpenLayers.Event.stop(evt); } var inNew = (this.feature != this.lastFeature); if(this.geometryTypeMatches(this.feature)) { // in to a feature if(previouslyIn && inNew) { // out of last feature and in to another if(this.lastFeature) { this.triggerCallback(type, 'out', [this.lastFeature]); } this.triggerCallback(type, 'in', [this.feature]); } else if(!previouslyIn || click) { // in feature for the first time this.triggerCallback(type, 'in', [this.feature]); } this.lastFeature = this.feature; handled = true; } else { // not in to a feature if(this.lastFeature && (previouslyIn && inNew || click)) { // out of last feature for the first time this.triggerCallback(type, 'out', [this.lastFeature]); } // next time the mouse goes in a feature whose geometry type // doesn't match we don't want to call the 'out' callback // again, so let's set this.feature to null so that // previouslyIn will evaluate to false the next time // we enter handle. Yes, a bit hackish... this.feature = null; } } else { if(this.lastFeature && (previouslyIn || click)) { this.triggerCallback(type, 'out', [this.lastFeature]); } } return handled; }; /************************************************************************************* IkMeasure control. Laajennetaan OpenLayers.Control.Measure-luokkaa ylikirjoittamalla measureComplete- ja measurePartial-metodit ja lisäämällä pause-metodi. *************************************************************************************/ OpenLayers.Control.IkMeasure = OpenLayers.Class(OpenLayers.Control.Measure, { /** * Method: measureComplete * Called when the measurement sketch is done. * * Parameters: * geometry - {} */ measureComplete: function(geometry) { this.cancelDelay(); this.measure(geometry, "measure"); }, /** * Method: measurePartial * Called each time a new point is added to the measurement sketch. * * Parameters: * point - {} The last point added. * geometry - {} The sketch geometry. */ measurePartial: function(point, geometry) { this.cancelDelay(); geometry = geometry.clone(); // when we're wating for a dblclick, we have to trigger measurepartial // after some delay to deal with reflow issues in IE if (this.handler.freehandMode(this.handler.evt)) { // no dblclick in freehand mode this.measure(geometry, "measurepartial"); } else { this.delayedTrigger = window.setTimeout( OpenLayers.Function.bind(function() { this.delayedTrigger = null; this.measure(geometry, "measurepartial"); }, this), this.partialDelay ); } }, /** * Method: pause * Called to pause measuring. This is done so measuring can be paused * and features don't have to be destroyed after finalizing. * * Parameters: * onPause - Boolean Set on pause true / false. */ pause: function(onPause) { this.handler.onPause = onPause; if(onPause) { //this.handler.finishGeometry(); if(this.handler.line) { var remIdx = this.handler.polygon? this.handler.line.geometry.components.length - 2:this.handler.line.geometry.components.length - 1; if(this.handler.line.geometry.removeComponent(this.handler.line.geometry.components[index])) { //this.handler.removePoint(); //this.handler.finalize(); //this.handler.undo(); this.handler.finishGeometry(); if(this.corners && this.corners.length > 0) { while(this.corners.length > this.handler.line.geometry.components.length) { var corner = this.corners.pop(); if(corner) { this.handler.layer.removeFeatures([corner]); } } } } else { this.handler.layer.removeAllFeatures(); this.handler.point = null; this.handler.line = null; this.handler.polygon = null; this.handler.lastDown = null; this.handler.lastUp = null; this.corners = []; } if(this.handler.line && this.partMeasPops && this.partMeasPops.length > 0) { while(this.partMeasPops.length > this.handler.line.geometry.components.length) { this.partMeasPops.pop().destroy(); } } if(this.handler.measurePop) { this.handler.measurePop.destroy(); this.handler.measurePop = null; } } this.handler.layer.redraw(); } else if(this.handler.line) { var index = this.handler.line.geometry.components.length -1; if(this.handler.CLASS_NAME == "OpenLayers.Handler.Polygon") { index--; } var oldEnd = this.handler.line.geometry.clone().components[index]; var newLonLat = new OpenLayers.LonLat(oldEnd.x, oldEnd.y); this.handler.lastDown = this.map.getPixelFromLonLat(newLonLat); this.handler.lastUp = this.handler.lastDown; if(this.handler.touch) this.handler.lastTouchPx = this.handler.lastDown; this.handler.line.geometry.addComponent( oldEnd, index+1 ); this.handler.point.geometry = oldEnd; } return false; } }); /************************************************************************************* IkMeasure-työkalun handlereiden laajennus. Estetään piirretyn featuren tuhoaminen finalizen jälkeen ja mahdollistetaan kartan liikuttelu myös alueiden kohdalta. *************************************************************************************/ var ikHandlerExtencion = { undo: function() { var geometry = this.line.geometry; var components = geometry.components; var index = this.getCurrentPointIndex(); if(!this.onPause)index--; var target = components[index]; var undone = geometry.removeComponent(target); if (undone) { if (!this.redoStack) { this.redoStack = []; } this.redoStack.push(target); this.drawFeature(); } return undone; }, down: function(evt) { var stopDown = this.stopDown; if(this.freehandMode(evt)) { stopDown = true; } if (!this.touch && (!this.lastDown || !this.passesTolerance(this.lastDown, evt.xy, this.pixelTolerance)) && !this.onPause) { this.modifyFeature(evt.xy, !!this.lastUp); } this.mouseDown = true; this.lastDown = evt.xy; this.stoppedDown = stopDown; return !stopDown; }, move: function (evt) { if(this.stoppedDown && this.freehandMode(evt) && !this.onPause) { this.addPoint(evt.xy); return false; } if (!this.touch && (!this.mouseDown || this.stoppedDown) && !this.onPause) { this.modifyFeature(evt.xy, !!this.lastUp); } return true; }, up: function (evt) { if (this.mouseDown && (!this.lastUp || !this.lastUp.equals(evt.xy)) && !this.onPause) { if(this.stoppedDown && this.freehandMode(evt)) { this.removePoint(); this.finalize(); } else { if (this.passesTolerance(this.lastDown, evt.xy, this.pixelTolerance)) { if (this.touch) { this.modifyFeature(evt.xy); } this.addPoint(evt.xy); this.lastUp = evt.xy; if(this.line.geometry.components.length === this.maxVertices + 1) { this.finishGeometry(); } } } } this.stoppedDown = this.stopDown; this.mouseDown = false; return !this.stopUp; }, destroyFeature: function(force) {} }; /************************************************************************************* IkPath ja IkPolygon handlerit laajennetaan luokista OpenLayers.Handler.Path ja OpenLayers.Handler.Polygon, em. laajennuksella. *************************************************************************************/ OpenLayers.Handler.IkPath = OpenLayers.Class(OpenLayers.Handler.Path, ikHandlerExtencion); OpenLayers.Handler.IkPolygon = OpenLayers.Class(OpenLayers.Handler.Polygon, ikHandlerExtencion); /************************************************************************************* OpenLayers.Control.Navigation-luokan wheelChange-metodin ylikirjoitus. SetCenter-metodin kutsuun lisätty muuttuja, joka kertoo että kutsu tulee rullalta. Näin Zoom osaa ottaa vasemman palkin huomioon tässäkin tapauksessa. *************************************************************************************/ OpenLayers.Control.Navigation.prototype.wheelChange = function(evt, deltaZ) { if (!this.map.fractionalZoom) { deltaZ = Math.round(deltaZ); } var currentZoom = this.map.getZoom(); var newZoom = this.map.getZoom() + Math.round(deltaZ); newZoom = Math.max(newZoom, 0); newZoom = Math.min(newZoom, this.map.getNumZoomLevels()-1); if (newZoom === currentZoom) { return; } var size = this.map.getSize(); var deltaX = size.w/2 - evt.xy.x; var deltaY = evt.xy.y - size.h/2; var newRes = this.map.baseLayer.getResolutionForZoom(newZoom); var zoomPoint = this.map.getLonLatFromPixel(evt.xy); var newCenter = new OpenLayers.LonLat( zoomPoint.lon + deltaX * newRes, zoomPoint.lat + deltaY * newRes ); this.map.setCenter( newCenter, newZoom, false, false, true ); }; /************************************************************************************* OpenLayers.Map-luokan setCenter-metodin ylikirjoitus. Välitetään fromWheel-parametri edelleen moveTo-metodille. *************************************************************************************/ OpenLayers.Map.prototype.setCenter = function(lonlat, zoom, dragging, forceZoomChange, fromWheel) { this.panTween && this.panTween.stop(); this.moveTo(lonlat, zoom, { 'dragging': dragging, 'forceZoomChange': forceZoomChange, 'fromWheel': fromWheel }); }; /******************************************************************************************** Kartan liikuttamisen ja zoomaamisen ylikirjoitus ********************************************************************************************/ OpenLayers.Map.prototype.moveTo = function(lonlat, zoom, options) { if (!options) { options = {}; } $("#ikMapLink").html(""); $(".ikLinkResults").hide(); if(!$(".ikMapGuiContainer").hasClass("igMobile"))$("#ikSaveLinkPop").remove(); var lpW,rpW; try {lpW = this.ikMapWrap.guiObj.getLeftPanelVisibleWidth();} catch(e){lpW = 0;} try {rpW = this.ikMapWrap.guiObj.getRightPanelVisibleWidth();} catch(e){rpW = 0;} if(this.ikMapWrap && this.ikMapWrap.guiObj.settings.mobile) { lpW = rpW = 0; this.ikMapWrap.followGps = (!this.dragging && options && options.fromGps != undefined); if(this.dragging && options && options.fromGps) return; if(this.ikMapWrap.followGps) { $(".ikGPSCenterButton").addClass("following"); } else { $(".ikGPSCenterButton").removeClass("following"); } if(this.ikMapWrap.trgtPop) { if(this.ikMapWrap.selectedParts && this.ikMapWrap.selectedParts.length > 0) { this.ikMapWrap.selPids(this.ikMapWrap.selectedParts, true); } else if(this.ikMapWrap.selectedTrgts.length > 0) { this.ikMapWrap.selTrgts(this.ikMapWrap.selectedTrgts, true); } else { this.ikMapWrap.ikTrgtCtrl.unselectAll(); this.ikMapWrap.selAreaWMS.mergeNewParams({"viewParams": ""}); this.ikMapWrap.selRouteWMS.mergeNewParams({"viewParams": ""}); this.ikMapWrap.selPointWMS.mergeNewParams({"viewParams": ""}); } } } if(this.ikMapWrap&&this.ikMapWrap.trgtPop)this.ikMapWrap.destroyTrgtPop(); if (zoom != null) { zoom = parseFloat(zoom); if (!this.fractionalZoom) { zoom = Math.round(zoom); } if(zoom == 0) { $(".olControlZoomOut").addClass("ikZoomOutDisabled"); $(".olControlZoomIn").removeClass("ikZoomInDisabled"); } else if(zoom == this.getNumZoomLevels()-1) { $(".olControlZoomIn").addClass("ikZoomInDisabled"); $(".olControlZoomOut").removeClass("ikZoomOutDisabled"); } else { $(".olControlZoomOut").removeClass("ikZoomOutDisabled"); $(".olControlZoomIn").removeClass("ikZoomInDisabled"); } } /* */ // dragging is false by default var dragging = options.dragging || this.dragging; // forceZoomChange is false by default var forceZoomChange = options.forceZoomChange; var ikRes = this.getResolution(); if(this.isValidLonLat(lonlat) && this.ikMapWrap && this.baseLayer.ikAutoChangeLayer && (new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat).distanceTo(this.baseLayer.maxExtent.toGeometry()) / ikRes < 20 || !this.baseLayer.maxExtent.containsLonLat(lonlat))) {//!(this.maxExtent.containsBounds(bounds) || bounds.containsBounds(this.maxExtent))) { this.ikMapWrap.guiObj.selectMap(this.baseLayer.ikAutoChangeLayer, true); } else { if (!this.getCachedCenter() && !this.isValidLonLat(lonlat)) { lonlat = this.maxExtent.getCenterLonLat(); this.center = lonlat.clone(); } if(this.restrictedExtent != null) { // In 3.0, decide if we want to change interpretation of maxExtent. if(lonlat == null) { lonlat = this.center; } if(zoom == null) { zoom = this.getZoom(); } var resolution = this.getResolutionForZoom(zoom); var extent = this.calculateBounds(lonlat, resolution); if(!this.restrictedExtent.containsBounds(extent)) { var maxCenter = this.restrictedExtent.getCenterLonLat(); if(extent.getWidth() > this.restrictedExtent.getWidth()) { lonlat = new OpenLayers.LonLat(maxCenter.lon, lonlat.lat); } else if(extent.left < this.restrictedExtent.left) { lonlat = lonlat.add(this.restrictedExtent.left - extent.left, 0); } else if(extent.right > this.restrictedExtent.right) { lonlat = lonlat.add(this.restrictedExtent.right - extent.right, 0); } if(extent.getHeight() > this.restrictedExtent.getHeight()) { lonlat = new OpenLayers.LonLat(lonlat.lon, maxCenter.lat); } else if(extent.bottom < this.restrictedExtent.bottom) { lonlat = lonlat.add(0, this.restrictedExtent.bottom - extent.bottom); } else if(extent.top > this.restrictedExtent.top) { lonlat = lonlat.add(0, this.restrictedExtent.top - extent.top); } } } var zoomChanged = forceZoomChange || ( (this.isValidZoomLevel(zoom)) && (zoom != this.getZoom()) ); var centerChanged = (this.isValidLonLat(lonlat)) && (!lonlat.equals(this.center)); // if neither center nor zoom will change, no need to do anything if (zoomChanged || centerChanged || dragging) { dragging || this.events.triggerEvent("movestart"); var res = zoomChanged ? this.getResolutionForZoom(zoom) : this.getResolution(); if((lpW > 0||rpW > 0) && !dragging && options.caller != "panTo" && /*(zoomChanged || centerChanged) && */!(this.zoom == null && lonlat.equals(this.center))&& !options.fromWheel) { if(lonlat == null) { lonlat = this.getCachedCenter(); var curRes = this.getResolution(); lonlat = lonlat.add(lpW*curRes/2-rpW*curRes/2, 0); } lonlat = lonlat.add(lpW*res/-2-rpW*res/-2, 0); if(!centerChanged) { centerChanged = (this.isValidLonLat(lonlat)) && (!lonlat.equals(this.center)); } } if (centerChanged) { if (!zoomChanged && this.center) { // if zoom hasnt changed, just slide layerContainer // (must be done before setting this.center to new value) this.centerLayerContainer(lonlat); } this.center = lonlat.clone(); } // (re)set the layerContainerDiv's location if (zoomChanged || this.layerContainerOrigin == null) { this.layerContainerOrigin = this.getCachedCenter(); this.layerContainerDiv.style.left = "0px"; this.layerContainerDiv.style.top = "0px"; var maxExtent = this.getMaxExtent({restricted: true}); var maxExtentCenter = maxExtent.getCenterLonLat(); var lonDelta = this.center.lon - maxExtentCenter.lon; var latDelta = maxExtentCenter.lat - this.center.lat; var extentWidth = Math.round(maxExtent.getWidth() / res); var extentHeight = Math.round(maxExtent.getHeight() / res); var left = (this.size.w - extentWidth) / 2 - lonDelta / res; var top = (this.size.h - extentHeight) / 2 - latDelta / res; this.minPx = new OpenLayers.Pixel(left, top); this.maxPx = new OpenLayers.Pixel(left + extentWidth, top + extentHeight); } if (zoomChanged) { this.zoom = zoom; this.resolution = res; // zoom level has changed, increment viewRequestID. this.viewRequestID++; } //send the move call to the baselayer and all the overlays var bounds = this.getExtent(); if(this.baseLayer.visibility) { this.baseLayer.moveTo(bounds, zoomChanged, options.dragging); options.dragging || this.baseLayer.events.triggerEvent( "moveend", {zoomChanged: zoomChanged} ); } bounds = this.baseLayer.getExtent(); for (var i=this.layers.length-1; i>=0; --i) { var layer = this.layers[i]; if (layer !== this.baseLayer && !layer.isBaseLayer) { var inRange = layer.calculateInRange(); if (layer.inRange != inRange) { // the inRange property has changed. If the layer is // no longer in range, we turn it off right away. If // the layer is no longer out of range, the moveTo // call below will turn on the layer. layer.inRange = inRange; if (!inRange) { layer.display(false); } this.events.triggerEvent("changelayer", { layer: layer, property: "visibility" }); } if (inRange && layer.visibility) { layer.moveTo(bounds, zoomChanged, options.dragging); options.dragging || layer.events.triggerEvent( "moveend", {zoomChanged: zoomChanged} ); } } } this.events.triggerEvent("move"); dragging || this.events.triggerEvent("moveend"); if (zoomChanged) { //redraw popups for (var i=0, len=this.popups.length; i 0 || rpW > 0) && fromOut) { var curRes = this.getResolution(); lonlat = lonlat.add(lpW*curRes/-2 - rpW*curRes/-2, 0); } if (this.panMethod && this.getExtent().scale(this.panRatio).containsLonLat(lonlat)) { if (!this.panTween) { this.panTween = new OpenLayers.Tween(this.panMethod); } var center = this.getCenter(); // center will not change, don't do nothing if (lonlat.lon == center.lon && lonlat.lat == center.lat) { return; } var from = { lon: center.lon, lat: center.lat }; var to = { lon: lonlat.lon, lat: lonlat.lat }; this.panTween.start(from, to, this.panDuration, { callbacks: { start: OpenLayers.Function.bind(function(lonlat) { this.events.triggerEvent("movestart"); }, this), eachStep: OpenLayers.Function.bind(function(lonlat) { lonlat = new OpenLayers.LonLat(lonlat.lon, lonlat.lat); this.moveTo(lonlat, this.zoom, { 'dragging': true, 'noEvent': true }); }, this), done: OpenLayers.Function.bind(function(lonlat) { lonlat = new OpenLayers.LonLat(lonlat.lon, lonlat.lat); this.moveTo(lonlat, this.zoom, { 'noEvent': true, 'caller': "panTo" }); this.events.triggerEvent("moveend"); }, this) } }); } else { if(fromOut && lpW > 0) { this.moveTo(lonlat, this.zoom, { 'caller': "panTo" }); } else { this.setCenter(lonlat); } } }; /******************************************************************************************** Hover-työkalu. Käytetään tunnistamaan kohteet pysäytettäessä hiiri. Ilmoittaa myös kun hiiri liikkuu. ********************************************************************************************/ OpenLayers.Control.Hover = OpenLayers.Class(OpenLayers.Control, { defaultHandlerOptions: { 'delay': 150, 'pixelTolerance': null, 'stopMove': false }, layers: null, hoverIn: function(){}, hoverOut: function() {}, initialize: function(options) { this.handlerOptions = OpenLayers.Util.extend( {}, this.defaultHandlerOptions ); OpenLayers.Control.prototype.initialize.apply( this, arguments ); this.handler = new OpenLayers.Handler.Hover( this, {'pause': this.onPause, 'move': this.onMove}, this.handlerOptions ); }, onPause: function(evt) { if(this.layers)this.hoverIn.call(this, evt); }, onMove: function(evt) { if(this.layers)this.hoverOut.call(this, evt); } }); /**************************************************************************************** Kohteen valintatyökalu. Laajennettu OpenLayers.Control.SelectFeature -luokasta, muuttamalla unselectAll-metodia niin, että options-objekti voi sisältää useita kohteita, jotka jätetään poistamatta. Objektiin lisätty parametrit: exceptFeats: String || [String] - kohteen/kohteiden partid, jotka halutaan säilyttää exceptOids: String || [String] - kohteen/kohteiden objectid, jotka halutaan säilyttää ****************************************************************************************/ OpenLayers.Control.IkSelectFeature = OpenLayers.Class(OpenLayers.Control.SelectFeature, { unselectAll: function(options) { // we'll want an option to supress notification here var layers = this.layers || [this.layer]; var layer, feature; var eFeats = (options && options.exceptFeats)? options.exceptFeats: []; var eOids = (options && options.exceptOids)? options.exceptOids: []; for(var l=0; l=0; --i) { feature = layer.selectedFeatures[i]; if(!options || (options.except != feature && $.inArray(feature.attributes.partid, eFeats) < 0 && $.inArray(feature.attributes.objectid, eOids) < 0)) { this.unselect(feature); } } } } }); /******************************************************************************************** Karttaluokka infokartta(options, guiParentObj) guiParentObj: objektin luova olio. Käytetään takaisinkutsuissa. Options: initLatLon: [Float, Float] - kartan avauskoordinaatit. Oletuksena [9608371.509933658,2849778.9643078037] (Kajaanin keskusta) initZoom: int - kartan avauszoomtaso, oletuksena 7. visibleProjection: String - näytettävän projektion nimi. Käytetään koordinaattien näyttämiseen. Oletuksena "EPSG:2393" hoverPopActive: Boolean - voiko Hover-työkalun Popup-listasta valita kohteita. Oletuksena true. bounds: [Float, Float, Float, Float] - PAKOLLINEN. Kartan rajauskoordinaatit, joiden avulla karttatasot myös keskitetään. Oletuksena [-596820.316627,8027722.4575739,6447616.208873,11486345.112802] naviMap: näkyvyysvakio - Pikkukartan näkyvyys. Oletuksena V_SHOWM. naviMapBounds: [Float, Float, Float, Float] - PAKOLLINEN. Pikkukartan rajauskoordinaatit. Oletuksena [-4246229.7944258,6134530.1413393,9842643.2565742,13051775.451796] ********************************************************************************************/ //OpenLayers.ProxyHost = "/cgi-bin/proxy.cgi?url="; function infokartta(container, options, guiParentObj) { this.settings = { containerId: "", initLatLon: [9608371.509933658,2849778.9643078037],//[3514821.345, 7151125.269],////65.00, 25.60], initZoom: 7, visibleProjection: "EPSG:3067", mousePosOptions: {prefix: "(ETRS-TM35FIN) I:", separator: " P:",numDigits: 0}, hoverPopsActive: true, bounds: [-596820.316627,8027722.4575739,6447616.208873,11486345.112802],//[3061995.247, 6575611.718,3875149.877, 7786095.948], naviMap: V_SHOWN, naviMapBounds: [-4246229.7944258,6134530.1413393,9842643.2565742,13051775.451796]//[3061995.247, 6575611.718,3875149.877, 7786095.948] }; if(options) { for(var property in options) { var value = options[property]; if(value !== undefined) { this.settings[property] = value; } } } this.settings.containerId = container; this.initialized = false; /******************************************************************************************** Tyylien määrittelyt ********************************************************************************************/ /******************************************************************************************** GPS-tason tyyli. ********************************************************************************************/ this.gps_style = new OpenLayers.StyleMap({ "default": new OpenLayers.Style({ fillOpacity: 1, graphicOpacity: 1, pointRadius: 15, pointerEvents: "none", graphicWidth: 30, graphicHeight: 60, backgroundWidth: 30, backgroundHeight: 60, graphicZIndex: 340, cursor: "default", rotation: "${ikdir}", externalGraphic: "http://kartta.pvp.fi/infogis-pvp/style/img/"+"${iksymbol}" }) }); /******************************************************************************************** Pistemäisten kohteiden tason (pointLayer) tyyli. ********************************************************************************************/ this.point_style = new OpenLayers.StyleMap({ "default": new OpenLayers.Style({ fillOpacity: 1, graphicOpacity: 1, pointRadius: 7, pointerEvents: "visiblePainted", graphicWidth: 14, graphicHeight: 14, backgroundWidth: 1, backgroundHeight: 1, backgroundGraphic: " ", graphicZIndex: 337, cursor: "pointer", externalGraphic: "http://kartta.pvp.fi/infogis-pvp/style/Netti/"+"${iksymbol}" }), "select": new OpenLayers.Style({ backgroundWidth: 16, backgroundHeight: 16, graphicZIndex: 339, backgroundGraphicZIndex: 338, graphicOpacity: 1, pointRadius: 8, pointerEvents: "visiblePainted", externalGraphic: "http://kartta.pvp.fi/infogis-pvp/style/Netti/"+"${iksymbol}", cursor: "pointer", backgroundGraphic: "http://kartta.pvp.fi/infogis-pvp/style/seuranta-gfx/iconBack.gif" }) }); /******************************************************************************************** Reittikohteiden tason (routeLayer) tyyli. ********************************************************************************************/ this.route_style = new OpenLayers.StyleMap( { "default": new OpenLayers.Style({ strokeColor: "red", strokeWidth: 3, strokeDashstyle: "solid", pointerEvents: "visiblePainted", cursor: "pointer", pointRadius: 3, graphicZIndex: 333, strokeColor: "${iklinecolor}", strokeDashstyle: "${iklinestyle}" }), "select": new OpenLayers.Style({ strokeColor: "${iksellinecolor}", strokeDashstyle: "${iksellinestyle}", graphicZIndex: 334, strokeWidth: 3 }) }); /******************************************************************************************** aluekohteiden tason (areaLayer) tyyli. ********************************************************************************************/ this.area_style = new OpenLayers.StyleMap({ "default": new OpenLayers.Style({ strokeWidth: 2, cursor: "pointer", pointRadius: 2, graphicZIndex: 328, strokeColor: "${iklinecolor}", fillOpacity: "${ikfillopacity}", fillColor: "${ikfillcolor}", strokeDashstyle: "${linestyle}" }), "select": new OpenLayers.Style({ strokeWidth: 2, cursor: "pointer", graphicZIndex: 329, fillOpacity: "${ikselfillopacity}", strokeColor: "${iksellinecolor}", fillColor: "${ikselfillcolor}", strokeDashstyle: "${iksellinestyle}" }) }); /******************************************************************************************** Mittakaavatulostuksen tyyli. ********************************************************************************************/ this.scaled_print_style = new OpenLayers.StyleMap( { "default": new OpenLayers.Style({ strokeColor: "red", strokeWidth: 3, strokeDashstyle: "solid", pointerEvents: "none", fillOpacity: 0, pointRadius: 3, graphicZIndex: 600 }) }); /******************************************************************************************** Mitta- ja koordinaattityökalujen tasojen tyylin muodostaminen. ********************************************************************************************/ var measureSymbolizers = { "Point": { pointRadius: 2, graphicName: "square", fillOpacity: 1, strokeWidth: 1, strokeOpacity: 1, strokeColor: "black", fillColor: "black" }, "Line": { strokeWidth: 3, strokeOpacity: 1, strokeDashstyle: "solid" }, "Polygon": { strokeWidth: 2, strokeOpacity: 1, fillOpacity: 0.3 } }; var meaStyle = new OpenLayers.Style(); meaStyle.addRules([ new OpenLayers.Rule({symbolizer: measureSymbolizers}) ]); this.measureStyle = new OpenLayers.StyleMap({"default": meaStyle}); this.marking_style = new OpenLayers.StyleMap({ "default": new OpenLayers.Style({ fillOpacity: 1, graphicOpacity: 1, pointerEvents: "", graphicWidth: 8, graphicHeight: 8, backgroundWidth: 1, backgroundHeight: 1, externalGraphic: "http://kartta.pvp.fi/infogis-pvp/style/seuranta-gfx/RedBall18.gif" }), "select": new OpenLayers.Style({ graphicOpacity: 1, graphicWidth: 14, graphicHeight: 14, pointerEvents: "", externalGraphic: "http://kartta.pvp.fi/infogis-pvp/style/seuranta-gfx/RedBall18.gif" }) }); /******************************************************************************************** Functiot ja muuttujat ********************************************************************************************/ this.trgtsOnMap = []; //Kartalla olevien kohteiden objectid:t this.partsOnMap = []; //Kartelle partId:llä valitut kohteet muodossa [oid,pid] this.selectedParts = []; //valittujen featureiden partid:t this.selectedTrgts = []; //valittujen kohteiden objectid:t this.ikBaseName = ""; //Valitun baselayerin nimi this.getBaseLayerName = GetBaseLayerName; this.delayedMmUpdate = DelayedMmUpdate; this.getIkMapCenter = GetIkMapCenter; this.otherLayerInit = OtherLayerInit; this.createPointControl = CreatePointControl; this.removePointControl = RemovePointControl; this.dimBaseLayer = DimBaseLayer; this.measureRoutes = MeasureRoutes; this.toggleRouteMeasure = ToggleRouteMeasure; this.setMarkingControl = SetMarkingControl; this.setMeasuringControl = SetMeasuringControl; this.handleMeasurements = HandleMeasurements; this.selectedOverlays = []; this.setOverlay = SetOverlay; this.setNaviLayer = SetNaviLayer; this.setBaseLayer = SetBaseLayer; this.onBaseLayerChange = OnBaseLayerChange; this.selTrgts = SelTrgts; this.selPids = SelPids; this.showBounds = ShowBounds; this.zoomToTrgts = ZoomToTrgts; this.addFeatures = AddFeatures; this.remFeatures = RemFeatures; this.addParts = AddParts; this.remParts = RemParts; this.remAllFeatures = RemAllFeatures; this.getSelectedFids = GetSelectedFids; this.ikMapLoadListener = IkMapLoadListener; this.showLoad = ShowLoad; this.loadAttribution = LoadAttribution; this.handleAttribution = HandleAttribution; this.loadTrgtHover = LoadTrgtHover; this.handleTrgtHover = HandleTrgtHover; this.loadTrgtClick = LoadTrgtClick; this.handleTrgtClick = HandleTrgtClick; this.initGeoLocating = InitGeoLocating; this.updateUserLocation = UpdateUserLocation; this.locatingFailed = LocatingFailed; this.centerToUserLocation = CenterToUserLocation; this.loadQueLength = 0; this.onTrgtPop = false; this.hoverHandlerTrgtPop = HoverHandlerTrgtPop; this.handlePopTrgtHover = HandlePopTrgtHover; this.handlePopTrgtClick = HandlePopTrgtClick; this.trgtPop = null; this.destroyTrgtPop = DestroyTrgtPop; this.onFeatureSelect = OnFeatureSelect; this.onHoverIn = OnHoverIn; this.onHoverOut = OnHoverOut; this.delayedUnselect = DelayedUnselect; this.delayedPopClose = DelayedPopClose; /*******************************************************************************************/ this.guiObj = guiParentObj; OpenLayers.ImgPath = "http://kartta.pvp.fi/infogis-pvp/img/"; this.attrbControl = new OpenLayers.Control.Attribution(); $("
").appendTo("#"+this.settings.containerId); var ctrls = [ new OpenLayers.Control.Navigation(), new OpenLayers.Control.MousePosition(this.settings.mousePosOptions), new OpenLayers.Control.PanZoomBar({panIcons: false}) //new OpenLayers.Control.LayerSwitcher({activeColor: "#008431"}), ]; if(this.guiObj.settings.mobile) { var ctrls = [ new OpenLayers.Control.Navigation(), new OpenLayers.Control.Zoom({ zoomInText: " ", zoomOutText: " " }) ]; } this.map = new OpenLayers.Map("ikOlMap", { controls: ctrls, theme: 'http://kartta.pvp.fi/infogis-pvp/theme/infoTrack/style.css', displayProjection: new OpenLayers.Projection(this.settings.visibleProjection), units: "m", maxResolution: 4891.969809375, maxExtent: new OpenLayers.Bounds(this.settings.bounds[0],this.settings.bounds[1],this.settings.bounds[2],this.settings.bounds[3]) }); this.map.ikMapWrap = this; var ikTmpWrap = this; this.map.events.on({"changebaselayer": function() {ikTmpWrap.onBaseLayerChange();}}); //FeatureSelect-controllin valinta callback ylikirjoitetaan: OpenLayers.Control.IkSelectFeature.prototype.callbacks = {click: ikTmpWrap.onFeatureSelect}; var lpWidth,rpWidth; try {lpWidth = this.guiObj.getLeftPanelVisibleWidth();} catch(e){lpWidth = 0;} try {rpWidth = this.guiObj.getRightPanelVisibleWidth();} catch(e){rpWidth = 0;} $("
").appendTo("#"+this.settings.containerId).sticky({draggable: false, top: ($("#"+this.settings.containerId).height()/2-50)+"px",height: "100px", backgroundColor: "transparent", border: "none", fade: "false", fade_opacity: "1", width: "100px", left: ($("#"+this.settings.containerId).width()/2+lpWidth/2-rpWidth/2-50)+"px", close: false}); $("#ikLoadingGif>.sticky-close").remove(); $("#ikLoadingGif").css({"z-index": "99999"}); $("#ikLoadingGif").hide(); this.areaLayer = null; this.routeLayer = null; this.pointLayer = null; this.usrLayer = null; this.pointWMS = null; this.routeWMS = null; this.areaWMS = null if(!$.isEmptyObject( ikMaps )) { this.bNo = []; for(var name in ikMaps) { ikTmpWrap.ikBaseName = name; break; } this.otherLayerInit(); if(!$.isEmptyObject( ikNaviMaps )) { this.mmLayers = []; for(var n in ikNaviMaps) { var naviM = ikNaviMaps[n]; this.mmLayers[n] = naviM.mLayer; } this.setNaviLayer(ikMaps[ikTmpWrap.ikBaseName].mNaviMapPref); this.mmapInitTimer = window.setTimeout( OpenLayers.Function.bind(this.delayedMmUpdate, this, 0), 500 ); } } this.map.setCenter(new OpenLayers.LonLat(this.settings.initLatLon[1], this.settings.initLatLon[0]), this.settings.initZoom); }; function DelayedMmUpdate(count) { window.clearTimeout(this.mmapInitTimer); this.mmapInitTimer = null; try{ this.minimap.update(); } catch(err) { if(count < 100) { this.mmapInitTimer = window.setTimeout( OpenLayers.Function.bind(this.delayedMmUpdate, this, count+1), 500 ); } } }; /******************************************************************************************** Tallennetun baselayerin nimen getter. Palauttaa: String - nimi. ********************************************************************************************/ function GetBaseLayerName() { return this.ikBaseName; }; /******************************************************************************************** Palauttaa kartan keskipisteen, käytettävässä koordinaatistossa. Ottaa huomioon vasemman panelin näkyvyyden. Palauttaa: OpenLayers.LonLat - kartan keskipisteen koordinaatit. ********************************************************************************************/ function GetIkMapCenter() { var tmpCenter = this.map.getCenter(); tmpRes = this.map.getResolution(); var lpW,rpW; try {lpW = this.guiObj.getLeftPanelVisibleWidth();} catch(e){lpW = 0;} try {rpW = this.guiObj.getRightPanelVisibleWidth();} catch(e){rpW = 0;} if(lpW > 0 || rpW > 0) { tmpCenter = tmpCenter.add(lpW*tmpRes/2 - rpW*tmpRes/2, 0); } return tmpCenter; }; /******************************************************************************************** Karttatasojen alustus. Nykyisellään alustetaan kaikki tasot täällä. Nimi legacyä. ********************************************************************************************/ function OtherLayerInit() { var ikTmpWrap = this; var firstName; for(var mName in ikMaps) { firstName = mName; break; } this.setBaseLayer(firstName, ikMaps[mName].mProj); this.bNo = null; this.bNo = []; this.areaWMS = new OpenLayers.Layer.WMS("areas", ["http://kartta.pvp.fi/geoserver/wms"], { LAYERS: 'infogis:wms_infogis_areas', // LAYERS: 'kainuu:wms_kainuu_areas', format: 'image/png', EXCEPTIONS: "application/vnd.ogc.se_blank", //"application/vnd.ogc.se_inimage" // tiled: false, transparent: true }, { visibility: false, buffer: 0, //singleTile: true, tileSize: new OpenLayers.Size(512, 512), displayOutsideMaxExtent: true, removeBackBufferDelay: 3000, tileOptions: {maxGetUrlLength: 2048} } ); this.selAreaWMS = new OpenLayers.Layer.WMS("selected areas", ["http://kartta.pvp.fi/geoserver/wms"], { LAYERS: 'infogis:wms_infogis_sel_areas', // LAYERS: 'kainuu:wms_kainuu_sel_areas', format: 'image/png', EXCEPTIONS: "application/vnd.ogc.se_blank", // tiled: false, transparent: true }, { visibility: false, buffer: 0, //singleTile: true, tileSize: new OpenLayers.Size(512, 512), displayOutsideMaxExtent: true, removeBackBufferDelay: 3000, tileOptions: {maxGetUrlLength: 2048} } ); this.routeWMS = new OpenLayers.Layer.WMS("routes", ["http://kartta.pvp.fi/geoserver/wms"], { LAYERS: 'infogis:wms_infogis_routes', // LAYERS: 'kainuu:wms_kainuu_routes', format: 'image/png', EXCEPTIONS: "application/vnd.ogc.se_blank", // tiled: false, transparent: true }, { visibility: false, buffer: 0, //singleTile: true, tileSize: new OpenLayers.Size(512, 512), displayOutsideMaxExtent: true, removeBackBufferDelay: 3000, tileOptions: {maxGetUrlLength: 2048} } ); this.selRouteWMS = new OpenLayers.Layer.WMS("selected routes", ["http://kartta.pvp.fi/geoserver/wms"], { LAYERS: 'infogis:wms_infogis_sel_routes', // LAYERS: 'kainuu:wms_kainuu_sel_routes', format: 'image/png', EXCEPTIONS: "application/vnd.ogc.se_blank", // tiled: false, transparent: true }, { visibility: false, buffer: 0, //singleTile: true, tileSize: new OpenLayers.Size(512, 512), displayOutsideMaxExtent: true, removeBackBufferDelay: 3000, tileOptions: {maxGetUrlLength: 2048} } ); this.tmpSelRouteWMS = new OpenLayers.Layer.WMS("temp selected routes", ["http://kartta.pvp.fi/geoserver/wms"], { LAYERS: 'infogis:wms_infogis_sel_routes', // LAYERS: 'kainuu:wms_kainuu_sel_routes', format: 'image/png', EXCEPTIONS: "application/vnd.ogc.se_blank", // tiled: false, transparent: true }, { visibility: false, buffer: 0, //singleTile: true, tileSize: new OpenLayers.Size(512, 512), displayOutsideMaxExtent: true, removeBackBufferDelay: 3000, tileOptions: {maxGetUrlLength: 2048} } ); this.pointWMS = new OpenLayers.Layer.WMS("points", ["http://kartta.pvp.fi/geoserver/wms"], { LAYERS: 'infogis:wms_infogis_points', // LAYERS: 'kainuu:wms_kainuu_points', format: 'image/png', EXCEPTIONS: "application/vnd.ogc.se_blank", // tiled: false, transparent: true }, { visibility: false, buffer: 0, //singleTile: true, tileSize: new OpenLayers.Size(512, 512), displayOutsideMaxExtent: true, removeBackBufferDelay: 3000, tileOptions: {maxGetUrlLength: 2048} } ); this.selPointWMS = new OpenLayers.Layer.WMS("selected points", ["http://kartta.pvp.fi/geoserver/wms"], { LAYERS: 'infogis:wms_infogis_sel_points', // LAYERS: 'kainuu:wms_kainuu_sel_points', format: 'image/png', EXCEPTIONS: "application/vnd.ogc.se_blank", // tiled: true, transparent: true }, { visibility: false, buffer: 0, //singleTile: true, tileSize: new OpenLayers.Size(512, 512), displayOutsideMaxExtent: true, removeBackBufferDelay: 3000, tileOptions: {maxGetUrlLength: 2048} } ); this.bNo.push(this.areaWMS); this.bNo.push(this.selAreaWMS); this.bNo.push(this.routeWMS); this.bNo.push(this.selRouteWMS); this.bNo.push(this.tmpSelRouteWMS); this.bNo.push(this.pointWMS); this.bNo.push(this.selPointWMS); this.usrLayer = new OpenLayers.Layer.Vector("user", { styleMap: this.point_style, projection: this.map.getProjectionObject(), displayInLayerSwitcher: true, visibility: true, rendererOptions: { zIndexing: true } }); this.bNo.push(this.usrLayer); this.map.addLayers(this.bNo); var lpW; try {lpW = this.guiObj.getLeftPanelVisibleWidth();} catch(e){lpW = 0;} this.map.addControl(new OpenLayers.Control.ScaleLine({geodesic: false, bottomOutUnits: "", bottomInUnits: ""})); $(".olControlScaleLine", ".ikMapGuiContainer").css({left: (lpW+70) +"px"}); this.ikTrgtCtrl = new OpenLayers.Control.IkSelectFeature([this.usrLayer], {hover: false, multiple: true, clickout: false, toggle: true, box: false}); this.ikHoverCtrl = new OpenLayers.Control.Hover({layers: [this.usrLayer], onPause: ikTmpWrap.onHoverIn, onMove: ikTmpWrap.onHoverOut}); this.map.addControl(this.ikTrgtCtrl); this.map.addControl(this.ikHoverCtrl); this.ikTrgtCtrl.activate(); if(!this.guiObj.settings.mobile)this.ikHoverCtrl.activate(); var mapWrap = this; if(this.guiObj && this.guiObj.settings.mobile) { this.initGeoLocating(); } this.initialized = true; }; /******************************************************************************************** Pistetyökalun luonti ja lisääminen kartalle. Käytetään esim. linkin teossa ja palaute- lomakkeessa. ********************************************************************************************/ function CreatePointControl() { this.pointCtrl = new OpenLayers.Control.DrawFeature(this.usrLayer, OpenLayers.Handler.Point, {handlerOptions: {stopDown: false, stopUp: false}, featureAdded: function(f) { $("#ikMapLink").html(""); $(".ikLinkResults").hide(); $("#ikSaveLinkPop").remove(); f.attributes["iksymbol"] = "RedBall18.gif"; f.attributes["ikdescription-fi"]= "Oma kohde"; f.attributes["ikdescription-en"]= "Created target"; f.layer.drawFeature(f); if(this.lastPoint) { f.layer.removeFeatures([this.lastPoint]); } this.lastPoint = f; return false; }}); this.map.addControl(this.pointCtrl); this.pointCtrl.activate(); }; /******************************************************************************************** Poistaa pistetyökalun pisteineen. ********************************************************************************************/ function RemovePointControl() { if(this.pointCtrl) { this.usrLayer.removeAllFeatures(); this.pointCtrl.deactivate(); this.pointCtrl = null; } }; function DimBaseLayer(opac) { var base = this.map.getLayersByName(this.ikBaseName); if(base.length > 0) { $(base).each(function() { this.setOpacity(opac); }); } else {} }; function MeasureRoutes() { var mapWrap = this; var pids = []; $(this.selectedParts).each(function() { if($.isArray(this)) pids.push(this[1]); }); $.ajax({ type: "POST", dataType: "text", timeout: 15000, url: "http://kartta.pvp.fi/infogis-pvp/php/measroutes.php?customer=infogis-pvp", async: true, data: "routes=["+pids.join(",")+"]", success: function(meas) { $("#ikMeasurement").html(meas); }, error: function (XMLHttpRequest, textStatus, errorThrown) { return true; } }); }; /************************************************************************************* Reittisegmenttien poimintaan (ja mittaamiseen) tarkoitetun työkalun aktiivisuus toggle. *************************************************************************************/ function ToggleRouteMeasure() { if(this.rMeasActive) { this.rMeasActive = false; $("#ikMeasurement").html("0 m"); this.ikTrgtCtrl.unselectAll(); this.selectedParts = []; this.selRouteWMS.mergeNewParams({"viewParams":""}); this.selRouteWMS.setVisibility(false); if(this.tmpSelRouteWMS.visibility) { this.tmpSelRouteWMS.mergeNewParams({"viewParams":""}); this.tmpSelRouteWMS.setVisibility(false); } $("#ikToggleMeasureButton", ".ikMapGuiContainer").html("> Aloita mittaus"); } else { this.ikTrgtCtrl.unselectAll(); this.rMeasActive = true; this.selectedParts = []; this.selRouteWMS.mergeNewParams({"viewParams":""}); this.selRouteWMS.setVisibility(false); var mapWrap = this; //this.measureRoutes(); $("#ikToggleMeasureButton", ".ikMapGuiContainer").html("> Uusi mittaus"); } if(ikLan != "fi" || forceLocal) { $("*[rel^='localize[meastool_buttons.']").localize("rplan", {language: ikLan, pathPrefix:ikLocalisePrefix}); } }; /************************************************************************************* Koordinaattityökalun luonti/poisto. Kutsuu SetMeasurngControl-metodia tyypillä "mark". on: Boolean - päälle/pois -> true/false. *************************************************************************************/ function SetMarkingControl(on) { this.setMeasuringControl(on, "mark"); }; /************************************************************************************* Reitti- ja aluetyökalun luonti/poisto (myös koordinaatityökalun). on: Boolean - päälle/pois -> true/false. type: String - työkalun tyyppi, vaihtohedot: "path", "area", "mark" *************************************************************************************/ function SetMeasuringControl(on, type) { if(on) { if(this.ikTrgtCtrl)this.ikTrgtCtrl.deactivate(); if(this.ikHoverCtrl)this.ikHoverCtrl.deactivate(); var mapObj = this.map; var ikMapWrap = this; var handler, styleMap; if(type == "area") { handler = OpenLayers.Handler.IkPolygon; } else { handler = OpenLayers.Handler.IkPath; } this.ikMeasureControl = new OpenLayers.Control.IkMeasure( handler, { persist: true, handlerOptions: { freehandToggle: 'altKey', layerOptions: {styleMap: this.measureStyle} }, callbacks: { modify: function(point, line, drawing) { if(!this.handler.onPause &&!this.handler.mouseDown && this.measType == "path") { var sketch = new OpenLayers.Geometry.LineString([line.geometry.components[line.geometry.components.length-1], line.geometry.components[line.geometry.components.length-2]]); var data = this.getBestLength(sketch); if(data[0] > 0) { var insPoint = new OpenLayers.LonLat(point.x, point.y); var decs = 2; if(data[1] == "m") decs = 0; if(!this.handler.measurePop) { this.handler.measurePop = new OpenLayers.Popup.Anchored(null, insPoint, new OpenLayers.Size(60,15), ""+data[0].toFixed(decs)+" "+data[1]+" ", {size: new OpenLayers.Size(2,2), pixel: new OpenLayers.Pixel(0,0)}, false); this.handler.measurePop.setBackgroundColor("transparent"); this.handler.measurePop.setBorder("none"); this.handler.measurePop.panMapIfOutOfView = false; this.handler.measurePop.keepInMap = true; this.map.addPopup(this.handler.measurePop, false); } else { this.handler.measurePop.setContentHTML(""+data[0].toFixed(decs)+""+data[1]+""); var contW = $(this.handler.measurePop.contentDiv).children(".ikMPopTxt").width(); var contH = $(this.handler.measurePop.contentDiv).height(); if(contH < 15) contH = 15; this.handler.measurePop.setSize(new OpenLayers.Size(contW, contH)); this.handler.measurePop.moveTo(this.map.getLayerPxFromViewPortPx(this.map.getPixelFromLonLat(insPoint))); } } } } } }); if($(".ikRMeasToggleButton:visible").length > 0) { try { this.guiObj.showRouteMeasureTool(false); } catch(e){} } this.ikMeasureControl.handler.onPause = false; this.ikMeasureControl.geodesic = true; this.ikMeasureControl.measType = type; this.ikMeasureControl.partMeasPops = []; this.ikMeasureControl.events.on({ "measure": this.handleMeasurements, "measurepartial": this.handleMeasurements }); this.map.addControl(this.ikMeasureControl); this.ikMeasureControl.activate(); if(type == "mark") { this.ikMeasureControl.markLayer = new OpenLayers.Layer.Vector("marks", {styleMap: this.marking_style, geometryType: OpenLayers.Geometry.Point, displayInLayerSwitcher: false, visibility: true}); this.map.addLayers([this.ikMeasureControl.markLayer]); this.ikMeasureControl.handler.layer.setVisibility(false); this.ikMeasureControl.marks = []; } if(type != "area") { this.ikMeasureControl.corners = []; } var lpW,rpW; try {lpW = this.guiObj.getLeftPanelVisibleWidth();} catch(e){lpW = 0;} try {rpW = this.guiObj.getRightPanelVisibleWidth();} catch(e){rpW = 0;} $("#ikCancelMPButton", ".ikMapGuiContainer").bind("click", function() { if(ikMapWrap.ikMeasureControl.handler.line) { var geom = ikMapWrap.ikMeasureControl.handler.line.geometry; var exists = true; var tmpIdxMinus = 1; var minComp = ikMapWrap.ikMeasureControl.measType == "area"? 3:2; if(ikMapWrap.ikMeasureControl.handler.onPause && geom.components.length == minComp) { $("#ikToggleMeasureButton").trigger("click"); var newLonLat = new OpenLayers.LonLat(geom.components[0].x, geom.components[0].y); var newPixel = ikMapWrap.map.getPixelFromLonLat(newLonLat); ikMapWrap.ikMeasureControl.handler.modifyFeature(newPixel); } if((ikMapWrap.ikMeasureControl.measType == "area" && geom.components.length == minComp) || geom.components.length == minComp) { if(ikMapWrap.ikMeasureControl.handler.layer) { ikMapWrap.ikMeasureControl.handler.layer.destroyFeatures(); } if(ikMapWrap.ikMeasureControl.markLayer) { ikMapWrap.ikMeasureControl.markLayer.destroyFeatures(); ikMapWrap.ikMeasureControl.marks = []; } ikMapWrap.ikMeasureControl.handler.point = null; ikMapWrap.ikMeasureControl.handler.line = null; ikMapWrap.ikMeasureControl.handler.polygon = null; if(ikMapWrap.ikMeasureControl.measType == "area") { $("#ikMeasurement").html("0.00 m2"); } else if(ikMapWrap.ikMeasureControl.measType == "path") { $("#ikMeasurement").html("0.00 m"); } exists = false; } else { if(ikMapWrap.ikMeasureControl.corners && ikMapWrap.ikMeasureControl.corners.length > 0) { var corner = ikMapWrap.ikMeasureControl.corners.pop(); if(corner) { ikMapWrap.ikMeasureControl.handler.layer.removeFeatures([corner]); ikMapWrap.ikMeasureControl.handler.layer.redraw(); } } ikMapWrap.ikMeasureControl.handler.undo(); if(ikMapWrap.ikMeasureControl.handler.onPause) { ikMapWrap.ikMeasureControl.handler.removePoint(); tmpIdxMinus = 0; } var newGeom = geom.clone(); var tmpMeas; var sup = ""; if(ikMapWrap.ikMeasureControl.measType == "area") { if(!ikMapWrap.ikMeasureControl.handler.onPause)newGeom.removeComponent(newGeom.components[newGeom.components.length-2]); var newArea = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Polygon([newGeom]) ); tmpMeas = ikMapWrap.ikMeasureControl.getBestArea(newArea.geometry); sup = "2"; } else { if(!ikMapWrap.ikMeasureControl.handler.onPause)newGeom.removeComponent(newGeom.components[newGeom.components.length-1]); if(ikMapWrap.ikMeasureControl.handler.onPause || geom.components.length > 2) { tmpMeas = ikMapWrap.ikMeasureControl.getBestLength(newGeom); } else { tmpMeas = [0,"m"]; } } var decimals = 2; if(tmpMeas[1] == "m") decimals = 0; var dev = 1; var units = tmpMeas[1]+sup; if(ikMapWrap.ikMeasureControl.measType == "area") { if(tmpMeas[1] == "m" && tmpMeas[0] >= 10000) { dev = 10000; decimals = 2; units = "ha"; } else if(tmpMeas[1] == "km" && tmpMeas[0] <= 100) { dev = 0.01; units = "ha"; } } var measure = (tmpMeas[0]/dev).toFixed(decimals); var meastr = ""+measure; if(measure >= 1000) { var spacer = meastr.indexOf('.') - 3; while(spacer > 0) { meastr = (meastr.substring(0, spacer)+" "+meastr.substring(spacer)); spacer -= 3; } } $("#ikMeasurement").html(meastr+" "+units); } if(ikMapWrap.ikMeasureControl.marks && ikMapWrap.ikMeasureControl.marks.length > 0) { ikMapWrap.ikMeasureControl.markLayer.removeFeatures([ikMapWrap.ikMeasureControl.markLayer.features.pop()]); if(ikMapWrap.ikMeasureControl.markLayer.features.length > 0) { var prev = ikMapWrap.ikMeasureControl.markLayer.features[ikMapWrap.ikMeasureControl.markLayer.features.length - 1]; ikMapWrap.ikMeasureControl.markLayer.selectedFeatures.push(prev); ikMapWrap.ikMeasureControl.markLayer.drawFeature(prev, "select"); } ikMapWrap.ikMeasureControl.marks.pop(); ikMapWrap.ikMeasureControl.markLayer.redraw(); tmpIdxMinus = (ikMapWrap.ikMeasureControl.handler.onPause&&geom.components.length>1)?-1:0; } if(ikMapWrap.ikMeasureControl.handler.measurePop) { ikMapWrap.ikMeasureControl.handler.measurePop.destroy(); ikMapWrap.ikMeasureControl.handler.measurePop = null; } if(ikMapWrap.ikMeasureControl.partMeasPops.length > 0) { while(ikMapWrap.ikMeasureControl.partMeasPops.length > 0 && (ikMapWrap.ikMeasureControl.partMeasPops.length >= geom.components.length - tmpIdxMinus || !exists)) { ikMapWrap.ikMeasureControl.partMeasPops.pop().destroy(); } } } }); $("#ikToggleMeasureButton", ".ikMapGuiContainer").removeClass("onPause").html("> Pysäytä").bind("click", function() { var onPause = false; if($(this).hasClass("onPause")) { $(this).html("> Pysäytä"); if(ikLan != "fi" || forceLocal) { $("*[rel^='localize[meastool_buttons.']").localize("rplan", {language: ikLan, pathPrefix:ikLocalisePrefix}); } } else { onPause = true; $(this).html("> Jatka"); if(ikLan != "fi" || forceLocal) { $("*[rel^='localize[meastool_buttons.']").localize("rplan", {language: ikLan, pathPrefix:ikLocalisePrefix}); } } $(this).toggleClass("onPause"); ikMapWrap.ikMeasureControl.pause(onPause); }); if(type == "mark") { var tCent = this.map.getCenter().clone(); var curRes = this.map.getResolution(); tCent = tCent.add(lpW*curRes/2 - rpW*curRes/2, 0); var wgsCent = tCent.clone().transform(this.map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326")); this.ikMeasureControl.wgsObj = new wgs84Format(wgsCent); try { this.guiObj.setMarkControlCc(tCent, ""+this.map.getProjection(), true); } catch(e){} try { this.guiObj.setMarkControlWGS(this.ikMeasureControl.wgsObj); } catch(e){} } if(ikLan != "fi" || forceLocal) { $("*[rel^='localize[meastool_buttons.']").localize("rplan", {language: ikLan, pathPrefix:ikLocalisePrefix}); } if($("#ikRightPanel").hasClass("ikHiddenPanel")) { try { this.guiObj.toggleRightPanel(); } catch(e){} } } else { if(type == "mark") { this.ikMeasureControl.markLayer.destroy(); } this.ikMeasureControl.deactivate(); while(this.ikMeasureControl.partMeasPops.length > 0) { this.ikMeasureControl.partMeasPops.pop().destroy(); } if(this.ikMeasureControl.handler.measurePop) { this.ikMeasureControl.handler.measurePop.destroy(); this.ikMeasureControl.handler.measurePop = null; } $("#ikCancelMPButton", ".ikMapGuiContainer").unbind("click"); $("#ikToggleMeasureButton", ".ikMapGuiContainer").unbind("click"); this.ikTrgtCtrl.activate(); this.ikHoverCtrl.activate(); this.ikMeasureControl = null; } }; /************************************************************************************* Mittatyökalun callback. Kutsutaan klikattaessa osa- ja kokonaismatkan pisteitä kartalle. (Myös aluetyökalun kulmat ja koordinaattityökalun pisteet.) evt: OpenLayers.Event - klikkauksen event. *************************************************************************************/ function HandleMeasurements(evt) { if(this.handler.measurePop) { this.handler.measurePop.destroy(); this.handler.measurePop = null; } var stopped = false; if(evt.type == "measure") { if(this.handler.onPause) stopped = true; this.handler.onPause = true; $("#ikToggleMeasureButton", ".ikMapGuiContainer").addClass("onPause"); $("#ikToggleMeasureButton", ".ikMapGuiContainer").html("> Jatka"); if(ikLan != "fi" || forceLocal) { $("*[rel^='localize[meastool_buttons.']").localize("rplan", {language: ikLan, pathPrefix:ikLocalisePrefix}); } } var pointClone = evt.geometry.components[evt.geometry.components.length-1].clone(); var feat = new OpenLayers.Feature.Vector(pointClone); if(this.measType != "area") { if(!this.handler.stoppedDown) { this.corners.push(feat); this.handler.layer.addFeatures([feat]); } else { this.corners.push(false); } } var mAnchor, mPopHTML, mPopOS; if(this.measType == "mark" && !stopped) { var markFeat = feat.clone(); this.markLayer.addFeatures([markFeat]); while(this.markLayer.selectedFeatures.length > 0) { this.markLayer.drawFeature(this.markLayer.selectedFeatures.pop(), "default"); } this.markLayer.selectedFeatures.push(markFeat); this.markLayer.drawFeature(markFeat, "select"); this.marks.push(pointClone); this.markLayer.redraw(); mAnchor = new OpenLayers.LonLat(pointClone.x, pointClone.y); if(!this.processing) { var pc2 = mAnchor.clone().transform(this.map.getProjectionObject(), new OpenLayers.Projection("EPSG:4326")); try { this.map.ikMapWrap.guiObj.setMarkControlCc(mAnchor, this.map.getProjection(), true); } catch(e){} this.wgsObj.set(pc2.lat, pc2.lon, "D"); try { this.map.ikMapWrap.guiObj.setMarkControlWGS(this.wgsObj); } catch(e){}; } this.processing = false; mPopHTML = "P"+this.marks.length+" " mPopOS = {size: new OpenLayers.Size(3,3), pixel: new OpenLayers.Pixel(0,0)}; } else if(this.measType != "mark") { var decimals = 2; if(evt.units == "m") decimals = 0; if(evt.order == 1) { var measurement = evt.measure.toFixed(decimals); var tmpGeom = evt.geometry.clone(); var verts = tmpGeom.getVertices(); if((verts.length > 2 || evt.type == "measure") && !this.handler.stoppedDown) { var cut = verts.length-2; if(evt.type == "measure") cut++; var tmpLine = new OpenLayers.Geometry.LineString([verts[cut-1], verts[cut]]); var measData = this.getBestLength(tmpLine); var decs = 2; if(measData[1] == "m") decs = 0; var tmpX = verts[cut-1].x + ((verts[cut].x - verts[cut-1].x)/2); var tmpY = verts[cut-1].y + ((verts[cut].y - verts[cut-1].y)/2); mAnchor = new OpenLayers.LonLat(tmpX, tmpY); mPopHTML = ""+measData[0].toFixed(decs)+""+measData[1]+" " mPopOS = null; } if(verts.length > 2 || evt.type == "measure") { var meastr = ""+measurement; if(measurement >= 1000) { var spacer = meastr.indexOf('.') - 3; while(spacer > 0) { meastr = (meastr.substring(0, spacer)+" "+meastr.substring(spacer)); spacer -= 3; } } $("#ikMeasurement").html(meastr+" "+evt.units); } } else { var dev = 1; var units = evt.units+"2"; if(evt.units == "m" && evt.measure >= 10000) { dev = 10000; decimals = 2; units = "ha"; } else if(evt.units == "km" && evt.measure <= 100) { dev = 0.01; units = "ha"; } var measure = (evt.measure/dev).toFixed(decimals); var meastr = ""+measure; if(measure >= 1000) { var spacer = meastr.indexOf('.') - 3; while(spacer > 0) { meastr = (meastr.substring(0, spacer)+" "+meastr.substring(spacer)); spacer -= 3; } } $("#ikMeasurement").html(meastr+" "+units); } } if(mPopHTML) { var popSize = this.measType == "mark"?new OpenLayers.Size(25,15):new OpenLayers.Size(60,15); var pMeasPop = new OpenLayers.Popup.Anchored(null, mAnchor, popSize, mPopHTML, mPopOS, false); pMeasPop.setBackgroundColor("transparent"); pMeasPop.setBorder("none"); pMeasPop.panMapIfOutOfView = false; pMeasPop.keepInMap = true; this.map.addPopup(pMeasPop, false); this.partMeasPops.push(pMeasPop); var child = $(pMeasPop.contentDiv).children(".ikMPopTxt"); if(child.width() != popSize.w || child.height() != popSize.h)pMeasPop.setSize(new OpenLayers.Size(child.width(),child.height())); } return true; }; function SetOverlay(layerName, visible) { var overlay = this.map.getLayersByName(layerName); if(overlay[0].visibility != visible) { overlay[0].setVisibility(visible); if(visible) { this.selectedOverlays.push(layerName); } else { this.selectedOverlays = $.grep(this.selectedOverlays, function(b) {return (b != layerName);}); } } }; /************************************************************************************* Pikkukartan tason asettaminen. Jos kontrolli on olemassa, se poistetaan ennen tason asettamista ja lisätään lopuksi uudelleen kartalle. Tässä otetaan huomioon näkyvyys- asetukset ja pikkukartan näkyvyyden senhetkinen tila. layerName: String - asetettavan tason nimi ikNaviMaps-objektissa. *************************************************************************************/ function SetNaviLayer(layerName) { this.map.addControl(this.attrbControl); if(this.settings.naviMap != V_OFF && (!this.minimap || layerName != this.minimap.layers[0].name) && (!this.guiObj || !this.guiObj.settings.mobile)) { var isMax = this.settings.naviMap; if(this.minimap != null) { isMax = this.minimap.minimizeDiv.style.display != 'none'? V_SHOWN:V_HIDDEN; this.minimap.destroy(); this.minimap = null; } var mOpt = {theme: 'http://kartta.pvp.fi/infogis-pvp/theme/infoTrack/style.css'}; if(this.mmLayers[layerName].mapOptions) { $.merge(mOpt, this.mmLayers[layerName].mapOptions); } else { $.merge(mOpt,{ maxResolution: 9783.93961875, maxExtent: new OpenLayers.Bounds(this.settings.naviMapBounds[0],this.settings.naviMapBounds[1],this.settings.naviMapBounds[2],this.settings.naviMapBounds[3]) }); } this.minimap = new OpenLayers.Control.OverviewMap({size: new OpenLayers.Size(180, 150), mapOptions: mOpt}); this.minimap.layers = [this.mmLayers[layerName]]; this.map.addControl(this.minimap); var ikMapWrapper = this; if(isMax == V_SHOWN) this.minimap.maximizeControl(); } else { $(".olControlAttribution").css({right: "25px"}); } }; /************************************************************************************* Pohjakarttana (baseLayer) käytettävän tason asettaminen. Myös kartalla olevat kohteet muunnetaan annettuun projektioon. layerName: String - tason nimi ikMaps-objektissa. layerProjection: String - asetettavan tason projektion nimi. *************************************************************************************/ function SetBaseLayer(layerName, layerProjection) { this.ikBaseName = layerName; //var newBase = this.map.getLayersByName(layerName); var newBase = [ikMaps[layerName].mLayer]; if(newBase.length == 1) { var tmpCenter, tmpRes, tmpBounds; var tmpProj = this.map.getProjectionObject(); var laProj = new OpenLayers.Projection(layerProjection); if(layerProjection) { tmpCenter = this.map.getCenter(); tmpRes = this.map.getResolution(); var oldBase = this.map.baseLayer; this.map.addLayer(newBase[0]); this.map.setBaseLayer(newBase[0]); if(newBase[0].CLASS_NAME == "OpenLayers.Layer.Google") { $(".olLayerGooglePoweredBy").show(); } else { $(".olLayerGooglePoweredBy").hide(); } if(oldBase) { this.map.removeLayer(oldBase); var newZoom = this.map.getZoomForResolution(tmpRes, false); //console.log(newZoom); tmpRes = this.map.getResolution(); var lpW,rpW; try {lpW = this.guiObj.getLeftPanelVisibleWidth();} catch(e){lpW = 0;} try {rpW = this.guiObj.getRightPanelVisibleWidth();} catch(e){rpW = 0;} if(this.guiObj.settings.mobile) lpW = rpW = 0; if(lpW > 0 || rpW > 0) { tmpCenter = tmpCenter.add(lpW*tmpRes/2-rpW*tmpRes/2, 0); } tmpCenter.transform(tmpProj, laProj); if(newBase[0].maxExtent && !newBase[0].maxExtent.containsLonLat(tmpCenter)) { this.map.moveTo(newBase[0].maxExtent.getCenterLonLat(), newZoom, {forceZoomChange: true}); } else { this.map.moveTo(tmpCenter , newZoom, {forceZoomChange: true}); } if(this.ikMeasureControl) { if(this.ikMeasureControl.markLayer && this.ikMeasureControl.markLayer.features.length > 0) { $(this.ikMeasureControl.markLayer.features).each(function() { $(this.geometry).each(function() { this.transform(tmpProj, laProj); }); }); } if(this.ikMeasureControl.handler.layer.features.length > 0) { $(this.ikMeasureControl.handler.layer.features).each(function() { $(this.geometry).each(function() { this.transform(tmpProj, laProj); }); }); } if(this.ikMeasureControl.partMeasPops) { $(this.ikMeasureControl.partMeasPops).each(function() { this.lonlat.transform(tmpProj, laProj); this.updatePosition(); }); } } if(this.areaLayer && this.areaLayer.features.length > 0) { $(this.areaLayer.features).each(function() { $(this.geometry).each(function() { this.transform(tmpProj, laProj); }); }); } if(this.areaLayer)this.areaLayer.redraw(); if(this.routeLayer && this.routeLayer.features.length > 0) { $(this.routeLayer.features).each(function() { $(this.geometry).each(function() { this.transform(tmpProj, laProj); }); }); } if(this.routeLayer)this.routeLayer.redraw(); if(this.pointLayer && this.pointLayer.features.length > 0) { $(this.pointLayer.features).each(function() { $(this.geometry).each(function() { this.transform(tmpProj, laProj); }); }); } if(this.pointLayer)this.pointLayer.redraw(); if(this.usrLayer && this.usrLayer.features.length > 0) { $(this.usrLayer.features).each(function() { $(this.geometry).each(function() { this.transform(tmpProj, laProj); }); }); } else if(this.guiObj && this.guiObj.uPoint) { this.guiObj.uPoint.geometry.transform(tmpProj, laProj); } if(this.usrLayer)this.usrLayer.redraw(); if(this.gpsLayer && this.gpsLayer.features.length > 0) { $(this.gpsLayer.features).each(function() { $(this.geometry).each(function() { this.transform(tmpProj, laProj); }); }); } if(this.gpsLayer)this.gpsLayer.redraw(); if(this.ikMeasureControl) { if(this.ikMeasureControl.markLayer)this.ikMeasureControl.markLayer.redraw(); if(this.ikMeasureControl.handler.layer)this.ikMeasureControl.handler.layer.redraw(); } } } return true; } else { return false; } }; /************************************************************************************* Kutsutaan pohjakarttaa (baseLayer) vaihdettaessa. Kutsuu parent-objektin baseLayerChanged-metodia jos parent on olemassa. *************************************************************************************/ function OnBaseLayerChange() { try{ this.guiObj.baseLayerChanged(); } catch(e){} }; /************************************************************************************* Kohde-popupin hover-handler. Tunnistaa hiiren siirtämisen popupin päälle ja pois. Popupin riveille on oma handler. evt: OpenLayers.Events - hover-event. Palauttaa: true, jotta event bubling ei pysähdy. *************************************************************************************/ function HoverHandlerTrgtPop(evt) { var mapWrap = $("#ikTrgtPopCont").data("ikMapWrap"); if(!mapWrap.rMeasActive) { if(evt.type == "mouseenter") { $(".olMap").css({cursor: "default"}); mapWrap.onTrgtPop = true; } else { mapWrap.onTrgtPop = false; if(mapWrap.selectedParts.length > 0) { mapWrap.ikTrgtCtrl.unselectAll({exceptFeats: mapWrap.selectedParts}); mapWrap.selPids(mapWrap.selectedParts, true); } else if(mapWrap.selectedTrgts.length > 0) { mapWrap.selTrgts(mapWrap.selectedTrgts, true); } else { mapWrap.ikTrgtCtrl.unselectAll(); mapWrap.selAreaWMS.mergeNewParams({"viewParams": ""}); mapWrap.selRouteWMS.mergeNewParams({"viewParams": ""}); mapWrap.selPointWMS.mergeNewParams({"viewParams": ""}); mapWrap.selAreaWMS.setVisibility(false); mapWrap.selRouteWMS.setVisibility(false); mapWrap.selPointWMS.setVisibility(false); } mapWrap.destroyTrgtPop(); } } return true; }; /************************************************************************************* Kohde-popupin rivien hover-handler. Valitsee rivin kohteen ja poistaa valinnan muilta. evt: OpenLayers.Events - hover-event. Palauttaa: true, jotta event bubling ei pysähdy. *************************************************************************************/ function HandlePopTrgtHover(evt) { var mapWrap = $("#ikTrgtPopCont").data("ikMapWrap"); var trgtId = $(this).data("ikpopfeatidx"); var trgtFid = $(this).data("ikpopfid"); if(trgtId && !mapWrap.rMeasActive) { if(evt.type == "mouseenter") { $(this).addClass("bold"); if(trgtFid) { mapWrap.selPids([[trgtId, trgtFid]], true); } else { mapWrap.selTrgts(trgtId, true); } } else { $(this).removeClass("bold"); } } return true; }; /************************************************************************************* Kohde-popupin rivien click-handler. Valitsee rivin kohteen ja poistaa valinnan muilta. *************************************************************************************/ function HandlePopTrgtClick() { var mapWrap = $("#ikTrgtPopCont").data("ikMapWrap"); if(!mapWrap.rMeasActive) { var trgtId = $(this).data("ikpopfeatidx"); var trgtFid = $(this).data("ikpopfid"); var lonlat = $("#ikTrgtPopCont").data("lonlat"); mapWrap.destroyTrgtPop(); try{mapWrap.guiObj.markSelected(trgtId);}catch(e){} $("#ikMapLink").html(""); $(".ikLinkResults").hide(); $("#ikSaveLinkPop").remove(); if(trgtFid) { try{mapWrap.guiObj.loadTrgtInfo(trgtId, trgtFid, lonlat);}catch(e){} mapWrap.selPids([[trgtId, trgtFid]]); } else { if(trgtId != "usrTrgt_1") { try{mapWrap.guiObj.loadTrgtInfo(trgtId, null, lonlat);}catch(e){} } else { try{mapWrap.guiObj.showUsrTrgtMessage();}catch(e){} } mapWrap.selTrgts(trgtId); if(trgtId != "usrTrgt_1") { var trgtData = $("#"+$("#"+trgtId).data("parentid")).data("trgts")[trgtId]; var tmpBbox = trgtData["bbox"]; mapWrap.showBounds(new OpenLayers.Bounds(tmpBbox[0],tmpBbox[1],tmpBbox[2],tmpBbox[3])); } } } }; /************************************************************************************* Kohde-popupin poisto kartalta. Palauttaa: true, jotta event bubling ei pysähdy. *************************************************************************************/ function DestroyTrgtPop() { //this.map.removePopup(this.trgtPop); this.trgtPop.destroy(); this.trgtPop = null; this.onTrgtPop = false; return true; }; /************************************************************************************* SelectFeature controllista perityn IkSelectFeaturen ylikirjoitettu click-metodi. Kutsutaan karttaa klikatessa, työkalun ollessa aktiivisena. feature: OpenLayers.Feature(.Vector) - IkSelectFeaturessa featuren valinta on muutettu poimimaan feature geometrian perusteella, alkuperäisen renderöijältä pyy- tämisen sijaan. Klikkaukselle on annettu pieni toleranssi. Jos kohteita on pisteessä useampi, tämä on päällimmäisenä ollut. *************************************************************************************/ function OnFeatureSelect(feature) { var inSel = false; $("#ikMapLink").html(""); $(".ikLinkResults").hide(); $("#ikSaveLinkPop").remove(); if(this.map.ikMapWrap.rMeasActive && this.map.ikMapWrap.selectedParts.length > 0) { if($.inArray(feature.attributes.partid, this.map.ikMapWrap.selectedParts) < 0) { this.map.ikMapWrap.selectedParts.push(""+feature.attributes.partid); } else { this.map.ikMapWrap.selectedParts = $.grep(this.map.ikMapWrap.selectedParts, function(f) { return (feature.attributes.partid != f); }); inSel = true; } } else if(this.map.ikMapWrap.selectedParts.length > 0 && $.inArray(feature.attributes.partid, this.map.ikMapWrap.selectedParts) > -1) { inSel = true; this.map.ikMapWrap.selectedParts = []; } else { this.map.ikMapWrap.selectedParts = [""+feature.attributes.partid]; } var panel = $("#ikInfoPanel"); if(panel.length == 0)panel = $("#ikAltInfoPanel"); if(panel.length != 0) { $(panel).each(function() { $(this).remove(); }); } if(this.map.ikMapWrap.trgtPop) { this.map.ikMapWrap.destroyTrgtPop(); } if(!inSel) { if(feature.attributes.partid != "usrTrgt_1") { try{this.map.ikMapWrap.guiObj.loadTrgtInfo(feature.attributes.objectid, feature.attributes.partid);}catch(e){} } else { try{this.map.ikMapWrap.guiObj.showUsrTrgtMessage();}catch(e){} } } try{this.map.ikMapWrap.guiObj.markSelected(feature.attributes.objectid);}catch(e){} this.map.ikMapWrap.selectedTrgts = []; var selected = (OpenLayers.Util.indexOf( feature.layer.selectedFeatures, feature) > -1); if(inSel) { this.unselect(feature); } else { this.unselectAll({except: feature, exceptFeats: this.map.ikMapWrap.selectedParts}); if(!selected)this.select(feature); } if(this.map.ikMapWrap.rMeasActive) this.map.ikMapWrap.measureRoutes(); }; /************************************************************************************* Kohteiden valinta hover-työkalulla. Kutsutaan hiiren ollessa pysähdyksissä kartalla hover-työkalulle annetun viiveen verran. evt: OpenLayers.Events - hover-event. *************************************************************************************/ function OnHoverIn(evt) { if(!this.map.ikMapWrap.onTrgtPop) { if(this.map.ikMapWrap.TrgtsPopTimerId != null) { window.clearTimeout(this.map.ikMapWrap.TrgtsPopTimerId); this.map.ikMapWrap.TrgtsPopTimerId = null; } if(this.map.ikMapWrap.TmpSelTimerId != null) { window.clearTimeout(this.map.ikMapWrap.TmpSelTimerId); this.map.ikMapWrap.TmpSelTimerId = null; } var tmpLonLat = this.map.getLonLatFromPixel(evt.xy.clone()); this.map.ikMapWrap.loadTrgtHover(tmpLonLat); } }; /******************************************************************************************* Kutsutaan hiirtä liikutettaessa, kun Hover-työkalu on aktiivisena. Kutsuu ajastimella DelayedUnselect- ja DelayedPopClose-functioita. evt: OpenLayers.Events - mousemove-event. *******************************************************************************************/ function OnHoverOut(evt) { if(this.lastHover && evt.xy.distanceTo(this.lastHover) > 7) { this.map.ikMapWrap.TmpSelTimerId = window.setTimeout( OpenLayers.Function.bind(this.map.ikMapWrap.delayedUnselect, this.map.ikMapWrap, null), 200 ); this.map.ikMapWrap.TrgtsPopTimerId = window.setTimeout( OpenLayers.Function.bind(this.map.ikMapWrap.delayedPopClose, this.map.ikMapWrap, null), 200 ); } }; /******************************************************************************************* Hover-työkalulla valittujen kohteiden valinnan poisto. Kutsutaan normaalisti ajastimella. *******************************************************************************************/ function DelayedUnselect() { if(this.TmpSelTimerId != null && !this.onTrgtPop && this.lastSel != null && this.ikHoverCtrl.lastHover != null) { window.clearTimeout(this.TmpSelTimerId); this.TmpSelTimerId = null; var mouse = this.map.controls[1].lastXy; var tmpLonLat = this.map.getLonLatFromPixel(mouse); var tmpSFHandler = this.ikTrgtCtrl; var mapWrap = this; var countySel = (this.guiObj && this.guiObj.selCounty)? this.guiObj.selCounty:""; var themeSel = (this.guiObj && this.guiObj.selTheme)? this.guiObj.selTheme:""; $.ajax({ type: "POST", dataType: "json", url: "http://kartta.pvp.fi/infogis-pvp/php/trgthover.json.php?customer=infogis-pvp", async: true, data: "lan="+ikLan+"&clientId="+ikClient+"&county="+countySel+"&theme="+themeSel+"&reso="+this.map.getResolution()+"&proj="+this.map.getProjection()+"&coord=["+tmpLonLat.lat+","+tmpLonLat.lon+"]&trgtsOnMap=["+this.trgtsOnMap.join(",")+"]&partsOnMap=["+this.partsOnMap.join(",")+"]", success: function(json) { if(json && json != null) { mapWrap.handleTrgtHover(json, tmpLonLat, mapWrap, true); mapWrap.map.ikMapWrap.TmpSelTimerId = window.setTimeout( OpenLayers.Function.bind(mapWrap.delayedUnselect, mapWrap, null), 200 ); return true; } else { $(".olMap").css({cursor: "default"}); mapWrap.lastSel = null; mapWrap.ikHoverCtrl.lastHover = null; if(mapWrap.selectedParts && mapWrap.selectedParts.length > 0) { mapWrap.selPids(mapWrap.selectedParts, true); } else if(mapWrap.selectedTrgts.length > 0) { mapWrap.selTrgts(mapWrap.selectedTrgts, true); } else { mapWrap.ikTrgtCtrl.unselectAll(); mapWrap.selAreaWMS.mergeNewParams({"viewParams": ""}); mapWrap.selRouteWMS.mergeNewParams({"viewParams": ""}); mapWrap.selPointWMS.mergeNewParams({"viewParams": ""}); } if(mapWrap.tmpSelRouteWMS.visibility) { mapWrap.tmpSelRouteWMS.mergeNewParams({"viewParams":""}); mapWrap.tmpSelRouteWMS.setVisibility(false); } } }, error: function (XMLHttpRequest, textStatus, errorThrown) { mapWrap.map.ikMapWrap.TmpSelTimerId = window.setTimeout( OpenLayers.Function.bind(mapWrap.delayedUnselect, mapWrap, null), 200 ); return true; } }); } }; /******************************************************************************************* Kohde-popupin sulkeminen. Kutsutaan normaalisti ajastimella. *******************************************************************************************/ function DelayedPopClose() { if(this.TrgtsPopTimerId != null) { window.clearTimeout(this.TrgtsPopTimerId); this.TrgtsPopTimerId = null; if(this.trgtPop && !this.onTrgtPop) { this.destroyTrgtPop(); } } }; /******************************************************************************************* Valitse kohteita ObjectId-arvon perusteella. trgts: String || [String] - objectid / object-taulukko. keepOlds: Boolean - true, jos valinta on vain väliaikainen (esim. hover-toiminnolla). Jos arvo on false tai määrittelemättä, trgts-parametrin arvo(t) talletetaan muuttujaan, jonka avulla kohteet pysyvät valittuna myös zoom-tasoa vaihdettaessa. *******************************************************************************************/ function SelTrgts(trgts, keepOlds) { var mapWrapObj = this; var trgtArray = $.isArray(trgts)? trgts:[trgts]; if(trgtArray && trgtArray.length > 0) { if(!keepOlds) { mapWrapObj.selectedParts = []; mapWrapObj.selectedTrgts = trgtArray; } var feats = []; var notInWFS = []; $(trgtArray).each(function() { var objId = ""+this; try { var layers = mapWrapObj.ikTrgtCtrl.layers || [mapWrapObj.ikTrgtCtrl.layer]; for(var l in layers) { var layer = layers[l]; var lFeats = layer.getFeaturesByAttribute("objectid", objId); if(lFeats && lFeats.length > 0) { $.merge(feats, lFeats); } else { notInWFS.push(objId); } } } catch(err) {} }); this.ikTrgtCtrl.unselectAll({exceptFeats: feats}); $(feats).each(function() { if(this && this.layer && $.inArray(this, this.layer.selectedFeatures) <0) { mapWrapObj.ikTrgtCtrl.select(this); } }); var params = ""; var hasSel = false; if(notInWFS.length > 0) { params = "wmscustomer:"+wmscustomer+";oids:"+notInWFS.join("\\,"); hasSel = true; } this.selAreaWMS.mergeNewParams({"viewParams":params}); this.selRouteWMS.mergeNewParams({"viewParams":params}); this.selPointWMS.mergeNewParams({"viewParams":params}); this.selAreaWMS.setVisibility(hasSel); this.selRouteWMS.setVisibility(hasSel); this.selPointWMS.setVisibility(hasSel); if(this.rMeasActive)this.toggleRouteMeasure(); } }; /******************************************************************************************* Valitse kohteita PartID-arvon perusteella. pids: String || [String] - partid / partid-taulukko. keepOlds: Boolean - true, jos valinta on vain väliaikainen (esim. hover-toiminnolla). Jos arvo on false tai määrittelemättä, pids-parametrin arvo(t) talletetaan muuttujaan, jonka avulla kohteet pysyvät valittuna myös zoom-tasoa vaihdettaessa. *******************************************************************************************/ function SelPids(pids, keepOlds) { var mapWrapObj = this; var pidArray = $.isArray(pids)? pids:[pids]; if(pidArray && pidArray.length > 0) { if(!keepOlds) { this.selectedParts = pidArray; this.selectedTrgts = []; } var fWMS = []; var feats = []; $(pidArray).each(function() { if(!$.isArray(this)) { var partId = ""+this; try { var layers = mapWrapObj.ikTrgtCtrl.layers || [mapWrapObj.ikTrgtCtrl.layer]; for(var l in layers) { var layer = layers[l]; var lFeats = layer.getFeaturesByAttribute("partid", partId); if(lFeats)$.merge(feats, lFeats); } } catch(err) {} } else { fWMS.push(this[1]); } }); this.ikTrgtCtrl.unselectAll({exceptFeats: feats}); $(feats).each(function() { if(this && this.layer && $.inArray(this, this.layer.selectedFeatures) <0) { mapWrapObj.ikTrgtCtrl.select(this); } }); if(!this.lastSel || this.lastSel.join("") != fWMS.join("")) { this.lastSel = fWMS; var pidStr = ""; var hasSel = false; if(fWMS.length > 0) { pidStr = "wmscustomer:"+wmscustomer+";partids:"+fWMS.join("\\,"); hasSel = true; } this.selAreaWMS.mergeNewParams({"viewParams":pidStr}); this.selRouteWMS.mergeNewParams({"viewParams":pidStr}); this.selPointWMS.mergeNewParams({"viewParams":pidStr}); this.selAreaWMS.setVisibility(hasSel); this.selRouteWMS.setVisibility(hasSel); this.selPointWMS.setVisibility(hasSel); } } }; /******************************************************************************************* Keskitä annetun alueen keskelle. Jos alueen korkeus ja leveys eivät ole nolla, kutsuu ZoomToTrgts-functiota. Muutosten myötä käynyt hieman turhaksi. bounds: OpenLayers.Bounds - alue, johon kohdistetaan *******************************************************************************************/ function ShowBounds(bounds) { try { var tmpBounds = bounds.clone(); var toProj = this.map.getProjectionObject(); tmpBounds.transform(new OpenLayers.Projection("EPSG:2393"), toProj);//!!! Täällä on vakiona asetettu projektio! if(this.map.baseLayer.ikAutoChangeLayer && !this.map.baseLayer.maxExtent.containsBounds(tmpBounds)) { tmpBounds.transform(toProj, new OpenLayers.Projection(ikMaps[this.map.baseLayer.ikAutoChangeLayer].mProj));//!!! Täällä on vakiona asetettu projektio! this.guiObj.selectMap(this.map.baseLayer.ikAutoChangeLayer, true); } if(tmpBounds.getWidth() == 0 && tmpBounds.getHeight() == 0) { this.map.moveTo(tmpBounds.getCenterLonLat()); } else { this.zoomToTrgts(tmpBounds); } } catch(err) {} }; /******************************************************************************************* Keskitä kohteisiin. Jos kohde ei mahdu ruudulle, karttaa loitonnetaan. trgtsBounds: OpenLayers.Bounds - alue, johon keskitetään. *******************************************************************************************/ function ZoomToTrgts(trgtsBounds) { var lpW,rpW; try {lpW = this.guiObj.getLeftPanelVisibleWidth();} catch(e){lpW = 0;} try {rpW = this.guiObj.getRightPanelVisibleWidth();} catch(e){rpW = 0;} if(this.guiObj.settings.mobile) lpW = rpW = 0; if(lpW > 0 || rpW > 0 ) { var mapSize = this.map.getSize(); var trueW = mapSize.w - lpW - rpW; var zLvl = this.map.getZoom(); var zoomedUp = false; var minRes = this.map.baseLayer.minResolution; var maxRes = this.map.baseLayer.maxResolution; var fits = false; do { var mapRes = this.map.getResolutionForZoom(zLvl); var calcW = trueW * mapRes; var calcH = mapSize.h * mapRes; if(mapRes < maxRes && (trgtsBounds.getWidth() >= calcW || trgtsBounds.getHeight() >= calcH)) { zLvl--; zoomedUp = true; } else { fits = true; } }while(!fits); this.map.setCenter(trgtsBounds.getCenterLonLat(), zLvl); } else if(this.map.getZoomForExtent(trgtsBounds, false) <= this.map.getZoom()) { this.map.zoomToExtent(trgtsBounds, false); } else { this.map.moveTo(trgtsBounds.getCenterLonLat()); } }; /******************************************************************************************* Lisää kohteita oid-parametrin perusteella. oids: String || [String] - kohteen / kohteiden objectId. *******************************************************************************************/ function AddFeatures(oids) { var trgtArray = $.isArray(oids)? oids:[oids]; if(trgtArray && trgtArray.length > 0) { var mapWrap = this; $.merge(this.trgtsOnMap, trgtArray); var oidStr = this.trgtsOnMap.length > 0? ";oids:"+this.trgtsOnMap.join("\\,"):""; var pidStr = this.partsOnMap.length > 0? ";partids:"+this.partsOnMap.join("\\,"):""; var vParams = "wmscustomer:"+wmscustomer+oidStr+pidStr; this.areaWMS.mergeNewParams({"viewParams":vParams}); this.routeWMS.mergeNewParams({"viewParams":vParams}); this.pointWMS.mergeNewParams({"viewParams":vParams}); this.areaWMS.setVisibility(true); this.routeWMS.setVisibility(true); this.pointWMS.setVisibility(true); } return false; }; /******************************************************************************************* Poista kohteet kartalta oid-parametrin perusteella. oids: String || [String] - kohteen / kohteiden objectId. *******************************************************************************************/ function RemFeatures(oids) { var trgtArray = $.isArray(oids)? oids:[oids]; if(trgtArray && trgtArray.length > 0) { this.trgtsOnMap = separateArray(trgtArray, this.trgtsOnMap); var selOidsl = this.selectedTrgts.length; var selPidsl = this.selectedParts.length; var mapWrap = this; mapWrap.selectedParts = $.grep(mapWrap.selectedParts, function(part) { if($.isArray(part)) {; if(part[1] == mapWrap.lastSel)mapWrap.lastSel = null; return ($.inArray(part[0], trgtArray) < 0) } return true; }); this.selectedTrgts = separateArray(trgtArray, this.selectedTrgts); var vParams = ""; var hasTrgts = false; if(this.trgtsOnMap.length > 0 || this.partsOnMap.length > 0) { var oidStr = this.trgtsOnMap.length > 0? ";oids:"+this.trgtsOnMap.join("\\,"):""; var pidStr = this.partsOnMap.length > 0? ";partids:"+this.partsOnMap.join("\\,"):""; var vParams = "wmscustomer:"+wmscustomer+oidStr+pidStr; hasTrgts = true; } this.areaWMS.mergeNewParams({"viewParams": vParams}); this.routeWMS.mergeNewParams({"viewParams": vParams}); this.pointWMS.mergeNewParams({"viewParams": vParams}); this.areaWMS.setVisibility(hasTrgts); this.routeWMS.setVisibility(hasTrgts); this.pointWMS.setVisibility(hasTrgts); if(this.selectedParts.length != selPidsl || this.selectedTrgts.length != selOidsl) { var params = ""; var hasSel = false; if(this.selectedTrgts.length > 0 && this.selectedTrgts.length != selOidsl) { params = "oids:"+this.selectedTrgts.join("\\,"); hasSel = true; } else if(this.selectedParts.length > 0 && this.selectedParts.length != selPidsl) { var pids = []; $(this.selectedParts).each(function() { if($.isArray(this)) { pids.push(this[1]); } else { pids.push(this); } }); params = "wmscustomer:"+wmscustomer+";partids:"+pids.join("\\,"); hasSel = true; } try{this.guiObj.showInfoPanel(false);}catch(e){} this.selAreaWMS.mergeNewParams({"viewParams": params}); this.selRouteWMS.mergeNewParams({"viewParams": params}); this.selPointWMS.mergeNewParams({"viewParams": params}); this.selAreaWMS.setVisibility(hasSel); this.selRouteWMS.setVisibility(hasSel); this.selPointWMS.setVisibility(hasSel); } } return false; }; /******************************************************************************************* Lisää kohteita oid-parametrin perusteella. oids: String || [String] - kohteen / kohteiden objectId. *******************************************************************************************/ function AddParts(pids) { var pidArray = $.isArray(pids)? pids:[pids]; if(pidArray && pidArray.length > 0) { var mapWrap = this; $.merge(this.partsOnMap, pidArray); var oidStr = this.trgtsOnMap.length > 0? ";oids:"+this.trgtsOnMap.join("\\,"):""; var pidStr = this.partsOnMap.length > 0? ";partids:"+this.partsOnMap.join("\\,"):""; var vParams = "wmscustomer:"+wmscustomer+oidStr+pidStr; this.areaWMS.mergeNewParams({"viewParams":vParams}); this.routeWMS.mergeNewParams({"viewParams":vParams}); this.pointWMS.mergeNewParams({"viewParams":vParams}); this.areaWMS.setVisibility(true); this.routeWMS.setVisibility(true); this.pointWMS.setVisibility(true); } return false; }; /******************************************************************************************* Poista kohteet kartalta oid-parametrin perusteella. oids: String || [String] - kohteen / kohteiden objectId. *******************************************************************************************/ function RemParts(pids) { var pidArray = $.isArray(pids)? pids:[pids]; if(pidArray && pidArray.length > 0) { this.partsOnMap = separateArray(pidArray, this.partsOnMap); var selOidsl = this.selectedTrgts.length; var selPidsl = this.selectedParts.length; var mapWrap = this; if(mapWrap.lastSel && pidArray.toString() == mapWrap.lastSel.toString())mapWrap.lastSel = null; mapWrap.selectedParts = $.grep(mapWrap.selectedParts, function(part) { if($.isArray(part)) {; if(part[1] == mapWrap.lastSel)mapWrap.lastSel = null; return ($.inArray(part[1], pidArray) < 0) } return true; }); var vParams = ""; var hasTrgts = false; if(this.trgtsOnMap.length > 0 || this.partsOnMap.length > 0) { var oidStr = this.trgtsOnMap.length > 0? ";oids:"+this.trgtsOnMap.join("\\,"):""; var pidStr = this.partsOnMap.length > 0? ";partids:"+this.partsOnMap.join("\\,"):""; var vParams = "wmscustomer:"+wmscustomer+oidStr+pidStr; hasTrgts = true; } this.areaWMS.mergeNewParams({"viewParams": vParams}); this.routeWMS.mergeNewParams({"viewParams": vParams}); this.pointWMS.mergeNewParams({"viewParams": vParams}); this.areaWMS.setVisibility(hasTrgts); this.routeWMS.setVisibility(hasTrgts); this.pointWMS.setVisibility(hasTrgts); if(this.selectedParts.length != selPidsl || this.selectedTrgts.length != selOidsl) { var params = ""; var hasSel = false; if(this.selectedTrgts.length > 0 && this.selectedTrgts.length != selOidsl) { params = "oids:"+this.selectedTrgts.join("\\,"); hasSel = true; } else if(this.selectedParts.length > 0 && this.selectedParts.length != selPidsl) { var pids = []; $(this.selectedParts).each(function() { if($.isArray(this)) { pids.push(this[1]); } else { pids.push(this); } }); params = "wmscustomer:"+wmscustomer+";partids:"+pids.join("\\,"); hasSel = true; } try{this.guiObj.showInfoPanel(false);}catch(e){} this.selAreaWMS.mergeNewParams({"viewParams": params}); this.selRouteWMS.mergeNewParams({"viewParams": params}); this.selPointWMS.mergeNewParams({"viewParams": params}); this.selAreaWMS.setVisibility(hasSel); this.selRouteWMS.setVisibility(hasSel); this.selPointWMS.setVisibility(hasSel); } } return false; }; /******************************************************************************************* Poista kaikki kohteet kartalta. *******************************************************************************************/ function RemAllFeatures() { if(this.trgtsOnMap.length > 0) { this.selectedParts = []; this.partsOnMap = []; this.trgtsOnMap = []; this.selectedTrgts = []; this.areaWMS.mergeNewParams({"viewParams":""}); this.selAreaWMS.mergeNewParams({"viewParams":""}); this.routeWMS.mergeNewParams({"viewParams":""}); this.selRouteWMS.mergeNewParams({"viewParams":""}); this.pointWMS.mergeNewParams({"viewParams":""}); this.selPointWMS.mergeNewParams({"viewParams":""}); this.areaWMS.setVisibility(false); this.routeWMS.setVisibility(false); this.pointWMS.setVisibility(false); this.selAreaWMS.setVisibility(false); this.selRouteWMS.setVisibility(false); this.selPointWMS.setVisibility(false); try{this.guiObj.showRouteMeasureTool(false);}catch(e){} } }; /******************************************************************************************* Poimi valittujen kohteiden fid-parametrit. Palauttaa: [String] - valittujen kohteiden Feature-Id -parametrit. *******************************************************************************************/ function GetSelectedFids() { var fids = []; for(var i in this.selectedParts) { var feats = []; var mapWrap = this; $(feats).each(function() { fids.push(this.attributes.partid); }); } return fids; }; /******************************************************************************************* Ensimmäisen taulukon sisällön poistaminen toisesta. a: [] - taulukko, jonka elementit poistetaan toisen parametrin taulukosta. fromB: [] - taulukko, josta ensimmäisen parametrin elementit poistetaan. Palauttaa: Kopion fromB-parametrin taulukosta, josta on poistettu a-parametrin elementit. *******************************************************************************************/ function separateArray(a, fromB) { var comp = a.slice(0); var result = fromB.slice(0); while(comp.length > 0 && result.length > 0) { var tmp = comp.pop(); result = $.grep(result, function(b) {return (b != tmp);}); } return result; }; /******************************************************************************************* Lataus-listener. Kutsuu ShowLoad-functiota. *******************************************************************************************/ function IkMapLoadListener(type) { var start = (type === "refresh"); this.showLoad(start); return true; }; /******************************************************************************************* Latausilmoituksen toggle. *******************************************************************************************/ function ShowLoad(show) { var oldState = this.loadQueLength; if(show) { this.loadQueLength++; } else { this.loadQueLength--; } if(this.loadQueLength <= 0) { $("#ikLoadingGif").hide(); }else if(oldState == 0) { $("#ikLoadingGif").show(); } if(this.loadQueLength < 0) this.loadQueLength = 0; return true; }; /******************************************************************************************* Attribution-tekstin Ajax-lataus. *******************************************************************************************/ function LoadAttribution(options) { var mapWrap = this; $.ajax({ type: "POST", dataType: "text", url: "http://kartta.pvp.fi/infogis-pvp/php/getcopyright.php?customer=infogis-pvp", async: true, data: "lan="+ikLan+"&clientId="+ikClient+"&layer="+options.layer+"&x="+options.x+"&y="+options.y+"&zoom="+options.zoom+"&resolution="+options.resolution, success: function(text) { mapWrap.handleAttribution(text, mapWrap); }, error: function (XMLHttpRequest, textStatus, errorThrown) { return true; } }); }; /******************************************************************************************* Ladatun attribution-tekstin käsittely. attrb: text-String - näytettävä attribution. mapWrap: infokartta - karttaelementin sisältävä objekti. *******************************************************************************************/ function HandleAttribution(attrb, mapWrap) { if(attrb) { mapWrap.map.baseLayer.attribution = attrb; mapWrap.attrbControl.updateAttribution(); } }; function LoadTrgtHover(lonlat) { var mapWrap = this; var countySel = (this.guiObj && this.guiObj.selCounty)? this.guiObj.selCounty:""; var themeSel = (this.guiObj && this.guiObj.selTheme)? this.guiObj.selTheme:""; this.hoverLoad = $.ajax({ type: "POST", timeout: 15000, dataType: "json", url: "http://kartta.pvp.fi/infogis-pvp/php/trgthover.json.php?customer=infogis-pvp", async: true, data: "lan="+ikLan+"&clientId="+ikClient+"&county="+countySel+"&theme="+themeSel+"&reso="+this.map.getResolution()+"&proj="+this.map.getProjection()+"&coord=["+lonlat.lat+","+lonlat.lon+"]&trgtsOnMap=["+this.trgtsOnMap.join(",")+"]&partsOnMap=["+this.partsOnMap.join(",")+"]&mobile="+this.guiObj.settings.mobile, success: function(json) { mapWrap.handleTrgtHover(json, lonlat, mapWrap); }, error: function (XMLHttpRequest, textStatus, errorThrown) { return true; } }); }; /******************************************************************************************* *******************************************************************************************/ function HandleTrgtHover(json, lonlat, ikMapWrap, noPop) { var tolerance = ikMapWrap.map.getResolution() * 10; var layers = ikMapWrap.ikHoverCtrl.layers || [ikMapWrap.ikHoverCtrl.layer]; var features = []; var trgtsHtml = ""; for(var l in layers) { var layer = layers[l]; for(var f in layer.features) { var feat = layer.features[f]; if(feat.geometry.atPoint(lonlat, tolerance, tolerance)) { features.push(feat); } } } if(features.length > 0) { ikMapWrap.ikTrgtCtrl.unselectAll({ exceptFeats: ikMapWrap.selectedParts, exceptOids: ikMapWrap.selectedTrgts }); var tmpSFHandler = ikMapWrap.ikTrgtCtrl; var tmpFeatArray = []; var tmpGeom = new OpenLayers.Geometry.Point(lonlat.lon, lonlat.lat); var numeration = 0; var tmpPids = []; for(var i in features) { var feature = features[i]; var dist = tolerance; if(feature.layer.name != "points" && feature.layer.name != "user") { dist = tolerance / 2; } var areaContains = false; if(feature.layer.name == "areas") { for(var o=0; o 0)numeration++; } else if(feature.layer.name == "routes") { tmpFeatArray[feature.attributes.objectid].iklength += parseFloat(feature.attributes.iklength); } var part = feature.attributes["partdescription-"+ikLan] || feature.attributes["partdescription-en"] || feature.attributes.partdescription; if(part) { tmpFeatArray[feature.attributes.objectid].parts.push(""+part); tmpFeatArray[feature.attributes.objectid].fidForPart.push(""+feature.attributes.partid); if(part.length > 0)numeration++; } if($.inArray(feature, feature.layer.selectedFeatures) < 0)tmpPids.push(feature.attributes.partid);//tmpSFHandler.select(feature); } } if(tmpPids.length > 0) ikMapWrap.selPids(tmpPids, true); for(var oid in tmpFeatArray) { var tmpFeat = tmpFeatArray[oid]; var len = tmpFeat.iklength; if(len != "") { var units = "m"; var decs = 0; if(len >= 1000) { len = len / 1000; units = "km"; decs = 2; } len = len.toFixed(decs)+units; } if(tmpFeat.ikdescription.length > 0)trgtsHtml += "" + tmpFeat.ikdescription+" "+ len +""; if(tmpFeat.parts.length > 0) { for(var idx = 0; idx < tmpFeat.parts.length; idx++) { if(tmpFeat.parts[idx].length > 0)trgtsHtml += "" + tmpFeat.parts[idx]+""; } } } } if(json && json != null) { $(".olMap").css({cursor: "pointer"}); var tmpSelParts = []; for(var oid in json) { var parent = json[oid]; var desc = parent["ikdescription-"+ikLan] || parent["ikdescription-en"] || parent.ikdescription; if(desc) trgtsHtml += "" + desc +""; if(parent["parts"]) { var parts = parent["parts"]; for(var part in parts) { var child = parts[part]; tmpSelParts.push([oid, part]); var pDesc = child["partdescription-"+ikLan] || child["partdescription-en"] || child.partdescription; if(parent["showParts"] && pDesc)trgtsHtml += "" + pDesc +""; } } } var pids = []; $(tmpSelParts).each(function() { if($.isArray(this)) { pids.push(this[1]); } else { pids.push(this); } }); if(!ikMapWrap.lastSel || ikMapWrap.lastSel.join("") != pids.join("")) { ikMapWrap.lastSel = pids; var pidStr = ""; var hasSel = false; if(pids.length > 0) { pidStr = "wmscustomer:"+wmscustomer+";partids:"+pids.join("\\,"); hasSel = true; } ikMapWrap.selAreaWMS.mergeNewParams({"viewParams":pidStr}); ikMapWrap.selAreaWMS.setVisibility(hasSel); if(ikMapWrap.rMeasCreated && ikMapWrap.rMeasActive) { ikMapWrap.tmpSelRouteWMS.mergeNewParams({"viewParams":pidStr}); ikMapWrap.tmpSelRouteWMS.setVisibility(true); } else { ikMapWrap.selRouteWMS.mergeNewParams({"viewParams":pidStr}); ikMapWrap.selRouteWMS.setVisibility(hasSel); } ikMapWrap.selPointWMS.mergeNewParams({"viewParams":pidStr}); ikMapWrap.selPointWMS.setVisibility(hasSel); } } if(!noPop && trgtsHtml.length > 0) { if(ikMapWrap.trgtPop)ikMapWrap.destroyTrgtPop(); var mapW = $(".ikMapGuiContainer").width(); var mapH = $(".ikMapGuiContainer").height(); ikMapWrap.ikHoverCtrl.lastHover = ikMapWrap.map.getPixelFromLonLat(lonlat);//evt.xy; var top = ikMapWrap.ikHoverCtrl.lastHover.y; if(mapH/2 < top) top -= 250; var left = (ikMapWrap.ikHoverCtrl.lastHover.x+10)+"px"; var right = ""; if(mapW/2 < ikMapWrap.ikHoverCtrl.lastHover.x) {//left -= 340; left = ""; right = (mapW-ikMapWrap.ikHoverCtrl.lastHover.x+10)+"px"; } $("
"+trgtsHtml+"
").appendTo("#"+ikMapWrap.settings.containerId).css({ top: top+"px", backgroundColor: "rgb(255,255,221)", position: "absolute", left: left, right: right }); if(ikMapWrap.guiObj.settings.mobile) $(".ikPopTrgt").css({"font-size": "0.8em", "margin-bottom": "3px"}); $("#ikTrgtPopCont").data("lonlat", lonlat); var numeration = $("#ikTrgtPopCont").children(".ikPopTrgt").length; if(($(".ikPopTrgt:last").outerHeight() * numeration) < 250){ var popH = $(".ikPopTrgt:last").outerHeight() * numeration; var popTop = ikMapWrap.ikHoverCtrl.lastHover.y; if(mapH/2 < popTop) popTop -= popH; $("#ikTrgtPopCont").css({height:popH+"px", top:popTop+"px"}); } else { $("#ikTrgtPopCont").css({height:"250px", overflow: "auto"}); } ikMapWrap.trgtPop = { destroy: function() { $("#ikTrgtPopCont").remove(); } }; $("#ikTrgtPopCont").data("ikMapWrap", ikMapWrap); if(ikMapWrap.settings.hoverPopsActive){ $("#ikTrgtPopCont").bind("mouseenter mouseleave", ikMapWrap.hoverHandlerTrgtPop); $("#ikTrgtPopCont").bind("hover", function() {return false;}); $(".ikPopTrgt").bind("mouseenter mouseleave", ikMapWrap.handlePopTrgtHover); $(".ikPopTrgt").bind("click", ikMapWrap.handlePopTrgtClick); } } }; function LoadTrgtClick(lonlat) { this.lastSel = null; var mapWrap = this; var countySel = (this.guiObj && this.guiObj.selCounty)? this.guiObj.selCounty:""; var themeSel = (this.guiObj && this.guiObj.selTheme)? this.guiObj.selTheme:""; $.ajax({ type: "POST", timeout: 15000, dataType: "text", url: "http://kartta.pvp.fi/infogis-pvp/php/trgtclick.php?customer=infogis-pvp", async: true, data: "rMeasOn="+(this.rMeasCreated && this.rMeasActive)+"&lan="+ikLan+"&clientId="+ikClient+"&county="+countySel+"&theme="+themeSel+"&reso="+this.map.getResolution()+"&proj="+this.map.getProjection()+"&coord=["+lonlat.lat+","+lonlat.lon+"]&trgtsOnMap=["+this.trgtsOnMap.join(",")+"]&partsOnMap=["+this.partsOnMap.join(",")+"]&mobile="+this.guiObj.settings.mobile, success: function(txt) { mapWrap.handleTrgtClick(txt, mapWrap, lonlat); }, error: function (XMLHttpRequest, textStatus, errorThrown) { return true; } }); }; function HandleTrgtClick(txt, ikMapWrap, lonlat) { if(txt && txt.length > 0) { window.clearTimeout(ikMapWrap.TmpSelTimerId); ikMapWrap.TmpSelTimerId = null; ikMapWrap.selectedTrgts = []; var braker = txt.indexOf(':'); var arr = [txt.substring(0, braker), txt.substring(braker+1, txt.length-1)]; var wasSelected = false; ikMapWrap.selectedParts = $.grep(ikMapWrap.selectedParts, function(part) { if($.isArray(part) && part[0] == arr[0] && part[1] == arr[1]) { wasSelected = true; return false; } else { return true; } }); if(!ikMapWrap.rMeasCreated || !ikMapWrap.rMeasActive) { ikMapWrap.selectedParts = []; } if(!wasSelected) { ikMapWrap.ikTrgtCtrl.unselectAll(); ikMapWrap.selectedParts.push(arr); try{ikMapWrap.guiObj.loadTrgtInfo(arr[0], arr[1], lonlat);}catch(e){} try{ikMapWrap.guiObj.markSelected(arr[0]);}catch(e){} } else { $(".ikSelectedOnList").removeClass("ikSelectedOnList"); $("#"+arr[0]+">.ttRowTitle>.ikTrgtName").removeClass("ikSelectedOnList"); $("#"+arr[0]+">.usrTRowTitle>.ikUsrTrgtName").removeClass("ikSelectedOnList"); $("#"+arr[0]+">.ttRowTitle>.ikTrgtName", "#ikSearchResultCont").removeClass("ikSelectedOnList"); } ikMapWrap.selectedTrgts = []; var pids = []; $(ikMapWrap.selectedParts).each(function() { if($.isArray(this)) { pids.push(this[1]); } else { pids.push(this); } }); if(ikMapWrap.tmpSelRouteWMS.visibility) { ikMapWrap.tmpSelRouteWMS.mergeNewParams({"viewParams":""}); ikMapWrap.tmpSelRouteWMS.setVisibility(false); } if(ikMapWrap.rMeasCreated && ikMapWrap.rMeasActive) ikMapWrap.measureRoutes(); var pidStr = ""; var hasSel = false; if(pids.length > 0) { pidStr = "wmscustomer:"+wmscustomer+";partids:"+pids.join("\\,"); hasSel = true; } ikMapWrap.selAreaWMS.mergeNewParams({"viewParams":pidStr}); ikMapWrap.selRouteWMS.mergeNewParams({"viewParams":pidStr}); ikMapWrap.selPointWMS.mergeNewParams({"viewParams":pidStr}); ikMapWrap.selAreaWMS.setVisibility(hasSel); ikMapWrap.selRouteWMS.setVisibility(hasSel); ikMapWrap.selPointWMS.setVisibility(hasSel); } }; function InitGeoLocating() { var mapWrap = this; try { mapWrap.positioningId = navigator.geolocation.watchPosition( function(loc) { if(mapWrap.gpsTimerId) { window.clearTimeout(mapWrap.gpsTimerId); mapWrap.gpsTimerId = null; } mapWrap.updateUserLocation(loc); }, function(err) { if(mapWrap.gpsTimerId) { window.clearTimeout(mapWrap.gpsTimerId); mapWrap.gpsTimerId = null; } mapWrap.locatingFailed(err); }, { enableHighAccuracy:true, maximumAge:30000 } ); } catch(e){} }; function UpdateUserLocation(loc) { var mapRef = this; var icon = "gps_circle60.png"; var dir = 0; if(loc && loc.coords && loc.coords.longitude && loc.coords.latitude) { $("#ikGPSCenterButtonMiddleCont").removeClass("centeringDisabled"); if(!this.gpsLayer) { this.gpsLayer = new OpenLayers.Layer.Vector("gps", { styleMap: this.gps_style, projection: this.map.getProjectionObject(), displayInLayerSwitcher: true, visibility: true, rendererOptions: { zIndexing: true } }); this.map.addLayers([this.gpsLayer]); } if(loc.coords.heading && loc.coords.speed && loc.coords.speed > 0 && !this.guiObj.settings.oldMobile) { dir = loc.coords.heading; icon = "gps_directional60.png"; } if(this.userPos) { this.userPos.attributes = {iksymbol: icon, "ikdescription": "", objectid: "ikUsrOnMap", partid: "ikUsrOnMap", ikdir: ""+dir}; var newLocation = new OpenLayers.LonLat(loc.coords.longitude, loc.coords.latitude).transform(new OpenLayers.Projection("EPSG:4326"), this.map.getProjectionObject()); this.userPos.move(newLocation); } else { var geom = new OpenLayers.Geometry.Point(loc.coords.longitude, loc.coords.latitude).transform(new OpenLayers.Projection("EPSG:4326"), this.map.getProjectionObject()); this.userPos = new OpenLayers.Feature.Vector(geom, {iksymbol: icon, "ikdescription": "", objectid: "ikUsrOnMap", partid: "ikUsrOnMap", ikdir: ""+dir}); if(this.gpsLayer.features.length == 0) { this.gpsLayer.addFeatures([this.userPos]); } } if(this.userPos && this.userPos.layer && this.followGps) this.map.moveTo(this.userPos.geometry.getBounds().getCenterLonLat(), null, {fromGps: true}); } else { if(this.userPos) { this.gpsLayer.removeFeatures([this.userPos]); this.userPos = null; } $("#ikGPSCenterButtonMiddleCont").addClass("centeringDisabled"); navigator.geolocation.clearWatch(mapWrap.positioningId); } }; function LocatingFailed(err) { var mapWrap = this; if(this.userPos) { this.gpsLayer.removeFeatures([this.userPos]); this.userPos = null; } $("#ikGPSCenterButtonMiddleCont").addClass("centeringDisabled"); switch(err.code) { case err.PERMISSION_DENIED: navigator.geolocation.clearWatch(mapWrap.positioningId); $("#ikGPSCenterButtonCont").remove(); break; case error.POSITION_UNAVAILABLE: navigator.geolocation.clearWatch(mapWrap.positioningId); mapWrap.gpsTimerId = window.setTimeout( OpenLayers.Function.bind(mapWrap.initGeoLocating, mapWrap, null), gpsUpdateRate ); break; case error.TIMEOUT: navigator.geolocation.clearWatch(mapWrap.positioningId); mapWrap.gpsTimerId = window.setTimeout( OpenLayers.Function.bind(mapWrap.initGeoLocating, mapWrap, null), gpsUpdateRate ); break; case error.UNKNOWN_ERROR: break; } }; function CenterToUserLocation() { if(this.userPos && this.userPos.layer) { this.map.moveTo(this.userPos.geometry.getBounds().getCenterLonLat(), null, {fromGps: true}); } }; function bearing(line) { var seg = line.getSortedSegments()[0]; var b_x = 0; var b_y = 1; var a_x = seg.x2 - seg.x1; var a_y = seg.y2 - seg.y1; var angle_rad = Math.acos((a_x*b_x+a_y*b_y)/Math.sqrt(a_x*a_x+a_y*a_y)) ; var angle = 360/(2*Math.PI)*angle_rad; if (a_x < 0) { return 360 - angle; } else { return angle; } };