Turf.within is not working - ajax

I have a function to get the nearest points (farmers) to a specific point(customer),i made a buffer around the customer with distance from the user then i am using turf.within to get all the points(farmers) inside this buffer.
It works fine if i give the array of coordinates in the feature collection in the variable searchWithin,but when i gave it as a variable (array) which is in this case the points of the buffer bufresult it doesn't work.
function Find_Nearest()
{
//getting the orderid to get the customer id
var select1 = document.getElementById('OrderId');
var Order_ID = select1.options[select1.selectedIndex].text;
var Cust_Name = document.getElementById('CustName').textContent;
//to check the distance entered by user
var select = document.querySelector('input[name="optradio"]:checked').value;
var dist=document.getElementById('dist').value;
if (select == "EnterRange")
{
if (dist == null || dist == "" || isNaN(dist) )
{
alert("Please enter a valid range");
document.getElementById('dist').focus() ;
}
else { distance=dist;}
}
else { distance=select;}
$.ajax({
type:"POST",
url:"CustomerID_geojson.php",
data:{'Cust_Name': Cust_Name} ,
dataType: 'json',
success: function (response)
{
var unit = 'kilometers';
var buffered = turf.buffer(response, distance, unit);
var bufresult = new Array();
bufresult.push(buffered.geometry.coordinates);
$.ajax({
type: "POST",
url: 'allfarmers_geojson.php',
dataType: 'json',
success: function (data)
{
var searchWithin = {
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": bufresult //the problem is here
// [[
// [126.5443329669793,8.71772],
// [126.17866648348965,9.34375583885896],
// [125.44733351651035,9.34375583885896],
// [125.08166703302071,8.71772],
// [125.44733351651035,8.091684161141039],
// [126.17866648348965,8.091684161141039],
// [126.5443329669793,8.71772]
// ]]
}
}
]
};
console.log(bufresult);
console.log(searchWithin);
var ptsWithin = turf.within(data, searchWithin);
console.log(ptsWithin);
geojsonLayer = L.geoJson(ptsWithin).addTo(mymap);
mymap.fitBounds(geojsonLayer.getBounds());
}
});
}
});
}

Have you tried replacing
var bufresult = new Array();
and
bufresult.push(buffered.geometry.coordinates);
with
bufresult = buffered.geometry.coordinates
I think the issue may be that you are initializing an array (bufresult) and then pushing the buffered geometry coordinates into that array. You could actually just skip the bufresult variable all together and just plug the buffered.geometry.coordinates variable into where you're using bufresult. Let me know if this doesn't work for you. Could you also include the error that you're getting?

Related

WMSLayer.getSource() Is not a function?

I just want to try showing information about the wms layer about the layers details using openlayers 3.14
map.on('singleclick', function(evt) {
var url = layers.getSource().getGetFeatureInfoUrl(
evt.coordinate, viewResolution, viewProjection,
{'INFO_FORMAT': 'text/javascript',
'propertyName': 'formal_en'});
if (url) {
var parser = new ol.format.GeoJSON();
$.ajax({
url: url,
dataType: 'jsonp',
jsonpCallback: 'parseResponse'
}).then(function(response) {
var result = parser.readFeatures(response);
if (result.length) {
var info = [];
for (var i = 0, ii = result.length; i < ii; ++i) {
info.push(result[i].get('formal_en'));
}
container.innerHTML = info.join(', ');
} else {
container.innerHTML = ' ';
}
});
}
});
layers is probably an array of ol.layer or it may not even be available in the function's scope.
Either way you need to get a single layer to use .getGetFeatureInfoUrl() against.
So either something like:
layers[0].getSource().getGetFeature....
or if layers isn't available you can get it from the map object with .getLayers()
map.getLayers().forEach(function(layer) {
// optionally check that the layer is the one you want.
if (layer.getProperties().ref === 'myLayer'){
layer.getSource().getGetFeature....
}
}

HighStocks not updating URL

I posted this question AJAX URL update as I thought the problem with my code was with AJAX but I think this could be an issue with HighStocks.
I have an external .js file with these functions:
//uses AJAX call to retrieve data and then creates the chart with the data
function createChart(ticker) {
$.ajax({
type: 'post',
url: 'http://...' + ticker + '....com',
success: function (data, status) {
//chart is rendered in here
}
//gets the user inputted ticker symbol from a HTML input box
// and passes to chart function
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
My HTML file just has a simple form with an input box and a button that when clicked calls the getTicker function. For some reason the chart is not being created and the AJAX call doesnt seem to work.
Is this something with HighStocks maybe? Any suggestions would be appreciated.
UPDATE Thank you for the suggestions, I have attempted to use JSONP but the chart still does not load. Can anybody see what I am doing wrong?
var closePrices = new Array();
var dateArray = new Array();
var timeStampArray = new Array();
var timeClose = new Array();
function jsonCallback(data, ticker) {
console.log( data );
//Put all the closing prices into an array and convert to floats
for(var i=0; i < data.query.results.quote.length; i++)
{
closePrices[i] = parseFloat( data.query.results.quote[i].Close );
}
//displays the values in the closePrices array
console.log( closePrices );
//Put all the dates into an array
for(var i=0; i < data.query.results.quote.length; i++)
{
dateArray[i] = data.query.results.quote[i].date;
}
//Convert all the dates into JS Timestamps
for(var i=0; i < dateArray.length; i++)
{
timeStampArray[i] = new Date( dateArray[i] ).getTime();
}
for(var i=0; i<data.query.results.quote.length; i++)
{
timeClose.push( [timeStampArray[i], closePrices[i]] );
}
timeClose = timeClose.reverse();
console.log ( timeClose );
//displays the dateArray
console.log( dateArray );
console.log( timeStampArray );
// Create the chart
$('#container').highcharts('StockChart', {
rangeSelector : {
selected : 1
},
title : {
text : ticker + ' Stock Price'
},
series : [{
name : ticker,
data: timeClose,
tooltip: {
valueDecimals: 2
}
}]
});
}
function createChart() {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22' + ticker +'%22%20and%20startDate%20%3D%20%222013-01-01%22%20and%20endDate%20%3D%20%222013-02-25%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
//Ajax call retrieves the data from Yahoo! Finance API
$.ajax( url, {
dataType: "jsonp",
success: function(data, status){
console.log(status);
jsonCallback(data, ticker);
},
error: function( jqXHR, status, error ) {
console.log( 'Error: ' + error );
}
});
}
//Function to get ticker symbol from input box.
function getTicker() {
var ticker = document.getElementById('userInput').value;
createChart(ticker);
}
Thanks to Jeffrey Blake and Pawel Fus for your suggestions. Using JSONP I was able to get my program functioning correctly :)

Highcharts multiple series from json

My JSON looks like:
[[[773,1363709520],[774,1363709580]],[[1546,1363709520],[1548,1363709580]]]
I would like highcharts to create a new series every time it reaches a new JSON array: [[1546,1363709520],[1548,1363709580]]
I have a hard coded version, but making my data[[]] is not helping...
$(function () {
var data = [];
var data1 = [];
$.ajax({
url: "http://localhost:8080/vdm-stats-core/stats/metrics?from=2&src=org.example.fib&customer=customer0&server=server0&metric=responses.count",
dataType: "jsonp", // Notice! JSONP <-- P (lowercase)
jsonp: "callback",
success: function (inData) {
console.log(inData[0][1][0]);
var xval = new Date();
for (a = 0; a < inData.length; a++) {
for (i = 0; i < inData[a].length; i++) {
var yval = inData[a][i][0];
xval = inData[a][i][1];
var x = [xval, yval];
if (a == 0) {
data.push(x);
}
if (a > 0) {
data1.push(x);
}
}
}
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
title: {
text: 'Test',
},
rangeSelector: {
selected: 1
},
xAxis: {
type: 'datetime'
},
series: [{
name: 'Customer0',
data: data
}, {
name: 'Customer1',
data: data1
}]
});
},
error: function () {
console.log(arguments);
}
});
});
Please help!
I tried to understand your code, here's my intepretation;
function success(inData) {
var customerNr,
timestamp,
VALUE = 0,
TIMESTAMP = 1,
series = {},
len = inData.length,
yval,
item;
for (customerNr = 0; customerNr < len; customerNr++) {
// Init series object literal for customer
series[customerNr] = {
name : 'Customer '+customerNr.toString(),
data : []
};
// Setup data for customer
for (item = 0; item < inData[customerNr].length; item++) {
yval = inData[customerNr][item][VALUE];
timestamp = inData[customerNr][item][TIMESTAMP];
series[customerNr].data.push([timestamp,yval]);
}
// Add series, but redraw only on last customer
chart.addSeries(series[customerNr],customerNr===len-1);
}
};
You recycle the series object for each customer, but I've added a customerNr property. addSeries method in Highchart will by default redraw chart (http://api.highcharts.com/highcharts#Chart.addSeries()). I've selected to only redraw chart on last customer. Forked fiddle example at; http://jsfiddle.net/hkskoglund/VVLNV/
The important thing to keep in mind is that the series object is already a json object...
So the easiest thing to do, assuming you control the creation of the json file, is format the json output as the entire series object:
[{ name: 'Customer0', data: [[773,1363709520],[774,1363709580]] }, { name: 'Customer1', data: [[1546,1363709520],[1548,1363709580]] }]
and then:
series: myData
I got it to work:
Had to reset my series data.
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container'
},
title: {
text: 'Test',
},
rangeSelector: {
selected: 1
},
xAxis: {
type: 'datetime'
},
series: []
});
$.ajax({
url: "http://localhost:8080/vdm-stats-core/stats/metrics?from=200&src=org.example.fib&customer=customer0&server=server0&metric=responses.count",
dataType: "jsonp", // Notice! JSONP <-- P (lowercase)
jsonp: "callback",
success: function (inData) {
var xval = new Date();
var series = {
name: 'Customer',
data: []
}
for (a = 0; a < inData.length; a++) {
for (i = 0; i < inData[a].length; i++) {
var yval = inData[a][i][0];
xval = inData[a][i][1];
var x = [xval, yval];
series.data.push(x);
}
chart.addSeries(series);
series.data = [];
}
},
error: function () {
console.log(arguments);
}
});
});

MVC3 and Twitter Bootstrap TypeAhead without plugin

I have gotten TypeAhead to work properly with static data and am able to call my controller function properly and get data but it is either A: Not parsing the data properly or B: The TypeAhead is not set up correctly.
JavaScript :
<input type="text" id="itemSearch" data-provide="typeahead" value="#ViewBag.Item" name="itemSearch"/>
$('#itemSearch').typeahead({
source: function (query, process) {
parts = [];
map = {};
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data, function (i, part) {
map[part.description] = part;
parts.push(part.description);
});
typeahead.process(parts);
}
});
},
updater: function (item) {
selectedPart = map[item].itemNumber;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return item.replace(regex, "<strong>$1</strong>");
}
});
Controller :
public ActionResult MakePartsArray(string query)
{
var possibleItem = query.ToLower();
var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
return new JsonResult
{
ContentType = "text/plain",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
In my controller I see the data being retrieved correctly and it appears to parse properly but nothing is showing up for my TypeAhead.
Any idea on how to verify exactly where the breakdown is occurring or does anyone see direct fault in my code?
Problem was in the ajax call-
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data.matches, function (i, part) {
var composedInfo = part.description + ' (' + part.itemNumber + ')';
map[composedInfo] = part;
parts.push(composedInfo);
});
process(parts);
}
});
and in the controller on the return type
return new JsonResult
{
ContentType = "application/json",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

JSON Data Map Issue with HighCharts + Ajax

I have the follow data returned via JSON
{"rows":[{"Date":"07/10/2011","Value":1206,"Action":"Drink"},
{"Date":"07/11/2011","Value":2288,"Action":"Pie"},
{"Date":"07/12/2011","Value":1070,"Action":"Drink"},
{"Date":"07/13/2011","Value":1535,"Action":"Beer"},
{"Date":"07/14/2011","Value":1721,"Action":"Drink"}],
"page":1,"total":1,"records":5}
I am trying to use this data with HighCharts but getting a bit confused.
jQuery.ajax({
url: fullPath + 'datamap',
dataType: "json",
type: 'POST',
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (data) {
var lines = data.split('\n');
$.each(lines, function(lineNo, line) {
var items = line.split(',');
var data = {};
$.each(items, function(itemNo, item) {
if (itemNo === 0) {
data.name = item;
} else {
data.y = parseFloat(item);
}
});
options.series[0].data.push(data);
});
// Create the chart
var chart = new Highcharts.Chart(options);
},
cache: false
});
I am trying to chart "Date" and "Value" ?
As I understand you need to show rows values with Highcharts. So firstly your initial data will be:
var chartData = data.rows;
Now chartData is just an array of objects. Use for loop to iterate through chartData like below:
var seriesData = [];
for (var i = 0; i < chartData.length; i++)
{
var x = new Date(chartData[i].Date).getTime();
var y = chartData[i].Value;
seriesData.push([x, y]);
}
After this loop you will have seriesData array of points that can be used in Highcharts. Now just render it:
var chart = new Highcharts.Chart({
chart: {
renderTo: 'chartContainer',
defaultSeriesType: 'line'
},
xAxis: {
type: 'datetime'
},
series: [{
data: seriesData
}]
});
Voila!
Test this: http://jsfiddle.net/ebuTs/8263/

Resources