How to restrict google places to specific city - google-places-api

I am currently able to restrict places to only one country, but I also want to restrict on a specific city also. Any ideas how to achieve that? This is my current code:
var autocomplete,
options = {
types: ['geocode'],
componentRestrictions: {country: 'est'}
};
autocomplete = new google.maps.places.Autocomplete(input, options);
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace().formatted_address;
$(input).attr('value',place);
});

As Luke said the places autocomplete allows you to use componentRestrictions to filter by country only.
But you can use a little trick with a search request string.
Just add prefix with city name in request.
var prefix = 'Kyiv, ';
$(input).on('input',function(){
var str = input.value;
if(str.indexOf(prefix) == 0) {
// string already started with prefix
return;
} else {
if (prefix.indexOf(str) >= 0) {
// string is part of prefix
input.value = prefix;
} else {
input.value = prefix+str;
}
}
});
http://jsfiddle.net/24p1et98/

Places Autocomplete currently allows you to use componentRestrictions to filter by country. What I would do in your situation is to use the options argument to filter by the bounds that define the city in question:
var cityBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(25.341233, 68.289986),
new google.maps.LatLng(25.450715, 68.428345));
var options = {
bounds: cityBounds,
types: ['geocode'],
componentRestrictions: {country: 'est'}
};

Google Provides two ways to achieve this. If you are not satisfied because in countries like India it do not work well, because states and provisions here do not have rectangular or structure boundaries.
1.LatLngBounds (LatLng southwest, LatLng northeast): Where you can give latitude and longitude to form an rectangle.
2. Location (Lat,Lng) & Radius: Where you can give latitude and longitude to form a circle.
But the problem with these approaches they do not provide expected results if you are from countries like India, where states and provisions are not in structured shapes (Rectangular) as in USA.
If you are facing same issue than there is an hack.
With jQuery/Jacascript, you can attach functions which will consistently maintain city name in text input which is bounded with Autocomplete object of Places API.
Here it is:
<script>
$(document).ready(function(){
$("#locality").val(your-city-name) //your-city-name will have city name and some space to seperate it from actual user-input for example: “Bengaluru | ”
});
$("#locality").keydown(function(event) { //locality is text-input box whixh i supplied while creating Autocomplete object
var localeKeyword = “your-city-name”
var localeKeywordLen = localeKeyword.length;
var keyword = $("#locality").val();
var keywordLen = keyword.length;
if(keywordLen == localeKeywordLen) {
var e = event || window.event;
var key = e.keyCode || e.which;
if(key == Number(46) || key == Number(8) || key == Number(37)){
e.preventDefault();
}//Here I am restricting user to delete city name (Restricting use of delete/backspace/left arrow) if length == city-name provided
if(keyword != localeKeyword) {
$("#locality").val(localeKeyword);
}//If input-text does not contain city-name put it there
}
if(!(keyword.includes(localeKeyword))) {
$("#locality").val(localeKeyword);
}//If keyword not includes city name put it there
});

Related

How to create a stock event in amCharts v4?

Is it possible to indicate events along a series in amCharts v4 similar to the Stock Event in the v3 stock chart?
While I was brought on board specifically for v4 and am not familiar with v3, I'm confident you can simulate some of these features using Bullets.
A bullet is a Container (basically a placeholder parent for whatever visual object or additional Containers that you want), that will appear at every point of data. You can put a label there as well as a line and any other shape, e.g.:
var stockBullet = series.bullets.push(new am4charts.Bullet());
stockBullet.dy = -20;
var circle = stockBullet.createChild(am4core.Circle);
circle.stroke = "#000";
circle.strokeWidth = 1;
circle.radius = 10;
circle.fill = series.fill.brighten(-0.3);
circle.dy = -10;
var line = stockBullet.createChild(am4core.Line);
line.stroke = "#000";
line.strokeWidth = 1;
line.height = 20;
var label = stockBullet.createChild(am4core.Label);
label.fill = am4core.color("#000");
label.strokeWidth = 0;
label.dy = -20;
label.textAlign = "middle";
label.horizontalCenter = "middle"
Since we don't want a bullet to appear at every point of data, only at Stock Events, we can handle that once the bullets are ready on the chart by going through their data, disabling them if need be, otherwise providing text for our label (and maybe tooltipText if need be) (presume there is a property stockEvent in the data):
stockBullet.events.on("inited", function(event) {
if (event.target.dataItem && event.target.dataItem.dataContext && event.target.dataItem.dataContext.stockEvent) {
event.target.children.getIndex(2).text = event.target.dataItem.dataContext.stockEvent.text;
} else {
event.target.disabled = true;
}
});
Getting tooltips of different objects to play well with each other can be tricky depending on your chart, e.g. if it has Chart Cursor enabled there's a cursorTooltipEnabled property to prevent triggering a tooltip over bullets. To simplify things in this case what I did is make an invisible series per unique stock event bullet. For each stock event, use adapters to set its paired series' tooltipText to what's desired, and the base, visible series' tooltipText to "":
series.adapter.add("tooltipText", function(text, target) {
if (target.tooltipDataItem.dataContext.stockEvent) {
return "";
}
return text;
});
// ...
hiddenSeries.adapter.add("tooltipText", function(text, target) {
if (target.tooltipDataItem.dataContext.stockEvent) {
return target.tooltipDataItem.dataContext.stockEvent.description;
}
return "";
});
Here's a demo:
https://codepen.io/team/amcharts/pen/337984f18c6329ce904ef52a0c3eeaaa
Screenshot:

How can I replace an image in Google Documents?

I'm trying to insert images into Google Docs (other GSuite apps later) from an Add-On. I've succeeded in fetching the image and inserting it when getCursor() returns a valid Position. When there is a selection (instead of a Cursor), I can succeed if it's text that's selected by walking up to the Parent of the selected text and inserting the image at the start of the paragraph (not perfect, but OK).
UPDATE: It seems that I was using a deprecated method (getSelectedElements()), but that didn't fix the issue. It seems the issue is only with wrapped images as well (I didn't realize that the type of the object changed when you changed it to a wrapped text).
However, when an wrapped-text Image (presumably a PositionedImage) is highlighted (with the rotate and resize handles visible in blue), both getSelection() and getCursor() return null. This is a problem as I would like to be able to get that image and replace it with the one I'm inserting.
Here's my code... any help would be great.
var response = UrlFetchApp.fetch(imageTokenURL);
var selection = DocumentApp.getActiveDocument().getSelection();
if (selection)
{
Logger.log("Got Selection");
var replaced = false;
var elements = selection.getRangeElements();
if (elements.length === 1
&& elements[0].getElement().getType() === DocumentApp.ElementType.INLINE_IMAGE)
{
//replace the URL -- this never happens
}
//otherwise, we take the first element and work from there:
var firstElem = elements[0].getElement();
Logger.log("First Element Type = " + firstElem.getType());
if (firstElem.getType() == DocumentApp.ElementType.PARAGRAPH)
{
var newImage = firstElem.asParagraph().insertInlineImage(0, response);
newImage.setHeight(200);
newImage.setWidth(200);
}
else if (firstElem.getType() == DocumentApp.ElementType.TEXT)
{
var p = firstElem.getParent();
if (p.getType() == DocumentApp.ElementType.PARAGRAPH)
{
var index = p.asParagraph().getChildIndex(firstElem);
var newImage = p.asParagraph().insertInlineImage(index, response);
newImage.setHeight(200);
newImage.setWidth(200);
}
}
} else {
Logger.log("Checking Cursor");
var cursor = DocumentApp.getActiveDocument().getCursor();
if (cursor)
{
Logger.log("Got Cursor: " + cursor);
var newImage = cursor.insertInlineImage(response);
var p = cursor.getElement();
var size=200;
newImage.setHeight(size);
newImage.setWidth(size);
}
}
You are using the deprecated 'getSelectedElements()' method of the Range class. You may notice it's crossed out in the autocomplete selection box.
Instead, use the 'getRangeElements()' method. After selecting the image in the doc, the code below worked for me:
var range = doc.getSelection();
var element = range.getRangeElements()[0].getElement();
Logger.log(element.getType() == DocumentApp.ElementType.INLINE_IMAGE); //logs 'true'

Appcelerator Store Local Searches

When a button is pressed, I would like the id and the name of the button saved locally.
I am not quite sure the best way to approach this problem. Should I use appcelerator properties (http://docs.appcelerator.com/titanium/3.0/#!/api/Titanium.App.Properties) or write to a file to storage? At the moment I am using the Ti.App.Properties.setList.
Example code:
searchStorageName = "searchHistory";
searchResultsArray = [];
var currentEntries = (Ti.App.Properties.getList(searchStorageName));
// Create search entry object.
var localSearchObject = {
company_name: resultNodeCompany,
company_id: resultNodeCompanyID,
variation_id: resultNodeCompanyVariationID
};
// Check if existing entries, if so push current search
// and previous searches to array.
if(currentEntries === null || currentEntries === undefined){
searchResultsArray.push(localSearchObject);
Ti.App.Properties.setList(searchStorageName, searchResultsArray);
// searchResultsArray.push(localSearchObject, currentEntries);
}
else {
searchResultsArray.push(localSearchObject, currentEntries);
Ti.App.Properties.setList(searchStorageName, searchResultsArray);
}
I am stuck at the moment as it is inserting duplicate searches into the array. When I loop over the values to create a list in the UI it shows duplicates.
var currentEntries = (Ti.App.Properties.getList(searchStorageName));
var currentEntriesLength = currentEntries.length;
var getPreviousHistorySearchesArray = [];
currentEntries.forEach(function(entry, index) {
var company_name = entry.company_name;
var company_id = entry.company_id;
var variation_id = entry.variation_id;
// Create View Entry.
createSearchHistoryViewEntry(index, company_name, company_id, variation_id);
}
Use SQLite_Database Better than local properties http://docs.appcelerator.com/titanium/3.0/#!/guide/Working_with_a_SQLite_Database

Xamarin.Android Couchbase.Lite Map Reduce

I simply want to create a View that uses Map-Reduce to do this: Say I have Documents for the Automobile Industry. I would like the user to query for a particular Make - say Ford for example. I would like the user to provide the Ford value via an EditText, Tap a Button, and the "Count" be shown in a TextView. So, to clarify, I want to do a count of a certain type of Document using Map-Reduce. I have searched for over 100 hundred hours on this and have not found not one single example - REAL example I mean. (I have read all the docs, only generic examples - no actual examples)
I am an experienced programmer 15+ yrs exp - all I need is one example, and I am good to go.
Can someone please assist me with this?
Thanks,
Don
Here is my Actual Code:
string lMS = "MS:5"; // just to show what type of value I am using
var msCount = dbase.GetView ("count_ms");
msCount.SetMapReduce ((doc, emit) => {
if (doc.ContainsKey ("DT") && doc["DT"].Equals ("P")) {
if (doc.ContainsKey ("MS") && doc["MS"].Equals (_ms))
{
emit (doc ["id"], 1);
}
}
},
(keys, values, rereduce) => values.ToList().Count, "1");
var mscView = dbase.GetView ("count_ms");
var query = mscView.CreateQuery ();
query.StartKey = "MS:1";
query.EndKey = "MS:9999";
var queryResults = query.Run ();
var nr = queryResults.Count; // shows a value of 1 - wrong - should be 40
// the line below is to allow me to put a stop statement to read line above
var dummyForStop = nr;
Try setting something like
var docsByMakeCount = _database.GetView("docs_by_make_count");
docsByMakeCount.SetMapReduce((doc, emit) =>
{
if (doc.ContainsKey("Make"))
{
emit(doc["Make"], doc);
}
},
(keys, values, rereduce) => values.ToList().Count
, "1");
when you create your view.
and when you use it:
var docsByMake = _database.GetView("docs_by_make_count");
var query = docsByCity.CreateQuery();
query.StartKey = Make;
query.EndKey = Make;
var queryResults = query.Run();
MessageBox.Show(string.Format("{0} documents has been retrieved for that query", queryResults.Count));
if (queryResults.Count == 0) return;
var documents = queryResults.Select(result => JsonConvert.SerializeObject(result.Value, Formatting.Indented)).ToArray();
var commaSeperaterdDocs = "[" + string.Join(",", documents) + "]";
DocumentText = commaSeperaterdDocs;
In my case Make and DocumentText are properties.
There are some optimizations to be made here, like rereducing, but it's the straight forward way.

How to get a jqGrid cell value when editing

How to get a jqGrid cell value when in-line editing (getcell and getRowData returns the cell content and not the actuall value of the input element).
General function to get value of cell with given row id and cell id
Create in your js code function:
function getCellValue(rowId, cellId) {
var cell = jQuery('#' + rowId + '_' + cellId);
var val = cell.val();
return val;
}
Example of use:
var clientId = getCellValue(15, 'clientId');
Dodgy, but works.
Here is an example of basic solution with a user function.
ondblClickRow: function(rowid) {
var cont = $('#grid').getCell(rowid, 'MyCol');
var val = getCellValue(cont);
}
...
function getCellValue(content) {
var k1 = content.indexOf(' value=', 0);
var k2 = content.indexOf(' name=', k1);
var val = '';
if (k1 > 0) {
val = content.substr(k1 + 7, k2 - k1 - 6);
}
return val;
}
After many hours grief I found this to be the simplest solution. Call this before fetching the row data:
$('#yourgrid').jqGrid("editCell", 0, 0, false);
It will save any current edit and will not throw if there are no rows in the grid.
As you stated, according to the jqGrid documentation for getCell and getRowData:
Do not use this method when you editing the row or cell. This will return the cell content and not the actual value of the input element
Since neither of these methods will return your data directly, you would have to use them to return the cell content itself and then parse it, perhaps using jQuery. It would be nice if a future version of jqGrid could provide a means to do some of this parsing itself, and/or provide an API to make it more straightforward. But on the other hand is this really a use case that comes up that often?
Alternatively, if you can explain your original problem in more detail there may be other options.
Try this, it will give you particular column's value
onSelectRow: function(id) {
var rowData = jQuery(this).getRowData(id);
var temp= rowData['name'];//replace name with you column
alert(temp);
}
Basically, you have to save the row before you access the cell contents.
If you do, then you get the value for the cell instead of the markup that comes when the cell is in edit mode.
jQuery.each(selectedRows, function(index, foodId) {
// save the row on the grid in 'client array', I.E. without a server post
$("#favoritesTable").saveRow(foodId, false, 'clientArray');
// longhand, get grid row based on the id
var gridRow = $("#favoritesTable").getRowData(foodId);
// reference the value from the editable cell
foodData += foodId + ":" + gridRow['ServingsConsumed'] + ',';
});
Hi, I met this problem too. Finally I solved this problem by jQuery. But the answer is related to the grid itself, not a common one. Hope it helps.
My solution like this:
var userIDContent = $("#grid").getCell(id,"userID"); // Use getCell to get the content
//alert("userID:" +userID); // you can see the content here.
//Use jQuery to create this element and then get the required value.
var userID = $(userIDContent).val(); // var userID = $(userIDContent).attr('attrName');
you can use this directly....
onCellSelect: function(rowid,iCol,cellcontent,e) {
alert(cellcontent);
}
This is my solution:
function getDataLine(grida, rowid){ //vykradeno z inineeditu a vohackovano
if(grida.lastIndexOf("#", 0) === 0){
grida = $(grida);
}else{
grida = $("#"+grida);
}
var nm, tmp={}, tmp2={}, tmp3= {}, editable, fr, cv, ind;
ind = grida.jqGrid("getInd",rowid,true);
if(ind === false) {return success;}
editable = $(ind).attr("editable");
if (editable==="1") {
var cm;
var colModel = grida.jqGrid("getGridParam","colModel") ;
$("td",ind).each(function(i) {
// cm = $('#mygrid').p.colModel[i];
cm = colModel[i];
nm = cm.name;
if ( nm != 'cb' && nm != 'subgrid' && cm.editable===true && nm != 'rn' && !$(this).hasClass('not-editable-cell')) {
switch (cm.edittype) {
case "checkbox":
var cbv = ["Yes","No"];
if(cm.editoptions ) {
cbv = cm.editoptions.value.split(":");
}
tmp[nm]= $("input",this).is(":checked") ? cbv[0] : cbv[1];
break;
case 'text':
case 'password':
case 'textarea':
case "button" :
tmp[nm]=$("input, textarea",this).val();
break;
case 'select':
if(!cm.editoptions.multiple) {
tmp[nm] = $("select option:selected",this).val();
tmp2[nm] = $("select option:selected", this).text();
} else {
var sel = $("select",this), selectedText = [];
tmp[nm] = $(sel).val();
if(tmp[nm]) { tmp[nm]= tmp[nm].join(","); } else { tmp[nm] =""; }
$("select option:selected",this).each(
function(i,selected){
selectedText[i] = $(selected).text();
}
);
tmp2[nm] = selectedText.join(",");
}
if(cm.formatter && cm.formatter == 'select') { tmp2={}; }
break;
}
}
});
}
return tmp;
}
I have a solution:
1. Using this.value to get the current editing value in the editing row.
2. Save the cell value to a hidden field when the cell lost its focus.
3. Read the hidden field when you need.
The code:
colModel="[
{ name: 'Net', index: 'Net', editable:true, editoptions: { dataEvents: [ { type: 'focusout', fn: function(e) {$('#HiddenNet').val(this.value);} }] }, editrules:{custom:true,}},
{ name: 'Tax', index: 'Tax', editable:true, editoptions: { dataEvents: [ { type: 'focus', fn: function(e) {this.value=$('#HiddenNet').val(); } }] }, editrules:{custom:true}}
]"
Good Luck
You can get it from the following way...!!
var rowId =$("#list").jqGrid('getGridParam','selrow');
var rowData = jQuery("#list").getRowData(rowId);
var colData = rowData['UserId']; // perticuler Column name of jqgrid that you want to access
In my case the contents of my cell is HTML as result of a formatter. I want the value inside anchor tag. By fetching the cell contents and then creating an element out of the html via jQuery I am able to then access the raw value by calling .text() on my newly created element.
var cellContents = grid.getCell(rowid, 'ColNameHere');
console.log($(cellContents));
//in my case logs <h3>The Value I'm After</h3>
var cellRawValue = $(cellContents).text();
console.log(cellRawValue); //outputs "The Value I'm After!"
my answer is based on #LLQ answer, but since in my case my cellContents isn't an input I needed to use .text() instead of .val() to access the raw value so I thought I'd post this in case anyone else is looking for a way to access the raw value of a formatted jqGrid cell.
its very simple write code in you grid.php and pass the value to an other page.php
in this way you can get other column cell vaue
but any one can make a like window.open(path to pass value....) in fancy box or clor box?
$custom = <<<CUSTOM
jQuery("#getselected").click(function(){
var selr = jQuery('#grid').jqGrid('getGridParam','selrow');
var kelr = jQuery('#grid').jqGrid('getCell', selr, 'stu_regno');
var belr = jQuery('#grid').jqGrid('getCell', selr, 'stu_school');
if(selr)
window.open('editcustomer.php?id='+(selr), '_Self');
else alert("No selected row");
return false;
});
CUSTOM;
$grid->setJSCode($custom);
I think an extension of this would get it for you.
retrieving-original-row-data-from-jqgrid
I think a better solution than using getCell which as you know returns some html when in edit mode is to use jquery to access the fields directly. The problem with trying to parse like you are doing is that it will only work for input fields (not things like select), and it won't work if you have done some customizations to the input fields. The following will work with inputs and select elements and is only one line of code.
ondblClickRow: function(rowid) {
var val = $('#' + rowid + '_MyCol').val();
}
I've got a rather indirect way. Your data should have an unique id.
First, setting a formatter
$.extend(true, $.fn.fmatter, {
numdata: function(cellvalue, options, rowdata){
return '<span class="numData" data-num="'+rowdata.num+'">'+rowdata.num+'</span>';
}
});
Use this formatter in ColModel. To retrieve ID (e.g. selected row)
var grid = $("#grid"),
rowId = grid.getGridPara('selrow'),
num = grid.find("#"+rowId+" span.numData").attr("data-num");
(or you can directly use .data() for latest jquery 1.4.4)
In order to get the cell value when in-line editing you need to capture this event(or another similar event, check documentation):
beforeSaveCell: function (rowid, celname, value, iRow, iCol) { }
In the value parameter you have the 'value' of the cell that was currently edited.
To get the the rest of the values in the row use getRowData()
I lost a lot of time with this, hope this helps.
My workaround is to attach an object containing orignal values to each tr element in the grid. I've used afterAddRecord callback to get my hands on the values before jqGrid throws them away and jQuery's "data" method to store them in the work.
Example:
afterInsertRow: function( rowid, rowdata, rowelem ) {
var tr = $("#"+rowid);
$(tr).data("jqgrid.record_data", rowelem);
},
“rowelem” is the array of cell values from our JSON data feed or [jsonReader] (http://www.trirand.com/jqgridwiki/doku.php?id=wiki:retrieving_data#jsonreader_as_function)
Then at any point I can fetch those attributes using:
$(tr).data(“jqgrid.record_data”).
More at: http://wojciech.oxos.pl/post/9423083837/fetching-original-record-values-in-jqgrid
I think that Aidan's answer is by far the best.
$('#yourgrid').jqGrid("editCell", 0, 0, false);
This commits any current edits, giving you access to the real value. I prefer it because:
You don't have to hard-code any cell references in.
It is particularly well suited to using getRowData() to get the entire grid, as it doesn't care which cell you've just been editing.
You're not trying to parse some markup generated by jqGrid which may change in future.
If the user is saving, then ending the edit session is likely the behaviour they would want anyway.
Before i was getting :
html tag of the textbox something like
but Here is the solution to get the value from that particular column, working and tested
function getValue(rowId, cellId) {
var val = $("[rowId='"+rowId+"'][name='"+cellId+"']").val();
return val;
}
var values = getValue(rowId, 'cellid');
I obtain edit value using javascript:
document.getElementById('idCell').value
I hope this info useful for someone.
I needed the original value before the formatter, so this is what I did:
{
name: 'Slot', title: false, formatter: function (cellValue, options, rowObject) {
rowObject['SlotID'] = cellValue; // <--- This saves the original ID
if (somelogic) {
return someString;
} else {
return someOtherString;
}
}
},
{ name: 'SlotID', hidden: true }
Now SlotID contains the original ID. Also, you don't need to have SlotID property on your original model.
try subscribing to afterEditCell event it will receive (rowid, cellname, value, iRow, iCol) where value is your a new value of your cell
You can use getCol to get the column values as an array then index into it by the row you are interested in.
var col = $('#grid').jqGrid('getCol', 'Sales', false);
var val = col[row];

Resources