Control activates before button click - javascript

I have a custom toolbar that fires events on html button click, there is a problem with one where it's activated on init instead of after button click.. it seems to trigger the function on init.
The controls toggle correctly but it seems to be activated by default or within init.
Here is the code:
/* other Controls */
polygon: new OpenLayers.Control.Measure(
OpenLayers.Handler.Polygon, {
persist: true,
immediate: true,
handlerOptions: {
layerOptions: {
renderers: renderer,
styleMap: styleMap
}
}
}
),
choose: new OpenLayers.Control.Button({ /** **/
activateControl: false, /** Problem here **/
trigger: tochiSentaku() /** **/
})
};
var control;
for(var key in allControls) {
control = allControls[key];
control.events.on({
"measure": handleMeasurements,
"measurepartial": handleMeasurements,
"button": tochiSentaku
});
map.addControl(control);
}
function toggleControl(element){
for(key in allControls){
var control = allControls[key];
if(control.active){
control.deactivate();
}
if(element.value == key && element.click){
control.activate();
vlayer.removeAllFeatures();
var mybutton = document.getElementById('output');
var xyz = "";
mybutton.innerHTML = xyz;
}
else{
control.deactivate();
}
}
}
tochiSentaku Function
function tochiSentaku(evt){
var element = document.getElementById("attribute");
map.events.register('click', map, function(e){
vlayer.destroyFeatures(vlayer,features);
var coord = $(".olControlMousePosition").text();
$("#attribute").html('<center><img src="images/loading.gif" alt="Now Loading..." /></center>');
$.getJSON("scripts/tochi_sentaku.php",{coord:coord}, function(data){
$("#attribute").html("<button id=\"attribute_map\" onclick=\"" + data.the_geom + "\">地図</button><table id='attribute_tbl'><tr><th>項目名</th><th>値</th></tr></table>");
for(var key in data){
if(key != "the_geom"){
$("#attribute_tbl").append("<tr><td>" + key + "</td><td>" + data[key] + "</td></tr>");
}
}
$("#attribute_map").click();
});
});
}
If anyone can give me some advice would greatly appreciate it.

You haven't provided the definition of tochiSentaku in your code snippet.
But my initial guess would be, to change the code to
choose: new OpenLayers.Control.Button({
activateControl: false,
trigger: tochiSentaku
})

Figured it out. Instead of using
trigger:tochiSentaku
I used
activate:tochiSentaku
#simplyharsh Thanks for your suggestion

Related

CodeMirror - insert text into editor when there are multiple editors

I have two codemirror editors on one page. A drop down list of items and radio group to target the correct editor.
What I want to do is on change of the drop down list insert the value of the item into the targeted editor (deleted by the radio group).
my code is as below: however the function isnt working. When I alert the item value and the target I get expected results, however the function to insert the text is failing:
<script type="text/javascript">
function editor(id) {
var editor = CodeMirror.fromTextArea(id, {
continuousScanning: 500,
lineNumbers: true
});
editor.setSize(null, 550);
}
var config_id = document.getElementById('id_config')
var config = editor(config_id);
var remote_config_id = document.getElementById('id_remote_config')
var remote_config = editor(remote_config_id);
function insertStringInTemplate(str, target) {
if (target== "id_config") {
var doc = config
} else {
var doc = remote_config
}
var cursor = doc.getCursor();
var pos = {
line: cursor.line,
ch: cursor.ch
}
doc.replaceRange(str, pos);
}
$(function(){
// bind change event to select
$('#template_vars').on('change', function () {
var var_data = $(this).val(); // get selected value
var var_target = $('input[name=target]:checked').val();
insertStringInTemplate(var_data, var_target)
return false;
});
});
$("#template_vars").chosen({no_results_text: "Oops, nothing found!"});
</script>
however the function to insert the text is failing
That function (i.e. insertStringInTemplate()) is working good/properly; however, the problem is with the editor() function, where you forgot to return the editor (i.e. the CodeMirror instance).
So a simple fix would be:
function editor(id) {
var editor = CodeMirror.fromTextArea(id, {
continuousScanning: 500,
lineNumbers: true
});
editor.setSize(null, 550);
return editor; // <- here's the fix
}
Demo on CodePen.
However in that demo, I added an if block to the insertStringInTemplate() function, as in the following code:
function insertStringInTemplate(str, target) {
if (target== "id_config") {
var doc = config
} else {
var doc = remote_config
}
// If there's a selection, replace the selection.
if ( doc.somethingSelected() ) {
doc.replaceSelection( str );
return;
}
// Otherwise, we insert at the cursor position.
var cursor = doc.getCursor();
var pos = {
line: cursor.line,
ch: cursor.ch
}
doc.replaceRange(str, pos);
}

Show the attribute inspector without saving a new feature

The requirement is to add a new feature from template picker but without applying it, can i show the attribute inspector than save the feature.
selectedTemplate = templatePicker.getSelected();
This selectedTemplate is then selected to put the points on the map than opens the attribute inspector by selecting it.
selectedTemplate.featureLayer.applyEdits([newGraphic], null, null);
Sample Code Block :
dojo.connect(drawToolbar, "onDrawEnd", function(geometry) {
//display the editable info window for newly created features
if (map.infoWindow.isShowing) {
map.infoWindow.hide();
}
drawToolbar.deactivate();
var fieldAttributes = layerFieldToAttributes(selectedTemplate.featureLayer.fields);
var newAttributes = dojo.mixin(fieldAttributes, selectedTemplate.template.prototype.attributes);
var newGraphic = new esri.Graphic(geometry, null, newAttributes);
var layerInfos = [{
'featureLayer': selectedTemplate.featureLayer,
'isEditable': true
}];
var attInspector = new esri.dijit.AttributeInspector({
layerInfos: layerInfos
}, dojo.create("div"));
selectedTemplate.featureLayer.applyEdits([newGraphic], null, null, function() {
var screenPoint = map.toScreen(getInfoWindowPositionPoint(newGraphic));
map.infoWindow.setContent(attInspector.domNode);
map.infoWindow.resize(325, 185);
map.infoWindow.show(screenPoint, map.getInfoWindowAnchor(screenPoint));
templatePicker.clearSelection();
});
dojo.connect(attInspector, "onAttributeChange", function(feature, fieldName, newFieldValue) {
feature.attributes[fieldName] = newFieldValue;
feature.getLayer().applyEdits(null, [feature], null);
});
dojo.connect(attInspector, "onDelete", function(feature) {
feature.getLayer().applyEdits(null, null, [feature]);
map.infoWindow.hide();
});
});
}
I would like my client first add the attribute to feature and (save & apply) it.
Any help would be appreciated.
Here is the sample project : https://www.dropbox.com/s/fh71g1k9nsa70nq/index-2.html.zip?dl=0
I dont think you can do that with the AttributeInspector, try creating a custom popup that will have options to save and delete/cancel, when saving fire the applyEdits, when clicking delete, remove, ect.
Content:
var content = "<input id='text1'></input> </br>" +
"<input id='text1'></input> </br>" + "<button id='submit'>Submit</button>" + "<button id='delete'>Delete</button>"
/*
var attInspector = new AttributeInspector({
layerInfos: layerInfos
}, dojo.create("div"));
*/
map.infoWindow.setTitle(selectedTemplate.featureLayer.name);
map.infoWindow.setContent(content);
map.infoWindow.resize(350, 240);
map.infoWindow.show(evt.geometry, map.getInfoWindowAnchor(evt.geometry));
Listener:
on(map.infoWindow, "show", function () {
on(dom.byId("submit"), "click", function () {
alert("I should be saving");
});
on(dom.byId("delete"), "click", function () {
alert("I should be deleting");
});
})
Check out this fiddler: https://jsfiddle.net/kreza/jpLj5y4h/2/

OpenLayers - how to use single and double click event on feature

I am using Opnelayers control for selection of feature
OpenLayers.Control.SelectFeature
when I triggered the single click event then feature get selected and its working fine for me. Now I want to use double click event for another operation.
I have get the idea from this link feature to have both a single click and double click event?
I have used the same code and both click events working fine but I cannot get the feature on which click event performed. This is the code
handler = new OpenLayers.Handler.Click(
select,
{
click: function(evt)
{
var feature = this.layer.getFeatureFromEvent(evt);
console.log(feature); // output null
if(this.layer.selectedFeatures){
this.unselect(this.layer.selectedFeatures[0]);
}
},
dblclick: function(evt)
{
// some other operation
}
},
{
single: true,
double: true,
stopDouble: true,
stopSingle: true
}
);
handler.activate();
Any idea which thing is missing in this code?
Thank you
For The Above Question this might solve your answer with few changes
var handler = new OpenLayers.Handler.Click(
layerName, {
click: function(evt) {
console.log('click has triggered');
var feature = layerName.getFeatureFromEvent(evt);
}
,dblclick: function(evt) {
console.log('dblclick has triggered');
}
},{
single: true
,double: true
,stopSingle: true
,stopDouble: true
}
);
handler.activate();
I have been in a similar situation and used the getClosestFeatureToCoordinate method of the layer source. The code would be something like:
click: function(evt) {
var coord = evt.coordinate;
var source = this.layer.getSource();
var feature = source.getClosestFeatureToCoordinate(coord);
// do something with feature
}
I have done in this way.
click: function(evt) {
var pos = map.getLonLatFromPixel(xy);
var point = new OpenLayers.Geometry.Point(pos.lon, pos.lat);
var list = $.map(this.layer.features, function(v) {
return v.geometry.distanceTo(point);
}); // get distance of all features
var min = (Math.min.apply(null, list)); // minimum distance
var closest = $.map(this.layer.features, function(v) {
if (v.geometry.distanceTo(point) == min)
return v;
});
feature = closest[0];
}

bootstrap - button with onclick function inside tooltip

As stated in title. Im trying to create a tooltip which will have some buttons inside. The problems is with the onclick function, which is somehow not working. This is the actual code I have.
$('#button_nowtime').popover({
trigger: 'click',
html: 'true',
title: "<b>Čas</b>",
content:
function() {
var returnstring="",button;
for(var i=0; i<files.length; i++){
button = document.createElement("a");
button.innerText = fileNametoButtonTime(files[i]);
button.onclick = (function() {
var currentID = i;
return function() {
alert("asd"); currentTimeIndex=currentID; setNowTimeButton(); drawImage(); $('#button_nowtime').popover('hide');
}
})();
button.href="#";
returnstring+=button.outerHTML;
returnstring+=" | ";
}
return returnstring;
}
});
The buttons appear in the tooltip but not react to the onclick function.
I've adjusted your original question (Demo Fiddle: http://jsfiddle.net/WfcM9/) to use jQuery to instead create the buttons and event handling.
With jQuery, it'll be adding the buttons to the DOM, giving them an class then outside the popover() function, give it a $(document).on('click', 'classname') for the document to wait for.
With jQuery .on('click')
<script>
var files = [ "FileOne", "FiletWO" ],
options = {
trigger: 'click',
html: 'true',
title: "<b>Čas</b>",
content: function() {
var $buttonsContainer = $('<div />');
for( var i=0; i< files.length; i++ ) {
var addLink = $('<a>').addClass('fileclick btn btn-default')
.attr( 'data-id', files[i] )
.html( files[i] );
$buttonsContainer.append( addLink );
}
return $buttonsContainer;
}
};
/**
* Create the Popover with above Options
**/
$('#button_nowtime').popover(options);
/**
* Listen for the Class Click on the buttons created.
**/
$(document).on('click', '.fileclick', function() {
alert( $(this).data('id') );
//Alerts FileOne or FileTwo
});
</script>
Fiddle Demo: http://jsfiddle.net/M2HQD/3/

Enabling History API with datatables

I have a dataTable object on a page representing a list of releases I need to keep track of with the url /releases I want to add the following functionality
if /releases?query=<query>, the dataTable will initialized with the provided query
The query parameter is updated if the user changes the search term
The back and forward buttons in the browser go the appropriate query
So far I am able to do the first 2, but when I listen for the popstate event, redrawing the table triggers a pushState which I can't figure out how to prevent. Here's my code so far:
$(document).ready(function(){
var prevSearch;
var table = $('#releases').dataTable({
"bJQueryUI" : true,
"sPaginationType" : "full_numbers",
"iDisplayLength" : 50,
"oSearch": {"sSearch": '#{params[:query]}'},
"fnDrawCallback": function(oSettings) {
var curSearch = oSettings.oPreviousSearch.sSearch;
if (!prevSearch) {
prevSearch = curSearch;
} else if (curSearch != prevSearch) {
console.log("changed to: " + curSearch);
history.pushState({query: curSearch}, "title", "releases?query=" + curSearch);
prevSearch = curSearch;
}
}
});
window.addEventListener("popstate", function(e) {
if (e.state) {
table.fnFilter(e.state.query);
}
});
});
Note, I am using a rails backend and this is inlined javascript being served in the page.
you have only 2 options here:
move pushState code out of drawCallback. There must be some other code that causes the datatables to draw when user enters something. put your pushState code there. This is the ideal solution
add a hack like this
$(document).ready(function () {
var prevSearch;
var saveState = true;
var table = $('#releases').dataTable({
"bJQueryUI":true,
"sPaginationType":"full_numbers",
"iDisplayLength":50,
"oSearch":{"sSearch":'#{params[:query]}'},
"fnDrawCallback":function (oSettings) {
var curSearch = oSettings.oPreviousSearch.sSearch;
if (!prevSearch) {
prevSearch = curSearch;
} else if (curSearch != prevSearch) {
console.log("changed to: " + curSearch);
if (saveState) {
history.pushState({query:curSearch}, "title", "releases?query=" + curSearch);
}
prevSearch = curSearch;
}
}
});
window.addEventListener("popstate", function (e) {
if (e.state) {
saveState = false;
table.fnFilter(e.state.query);
saveState = true;
}
});
});

Categories

Resources