Map layer is not defined - dictionary

I am trying to do a point cluster layer based on the JSON objects I obtained from database. Here is my JavaScript to plot a point cluster layer:
function addClusters() {
$.ajax({
url: "index.aspx/getBusCommuter",
type: "POST",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var parsed = JSON.parse(data.d);
$.each(parsed, function (i, jsondata) {
var coordXicon = jsondata.BusStopX;
var coordYicon = jsondata.BusStopY;
var commuterAmt = jsondata.CommuterAmt;
var latlng = new esri.geometry.Point({ "x": coordXicon, "y": coordYicon, "spatialReference": { "wkid": 4326 } });
// cluster layer that uses OpenLayers style clustering
clusterLayer = new ClusterLayer({
"data": commuterAmt,
"distance": 100,
"id": "clusters",
"labelColor": "#fff",
"labelOffset": 10,
"resolution": map.extent.getWidth() / map.width,
"singleColor": "#888"
});
var defaultSym = new SimpleMarkerSymbol().setSize(4);
var renderer = new ClassBreaksRenderer(defaultSym, "clusterCount");
var picBaseUrl = "http://static.arcgis.com/images/Symbols/Shapes/";
var blue = new PictureMarkerSymbol(picBaseUrl + "BluePin1LargeB.png", 32, 32).setOffset(0, 15);
var green = new PictureMarkerSymbol(picBaseUrl + "GreenPin1LargeB.png", 64, 64).setOffset(0, 15);
var red = new PictureMarkerSymbol(picBaseUrl + "RedPin1LargeB.png", 72, 72).setOffset(0, 15);
renderer.addBreak(0, 2, blue);
renderer.addBreak(2, 200, green);
renderer.addBreak(200, 1001, red);
clusterLayer.setRenderer(renderer);
map.addLayer(clusterLayer);
});
},
error: function (request, state, errors) {
}
});
}
However, when I try to run it, it told me an error message which is clusterLayer is not defined. I wonder which part I missed and am I doing in the correct way.
Also, I wonder is it possible/correct to set the commuterAmt I obtained to data so that for each point on the map will be attached with the correct amount?
I get the reference from: ArcGIS Documentation
Thanks in advance.

Try to download the sample code ArcGIS Documentation
Include ClusterLayer.js from extras direxctory
var dojoConfig = {
paths: {
extras: location.pathname.replace(/\/[^/]+$/, "") + "/extras"
}
};
then in your code use
define dojo.provide("extras.ClusterLayer");
and call
clusterLayer = new extras.ClusterLayer({
"data": commuterAmt,
"distance": 100,
"id": "clusters",
"labelColor": "#fff",
"labelOffset": 10,
"resolution": map.extent.getWidth() / map.width,
"singleColor": "#888"
});

Related

I need to create an NDWI diagram in GEE, but I get an error

I want to generate a NDWI chart, but I get this error:
Error generating chart: No features contain non-null values of "system:time_start".
enter code here
var L8 = ee.ImageCollection("LANDSAT/LC08/C02/T1_RT_TOA")
.filterDate('2021-01-01', '2021-12-31')
.filterBounds(VolRn)
.filterMetadata('CLOUD_COVER', 'less_than', 1.5)
.mean()
.clip(VolRn);
var green = L8.select('B3');
var nir = L8.select('B5');
var ndwi = green.subtract(nir).divide(green.add(nir)).rename('NDWI');
var ndwiParams = {
min: -1,
max: 1,
palette: ['green', 'white', 'blue']
};
var ndwiMasked = ndwi.updateMask(ndwi.gte(0.001))
Map.setCenter(44.5858, 48.8047, 7);
Map.addLayer(ndwi, ndwiParams, 'NDWI image');
var options = {
title: 'Landsat Spectral Indexes',
hAxis: {title: 'Date'},
vAxis: {title: 'Value'},
lineWidth: 1,
maxPixels: 1e9,
series: {
0: {color: 'blue'}, // NDWI
}};
print(Chart.image.series(ndwi, VolRn, ee.Reducer.mean(), 200).setOptions(options));
enter code here
Can you please explain what this error is and how to fix it.
I am completely new to GEE and can't find information about this error.
I will be very grateful

Google Trends polynomial regression does not work

I'm trying to add polynomial regression line to my google trends live graph but it does not work properly:
as you can see the polynomial regression trendline is not fitting the data points properly (it's straight trendline and not a polynomial trendline).
My code is:
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Time of Day');
data.addColumn('number', 'Depth');
var options = {
title: 'graph',
legend: 'none',
crosshair: { trigger: 'both', orientation: 'both' },
trendlines: {
0: {
type: 'polynomial',
degree: 3,
visibleInLegend: true,
}
},
hAxis: {
viewWindow: {
min: new Date(),
}
},
vAxis: {
viewWindow: {
min: 0,
max: 100
}
}
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart'));
chart.draw(data, options);
var interval = setInterval(function() {
var time = new Date();
data.addRow([time, newValue])
chart.draw(data, options);
}, 10);

Open Layers issue with markers changing coordinates

I have an issue that is driving me crazy. I have an openlayers map project that works fine. I took this concept code and moved it to a project that utilizes .Net and the projection for the markers/icons get messed up.
//set the Icon/Marker that will be used
var iconStyle = new ol.style.Style({
image: new ol.style.Icon(/** #type {olx.style.IconOptions} */({
anchor: [0.5, 46],
anchorXUnits: 'fraction',
anchorYUnits: 'pixels',
opacity: 0.8,
src: '<%=PinMarkerImage%>'
}))
});
var vectorLayer = new ol.layer.Vector({
source: vectorSource,
style: iconStyle
});
//we will zoom the map to fit the locations after we create
//the map
var mapObj = new ol.Map({
layers: [new ol.layer.Tile({ source: new ol.source.OSM() }), vectorLayer],
target: document.getElementById('map-canvas'),
view: new ol.View({
center: ol.proj.fromLonLat([0, 0]),
zoom: 12
})
});
alert(vectorSource.getExtent());
mapObj.getView().fit(vectorSource.getExtent(), { padding: [75, 40, 40, 75], constrainResolution: false });
//I pass in an object one at a time to populate the features
function changeMapOption(oBranch, i) {
// alert('selected');
var long = oBranch.Longitude;
var lat = oBranch.Latitude;
alert(long + ' ' + lat);
//lastCord = ol.proj.transform([coord[0], coord[1]], 'EPSG:4326', 'EPSG:3857');
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857')), //ol.proj.fromLonLat([long, lat])),
id: oBranch.Id,
title: oBranch.Name,
address: oBranch.Address + ", " + oBranch.City + ", " + oBranch.State + " " + oBranch.ZipCode
});
//alert(iconFeature.getGeometry());
vectorSource.addFeature(iconFeature);
//mapObj.getView().fit(vectorSource.getExtent(), { padding: [75, 40, 40, 75], constrainResolution: false });
//target = mapObj.getTarget();
//This will zoom the map to fit all of the vector Sources in vectorSource
//alert(vectorSource.getExtent());
//mapObj.addOverlay(popup);
//jTarget = typeof target === "string" ? $("#" + target) : $(target);
//element = document.getElementById('popup');
}
I have the alerts set to check the Longitude and Latitude. These are correct. For this test run I have three objects that are populated, the Longitude and Latitudes are as follows:
-112.04883, 40.492104
-95.673328, 29.95752
-95.638558, 29.880014
When I run the code the alert for the vectorSource.getExtent() produces this:
-12473218.699582075,-8426499.834030088,-10646435.576762961,-6361484.120029401
And the markers show up off the lower coast of Chile. The Latitude is wrong, yet the Longitude appears to be correct.
I could certainly use some guidance here. This is driving me crazy.
Thanks for any assistance.
After trying multiple times, I came up with a solution that works. Hopefully this will help someone down the line.
function loadMarker(oBranch, i) {
var sHTML = getMarkerInfoHtml(oBranch);
var long = oBranch.Longitude * 1;
var lat = oBranch.Latitude * 1;
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat(([long, lat]))),
index: oBranch.Id,
id: oBranch.Id,
title: oBranch.Name,
address: sHTML //oBranch.Address + ", " + oBranch.City + ", " + oBranch.State + " " + oBranch.ZipCode
});
vectorSource.addFeature(iconFeature);
}
The key was these two lines:
var long = oBranch.Longitude * 1;
var lat = oBranch.Latitude * 1;
by adding the * 1 to the line it forces JavaScript to treat the variables properly as numeric. It now places the markers in the correct location.

How do i pass my returned json string to different textbox

[WebMethod(EnableSession = true)]
public static string Get_OtherBillInfo(string EntryID)
{
if (HttpContext.Current.Session["Bill_Report"] == null)
{
return null;
}
List<TenementNotePrintedModel> BillReport = (List<TenementNotePrintedModel>)HttpContext.Current.Session["Bill_Report"];
TenementNotePrintedModel model = BillReport.Find(ct => ct.EntryID.Equals(int.Parse(EntryID)));
JavaScriptSerializer h = new JavaScriptSerializer();
string str = h.Serialize(model);
return str;
}
=============================
$.ajax({
type: 'POST',
url: 'BillReoprt_PayerID.aspx/Get_OtherBillInfo',
data: JSON.stringify({ 'EntryID':EntryID}),
dataType: 'json',
async: false,
contentType: 'application/json; charset=utf-8',
success: function (response)
{
if (response.d != "")
{
}
},
error: function (response)
{
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
}
================================My returned Data from json is this============
{"d":"{\"EntryID\":76556,\"AssmtNoNew\":1571,\"OwnerID\":16053,\"AssmtNoNew09\":null,\"PropertyID\":15117,\"PID\":\"C-649387/ ALICE MPEREH AND BROS AND SIS - \",\"oPID\":\"649387\",\"HouseNbr\":\"B105\",\"BatchNo\":null,\"FullName\":\"ALICE MPEREH AND BROS AND SIS ()\",\"GeneratedBy\":null,\"BusinessName\":\"\",\"ElectoralID\":null,\"ElectoralArea\":null,\"EvaluationCode\":null,\"strCode\":null,\"AreaOff\":\"WESTERN REGION\",\"LgaName\":null,\"ZoneName\":null,\"AgencyCode\":null,\"LGA\":\"SHC\",\"AREAID\":null,\"StrName\":\"NEW EFFIA\",\"ShopNo\":null,\"Arr_Chargeable\":\"Y\",\"RevCode\":\"2021602\",\"Descr\":\"GROUND RENT(2nd Class Residential -Plot Up to 0.25 acre) 2021602\",\"propAddr\":\"B105, NEW EFFIA, WESTERN REGION\",\"ADDRESS\":\"B108, NEW EFFIA, WESTERN REGION\",\"FDescr\":\"\",\"PropertyStatus\":\"UnAssessed\",\"ArrearsPeriod\":\"\",\"Ratable\":0,\"ImpostRate\":0,\"AmtDue\":70,\"MinRate\":70,\"Arrears\":0,\"ArrearsInt\":0,\"Paymt\":0,\"OtherCharges\":0,\"TotalDue\":70,\"PayDate\":null,\"pAssmtYr\":null,\"AssmtYr\":\"2012\",\"OldAssessmtRef\":null,\"AssessmtRef\":null,\"DepoSlip\":\"12/16053\",\"DatePrinted\":null,\"BillStatus\":null,\"BatchPrint\":null}"}
Thanks for your help...
Depending on what you intend to do;
inside success:
if (response.d != "") {
var responseObject = JSON.parse(response);
$("#YourTextBoxId").val(responseObject.d.BusinessName);
}
or
$("#<%= YourServerTextBox.UniqueId %>").val(responseObject.d.BusinessName);

Asp.net webform with flot.js chart on return Json does not work

I am using ASP.NET webforms for flot charts I connected to database in test.aspx.cs file using [Webmethod] where I can return json.
I stored the return value both in textarea and $.plot(placeholder, [and also here], options) It does not print the graph in placeholder however when I do:
var data = past
the value of textarea here and run applicationn it prints to me the value.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<string> GetLocation(string location)
{
List<string> result = new List<string>();
StringBuilder strQuery = new StringBuilder();
strQuery.Append("SELECT Location.Nome_Location, DATEPART(day, Statistiche.Data_Statistica) AS SDay, COUNT(Statistiche.ID_Tabella) AS Stats");
strQuery.Append(" FROM Statistiche INNER JOIN Tabelle ON Statistiche.ID_Tabella = Tabelle.ID_Tabella INNER JOIN");
strQuery.Append(" Location ON Statistiche.ID_Colonna_Statistica = Location.ID_Location");
strQuery.Append(" WHERE (Statistiche.ID_Tabella = 2) AND (Statistiche.ID_Box = 60) AND (Location.Nome_Location = 'Albilò')");
strQuery.Append("GROUP BY Location.Nome_Location, DATEPART(day, Statistiche.Data_Statistica)");
string query = strQuery.ToString();
SqlConnection con = new SqlConnection("");
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
int counter = 1;
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (counter == 1)
{
result.Add("[{'label': 'Europe (EU27)','data':[[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]");
}
else
result.Add("[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]");
if (counter==31)
{
result.Add("[" + dr["SDay"].ToString() + "," + dr["Stats"].ToString() + "]]}]");
}
counter++;
}
return result;
}
$.ajax({
type: "POST",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "test.aspx/GetLocation",
data: "{'location':'Albilò'}",
success: function drawChart(msg) {
var options = { lines: { show: true }, points: { show: true }, xaxis: { tickDecimals: 0, tickSize: 1} };
var ddata = [];
var data = msg.d;
for (var i = 0; i < 32; i++) {
ddata.push(data[i]);
}
var placeholder = $("#placeholder");
$("#txtvalue").val(ddata);
var datad = $("#txtvalue").text();
$.plot(placeholder, ddata, options);
},
error: function () {
alert("call is called111");
}
});
First of all, why do you create JSON yourself? You've already specified to return JSON in you attributes.
Refactore method to return simple array of POCO objects like
[Serializable]
public class pocoObject
{
public string Label;
..
}
Then your method should just return list of object and have attributes set up:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<pocoObject> GetLocation(string location)
{
...
return result; // result is list of pocoObjects
}
Flot.js is rather sensitive to data you set as source, so after this take a look at data in firebug, it should be correct json formatted data. So please visit wiki and also compare your data to working samples.
This how you can initiliaze legend names of you plot:
$(function () {
var d1 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25)
d1.push([i, Math.sin(i)]);
var d2 = [];
for (var i = 0; i < Math.PI * 2; i += 0.25)
d2.push([i, Math.cos(i)]);
var d3 = [];
for (var i = 0; i < Math.PI * 2; i += 0.1)
d3.push([i, Math.tan(i)]);
$.plot($("#placeholder"), [
{ label: "sin(x)", data: d1},
{ label: "cos(x)", data: d2},
{ label: "tan(x)", data: d3}
], {
series: {
lines: { show: true },
points: { show: true }
},
xaxis: {
ticks: [0, [Math.PI/2, "\u03c0/2"], [Math.PI, "\u03c0"], [Math.PI * 3/2, "3\u03c0/2"], [Math.PI * 2, "2\u03c0"]]
},
yaxis: {
ticks: 10,
min: -2,
max: 2
},
grid: {
backgroundColor: { colors: ["#fff", "#eee"] }
}
});
});

Resources