I need to secure the values of LatLng that are used to draw lines on a Google Map since I have some work that I did and I don't want anybody to copy it ..
Are the points used to draw the lines visible to anyone to see it and copy it or it is eventually secured?
I draw the Lines in the success function of an ajax call:
var position = new google.maps.LatLng(x, y);
var myOptions = {
zoom: 11,
center: position,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("googlemap"),
myOptions);
$.ajax({
type: "GET",
dataType: "json",
url: url,
success: function (data) {
$.each(data, function () {
$.each(this, function (index, Segment) {
$.each(Segment, function () {
for (var i = 0; i < Segment.X.length - 1; i++) {
var line = new google.maps.Polyline({
path: [new google.maps.LatLng(Segment.Y[i], Segment.X[i]), new google.maps.LatLng(Segment.Y[i + 1], Segment.X[i + 1])],
strokeColor: color,
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
}
});
});
});
}
});
So is the point copyable for the fact that it is drawn in the client side ?
You can't secure the points as long as you render the line on clientSide. As soon as you create a polyline this polyline is accessible and the path can be retrieved(no matter if you encrypt the JSON somehow).
The only approach I see so far is a serverside rendering, e.g. an image containing the line as overlay or a FusionTableLayer(created from a fusionTable with private access)
Yes, client-side code is by its nature insecure and copyable. For instance you make an AJAX request for a specific URL, which will return some JSON with a series of points. If someone else accessed that URL directly, they'd be able to get the points from that same JSON.
Related
I have been trying to pull in information from my web API into my application.
Currently i am just trying to pull in data not submit it yet. The API is working and running as a service on my system.
It is returning data in json format an example of the data returned by the WEB API.
[
{
"$id": "1",
"id": "6c32e378-0f06-45da-9dda-0515c813cd5d",
"application_name": "FDB INTERFACE",
"description": "Interface for FDB decision support",
"active": true,
"tbl_update_header": []
},
{
"$id": "2",
"id": "58f68624-3803-43ff-b866-0a507ea85459",
"application_name": "HPM",
"description": "Helix Health Practice Manager",
"active": true,
"tbl_update_header": []
},
This is my page just to try and get the some data to display
<html>
<head>
<title></title>
<script src="~/Scripts/jquery-2.1.1.js"></script>
<script type="text/javascript">
$.ajax({
type: "GET",
url: "http://localhost:9981/API/Application",
processData: true,
data: {},
dataType: "json",
error: function (jqXHR, textStatus, errorThrown) {
// debug here
alert(jqXHR);
},
//error: function(error, data){
// console.log(error)
//},
success: function (data) {
//Clear the div displaying the results
$("productView").empty();
//Create a table and append the table body
var $table = $('<table border="2">');
var $tbody = $table.append('<tbody />').children('tbody');
//data - return value from the web api method
for (var i = 0; i < data.lenght; i++) {
//adda new row to the table
var $trow = $tbody.append('<tr />').children('tr:last');
//add a new column to display name
var $tcol = $trow.append('<td/>').children('td:last').append(data[i].id);
//add a new column to display description
var $tcol = $trow.append('<td/>').children('td:last').append(data[i].description);
}
//display the table in the div
$table.appendTo('#productView');
}
});
</script>
</head>
<body>
<div id="productView"></div>
</body>
</html>
The page loaded but is empty and no error is returned from any section.
I run the web page from chrome/FF/IE none of them show error in dev mode and VS shows no errors. I am not sure if i am parsing the data wrong or calling to the wrong part of the json to display the data.
I must be doing something silly at this point but just cant get pass this part.
you can also set this property in your js file before ajax call
$.support.cors = true;
There is a typo in your success method...
success: function (data) {
//Clear the div displaying the results
$("productView").empty();
//Create a table and append the table body
var $table = $('<table border="2">');
var $tbody = $table.append('tbody /').children('tbody');
//data - return value from the web api method
for (var i = 0; i < data.length; i++){
//adda new row to the table
var $trow=$tbody.append('<tr />').children('tr:last');
//add a new column to display name
var $tcol = $trow.append('<td/>').children('td:last').append(data[i].application_name);
//add a new column to display description
var $tcol = $trow.append('<td/>').children('td:last').append(data[i].description);
//add a new column to display active
var $tcol = $trow.append('<td/>').children('td:last').append(data[i].active);
}
//display the table in the div
$table.appendTo('#productView');
It should be data.length and not data.lenght.
Success. The issue was with CORS. also with the spelling mistake of data.length
The code works fine and the results are what i was wanting to get . Thank you all for your assist.
To fix the issue i had to enable CORS in iis server side to allow cross domain access.
Your code above has a success function, but not an error function.
Try setting an error function, and then see what happens :
data: {},
dataType: "json",
error: function(jqXHR, textStatus, errorThrown ) {
// debug here
alert(jqXHR);
},
success: function() ...
I am working on a asp.net C# MVC web application and offers a jquery UI price range filter to filter the products based on selected price range. The resulted products are loaded via Ajax and everything seems to work fine upto now. However, after upgrading to the jQuery version 1.10.2 and jQuery UI 1.10.3, the same slider works on first load, but fails to load after Ajax requests. The following code is on the page where filter is being impelemented.
The same code is working fine with jQuery 1.7.1 and jQuery UI 1.10.0.
It appears that the slider is not initialized after content is loaded via Ajax, but not sure why! What could be wrong here?
$("#slider-range").slider({
range: true,
min: minValue,
max: maxValue,
values: [selectedMinValue, selectedMaxValue],
values: [selectedMinValue, selectedMaxValue],
slide: function (event, ui) {
//Note: Currency Custom formatting is not supported.
$(".currentMinPrice").html('#(Model.PriceRangeFilterContext.CurrencySymbol) ' + ui.values[0]);
$(".currentMaxPrice").html('#(Model.PriceRangeFilterContext.CurrencySymbol) ' + ui.values[1]);
},
change: function (event, ui) {
var url = removeParameter('#(currentURL)', "price");
var newUrl = url.replace(/&/g, '');
if (isAjaxRequest) {
callAjax(UpdateQueryString("price", ui.values[0] + "-" + ui.values[1], newUrl));
}
}
});
isAjaxRequest = true;
$(".currentMinPrice").html('#(Model.PriceRangeFilterContext.CurrencySymbol) ' + $("#slider-range").slider("values", 0));
$(".currentMaxPrice").html('#(Model.PriceRangeFilterContext.CurrencySymbol) ' + $("#slider-range").slider("values", 1));
}
Ajax function
$.ajax(
{
url: url,
type: 'POST',
success: function (result)
{
// Result is in html
$('#catalog').replaceWith(result);
$('#ajax-loading').hide();
DisplayFilter();
//Lazy Loading
$("img.lazy").show().lazyload(
{
effect: "fadeIn"
});
$(window).trigger("scroll");
}
});
I think you need to initialize your slider AFTER it is rendered. None of the DOM elements you create after your initial render will be intialized or bound by javascript you have already run.
So, 1st Encapsulate your initialization in a function:
function initSlider(passedMin, passedMax)
{
$("#slider-range").slider({
range: true,
min: passedMin,
max: passedMax,
values: [selectedMinValue, selectedMaxValue],
values: [selectedMinValue, selectedMaxValue],
slide: function (event, ui) {
//Note: Currency Custom formatting is not supported.
$(".currentMinPrice").html('#(Model.PriceRangeFilterContext.CurrencySymbol) ' + ui.values[0]);
$(".currentMaxPrice").html('#(Model.PriceRangeFilterContext.CurrencySymbol) ' + ui.values[1]);
},
change: function (event, ui) {
var url = removeParameter('#(currentURL)', "price");
var newUrl = url.replace(/&/g, '');
if (isAjaxRequest) {
callAjax(UpdateQueryString("price", ui.values[0] + "-" + ui.values[1], newUrl));
}
}
});
isAjaxRequest = true;
$(".currentMinPrice").html('#(Model.PriceRangeFilterContext.CurrencySymbol) ' + $("#slider-range").slider("values", 0));
$(".currentMaxPrice").html('#(Model.PriceRangeFilterContext.CurrencySymbol) ' + $("#slider-range").slider("values", 1));
}
}
Then in your AJAX, call your init function on success
$.ajax(
{
url: url,
type: 'POST',
success: function (result)
{
// Result is in html
$('#catalog').replaceWith(result);
$('#ajax-loading').hide();
DisplayFilter();
//Lazy Loading
$("img.lazy").show().lazyload(
{
effect: "fadeIn"
});
$(window).trigger("scroll");
initSlider(newMin, newMax)
}
});
How do I plot highchart Gauge with JSON Data?
I am working on highchart gauge, I got succes in showing the latest data from the database. I used JavaScriptSerializer for that
The code is..
<script type="text/javascript">
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'gauge',
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
//Other char parameter comes here
}
function (chart) {
setInterval(function () {
$.getJSON("S14.aspx", function (data, textStatus) {
console.log(data);
$.each(data, function (index, wind) {
var point = chart.series[0].points[0],
newVal = wind;
point.update(newVal);
});
});
}, 3000);
});
The code for JSON is
public string chartData1
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
List<double> _data = new List<double>();
GetData();
foreach (DataRow row in dt.Rows)
{
_data.Add((double)Convert.ToDouble(row["S11"]));
}
JavaScriptSerializer jss = new JavaScriptSerializer();
chartData1 = jss.Serialize(_data);
}
My JSON looks like
[1387204961992.4268,72]
Well the problem is that the dial of gauge is not moving according to the last values i need to refresh the page for that. I know this is happening because the GetData function is being executed only one time. I am stuck here.
How do I get the dial move according to the last values updates in the database?
Try to place this part of code
setInterval(function() {
$(function() {
$.getJSON('S12.aspx', function(data) {
$.each(data, function(val) {
if (val !== null)
{
var point = chart.series[0].points[0];
point.update(val);
}
});
});
})
},2000)
Inside callback chart, like here: http://www.highcharts.com/demo/gauge-speedometer
If you receive any errors,please attach.
I think there is a bug or something in the visual studio 2012 . I just paste the entire code on the new aspx page it it got working. I have not done anything else I just pasted the code on another page.
<script type="text/javascript">
$(function () {
$('#container1').highcharts({
chart: {
type: 'gauge',
alignTicks: false,
plotBackgroundColor: null,
plotBackgroundImage: null,
plotBorderWidth: 0,
plotShadow: false
},
title: {
text: 'Pressure Meter'
},
pane: {
startAngle: -150,
endAngle: 150
},
yAxis: [{
min: 0,
max: 1000,
lineColor: '#339',
tickColor: '#339',
minorTickColor: '#339',
offset: -25,
lineWidth: 2,
labels: {
distance: -20,
rotation: 'auto'
},
tickLength: 5,
minorTickLength: 5,
endOnTick: false
}, {
min: 0,
max: 1000,
tickPosition: 'outside',
lineColor: '#933',
lineWidth: 2,
minorTickPosition: 'outside',
tickColor: '#933',
minorTickColor: '#933',
tickLength: 5,
minorTickLength: 5,
labels: {
distance: 12,
rotation: 'auto'
},
offset: -20,
endOnTick: false
}],
series: [{
name: 'Pressure',
data: [80],
dataLabels: {
formatter: function () {
var psi = this.y,
bar = Math.round(psi / 14.50);
return '<span style="color:#339">' + psi + ' psi</span><br/>' +
'<span style="color:#933">' + bar + ' bar</span>';
},
backgroundColor: {
linearGradient: {
x1: 0,
y1: 0,
x2: 0,
y2: 1
},
stops: [
[0, '#DDD'],
[1, '#FFF']
]
}
},
tooltip: {
valueSuffix: ' psi'
}
}]
},
// Add some life
function (chart) {
setInterval(function () {
$.getJSON("S12.aspx", function (data, textStatus) {
$.each(data, function (index, wind) {
var point = chart.series[0].points[0],
newVal = wind;
point.update(newVal);
});
});
}, 3000);
});
});
</script>
In order for the chart to update, the browser somehow needs to request the latest data from the server. There are two ways it can do this:
A page refresh - the whole page is fetched again, with the latest data.
An Ajax request. This makes a request for just the data, without re-loading the entire page.
I presume you would like to update the chart without reloading the entire page. In order do to this, you need to find out about making ajax requests using jquery.
The highcharts site has some resources which will help you (e.g. http://www.highcharts.com/docs/working-with-data/preprocessing-live-data). You need to learn how to make an ajax call in javascript, and use the returned data to update your chart. You will also need to write the server side part which returns the ajax data. The example given is in php, but it should be fairly straight forward to do something similar in asp.net.
I'm trying to create a simple ASP.NET site which will use the offset or position functions provided by JQuery to pass the coordinates of a <div> element to an ASP.NET code behind via a button's OnClick method.
I've searched and found this example but it doesn't seem to work as expected, upon clicking no coordinates are returned.
How do I obtain the coordinates of a given <div> element and pass these to an ASP.NET button's OnClick method?
PART 1
To get location of the element you can use either offset() or position()
Fiddle: http://jsfiddle.net/XFfLP/
function test() {
var p = $("#testID");
var position = p.offset();//p.position()
$("#Field1").val(position.top);
$("#Field2").val(position.left);
}
PART 2
To pass data from pages to server code-behind you can use Web-Methods
Article: http://blog.nitinsawant.com/2011/09/draft-sending-client-side-variables-to.html
1. Web-Method sample code:
[System.Web.Services.WebMethod]
public static string AcceptData(object jsonData)
{
Customer newCust =(Customer)JsonConvert.DeserializeObject(jsonData.ToString(),typeof(Customer));
return "Server response: Hello "+newCust.FirstName;
}
2. JS sample Code:
var newCustomer = {
"FirstName": $("#txtFirstName").val(),
"LastName": $("#txtLastName").val(),
"Telephone": $("#txtTelephone").val()
}
var jsonData = "{'jsonData':'" + JSON.stringify(newCustomer) + "'}";//create string representation of the js object
//post data to server
$.ajax({
type: "POST",
url: 'Test.aspx/AcceptData',
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: ($.browser.msie) ? "text" : "json",
success: function(msg) {
//call successfull
var obj = msg.parseJSON();
alert(obj.d); //d is data returned from web services
//The result is wrapped inside .d object as its prevents direct execution of string as a script
},
error: function(xhr, status, error) {
//error occurred
alert(xhr.responseText);
}
});
I have created a javascript context menu using Jquery that works perfectly. But there are two options. The first one is to create this context menu in C# (If that's possible). The second way is to run a C# Function when a button in the menu is clicked. Which option is the best and how do i start? Kind regards
Javascript:
function Menu($div){
var that = this,
ts = null;
this.$div = $div;
this.items = [];
// create an item using a new closure
this.create = function(item){
var $item = $('<div class="item '+item.cl+'">'+item.label+'</div>');
$item
// bind click on item
.click(function(){
if (typeof(item.fnc) === 'function'){
item.fnc.apply($(this), []);
}
})
// manage mouse over coloration
.hover(
function(){$(this).addClass('hover');},
function(){$(this).removeClass('hover');}
);
return $item;
};
this.clearTs = function(){
if (ts){
clearTimeout(ts);
ts = null;
}
};
this.initTs = function(t){
ts = setTimeout(function(){that.close()}, t);
};
}
// add item
Menu.prototype.add = function(label, cl, fnc){
this.items.push({
label:label,
fnc:fnc,
cl:cl
});
}
// close previous and open a new menu
Menu.prototype.open = function(event){
this.close();
var k,
that = this,
offset = {
x:0,
y:0
},
$menu = $('<div id="menu"></div>');
// add items in menu
for(k in this.items){
$menu.append(this.create(this.items[k]));
}
// manage auto-close menu on mouse hover / out
$menu.hover(
function(){that.clearTs();},
function(){that.initTs(3000);}
);
// change the offset to get the menu visible (#menu width & height must be defined in CSS to use this simple code)
if ( event.pixel.y + $menu.height() > this.$div.height()){
offset.y = -$menu.height();
}
if ( event.pixel.x + $menu.width() > this.$div.width()){
offset.x = -$menu.width();
}
// use menu as overlay
this.$div.gmap3({
action:'addOverlay',
latLng: event.latLng,
content: $menu,
offset: offset
});
// start auto-close
this.initTs(5000);
}
// close the menu
Menu.prototype.close = function(){
this.clearTs();
this.$div.gmap3({action:'clear', name:'overlay'});
}
Well you could create a server control in C# and emit the menu from it, but since you already have a working menu it's just easier to call a server-side method in response to a click. If you're using jQuery it's as easy as:
$.ajax({
url: "/Path/To/MyMethod",
type: "POST",
dataType: "JSON",
data: <some POST data>,
contentType: "application/json; charset=utf-8",
success: function (result) {
// Do your stuff here
},
error: function (jqXHR, textStatus, errorThrown) {
// Report error
}
});
The implementation of the server-side part can be either a static [WebMethod] in an ASPX page, or if you're using MVC then it can be a direct call to a controller method.
I am assuming what you are trying to do is call a c# method when an Item on the context menu is selected. If you are using an MVC model this is pretty easy to do. Use a call as follows passing the parameters in JSON format. I am just using a skeleton method from my code as an example you would call LibraryRead method when you click on the Context Menu Link
Client Side
function LibraryRead() {
$.ajax({
url : 'Library/ReadLibrary',
type : "POST",
data : JSON.stringify(idLibrary),
dataType : "json",
contentType : "application/json; charset=utf-8",
success : function(result) {
$(result).each(function() {
....Process Results
});
},
error : function() {
.....If something goes wrong, if you use a try catch in your code
which does not handle the exception correctly and something goes wrong
this will not be triggered. Use propper exception handling.
}
});
}
Server Side
// Post: /Library/ReadLibrary
[HttpPost]
public JsonResult ReadLibrary(int idLibrary)
{
try
{
var library = READ your library here from your data source
return this.Json(library);
}
else
{
return null;
}
}
catch (Exception ex)
{
//Exception handling omitted for simplicity
}
}
Do a search on google for MVC3 and JQuery / Javascript calls with JSON, there are loads of resources available.
If you are not using MVC pattern you may be able to use a web service or method in the code behind. You need to add the appropriate attribute over the method though like [Ajax.AjaxMethod()] or [WebMethod]