Leaflet markers duplicating, removeLayer problem - ajax

I have Ajax function in my Laravel project. I'm taking data from db and send them on Leaflet map.
When I have setInterval, markers starts to duplicate. Unfortunately removeLayer can not help me, or I'm ussing it wrong.
This is my code
function callAjax() {
$.ajax({
url: '/device_new',
type: 'GET',
dataType: 'json',
success: function(data) {
markerLayer.removeLayer();
var markerLayer = L.featureGroup().addTo(map);
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
marker.addTo(markerLayer);
}
}
map.fitBounds(markerLayer.getBounds());
},
});
setInterval(callAjax, 3000);
}
Any idea what could be a problem?

removeLayer(<Layer>) removes a single given layer from the featureGroup.
You need
markerLayer.clearLayers()
to remove all layers.

Change your code to:
function callAjax() {
$.ajax({
url: '/device_new',
type: 'GET',
dataType: 'json',
success: function(data) {
markerLayer.clearLayers();
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
marker.addTo(markerLayer);
}
}
map.fitBounds(markerLayer.getBounds());
},
});
setInterval(callAjax, 3000);
}
function loadMap() {
// Where you want to render the map.
var element = document.getElementById('osm-map');
// Height has to be set. You can do this in CSS too.
element.style = 'height:405px;', 'width:500px;';
// Create Leaflet map on map element.
map = L.map(element);
// Add OSM tile leayer to the Leaflet map.
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© OpenStreetMap contributors'
}).addTo(map);
map.pm.addControls({
position: 'topleft',
});
//********************** ADD HERE **************
var markerLayer = L.featureGroup().addTo(map);
}

Related

How to use for loop in ajax success function?

This is my alert output result:
The above picture array is my result that is get from table using ajax request.but i don't know how to use in for loop and i have tired in for loop the value is splitted one by one like
My code
<script type="text/javascript">
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
alert(data);
var result = data;
var arr = result;
for (var i = 0; i < arr.length; i++){
document.write("<br><br>array index: " + i);
var obj = arr[i];
for (var key in obj){
var value = obj[key];
document.write("<br> - " + key + ": " + value);
}
}
}
});
});
</script>
You can modify your script like this and then do whatever Logic you want for the response
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
myGoodFunctionToHandleResponse(data);
}
});
});
function myGoodFunctionToHandleResponse(data){
for(let i in data){
console.log(data[i]);
}
}
I have forgot to put JSON.parse() this function after success function and so i didn't get the correct result so far.
<script type="text/javascript">
$('#TDate').on('input change', function() {
var name =$('#TDate').val();
var credit = 0;
var debit = 0;
$.ajax({
type: "POST",
url: "<?php echo base_url();?>BookKeeping/item",
data: {name:name},
datatype: 'json',
success: function (data) {
var result = JSON.parse(data)
var mycars = result;
for (i in mycars)
{
if( mycars[i].dc == "C"){
var credit = mycars[i].Amt;
}
else{
var debit = mycars[i].Amt;
}
if(credit > debit)
{
var bal = credit - debit;
}
else{
var bal = debit - credit;
}
}
$('#bal').val(bal);
}
});
});
</script>

css Property for jquery ajax success function

I'm working with MVC3, using the following jQuery AJAX call:
function Displaymaingrid () {
var Geo = $('#ddlGeo').val();
var Vertical = $('#ddlVertical').val();
var Month = $('#ddlMonth').val();
if(Vertical == "All")
{
var Flag = 1;
}
else
{
var Flag = 2;
}
$.ajax({
url: "#Url.Action("TRUnutilizedOwnershipChange", "TravelReady")",
datatype: "html",
type: "post",
data: {strGeo:Geo, strVertical:Vertical, intMonth:Month, intFlag:Flag},
error: function(){},
success: function(data){
$('.travTableContent').empty();
var text3 = data.data.lstunutilizedownershipentities;
for( var item in text3)
{
$('<tr />').html(text3[item]).appendTo('.travTableContent');
$('<td />').html(text3[item].CurrentOwnership).appendTo('.travTableContent');
$('<td />').html('' + text3[item].cnt + '').appendTo('.travTableContent');
}
}
});
}
I want to set the CSS property for success function:
$('<tr />').html(text3[item]).appendTo('.travTableContent');
I want to add the following CSS property in the above line:
("tr:odd").css("background-color", "#d0d1e2")
Where do I need to insert this line?
Add it after the "for" statement.
for( var item in text3){
$('<tr />').html(text3[item]).appendTo('.travTableContent');
$('<td />').html(text3[item].CurrentOwnership).appendTo('.travTableContent');
$('<td />').html('' + text3[item].cnt + '').appendTo('.travTableContent');
}
$("tr:odd").css("background-color", "#d0d1e2");

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/

How to initialize jquery easy slider plugin to my plugin?

I have a plugin which retrieves JSON data from external file and appends it to the "div#slider", the data is retrieved and is working fine but the easySlider is not initialized after retrieving the data successfully . and the slide does not starts.
I have codes on http://lkamal.com.np/r3dImage
my plugin code is as follows:
(function($) {
$.fn.r3dImage = function(options){
var defaults = {
url: 'ajax/test.txt',
pause: 2000,
};
var options = $.extend(defaults, options);
//retrive json file
return this.each(function() {
obj = $(this);
var body = obj.html();
getJson();
});
function getJson(){
$.ajax({
type: "POST",
url: options.url,
dataType: "json",
cache: false,
contentType: "application/json",
success: function(data) {
//alert("Success");
$.each(data.dashboard, function(i,post){
obj.html('<li><img src="' + post.ImageUrl + '" title="' + post.OverlayText +'" /></li>');
});
$(obj).easySlider({
pause: options.pause
});
},
error: function(xhr, status, error) {
alert(xhr.status);
}
});
};
/* this.each(function() {
$(options.container).easySlider({
pause: options.pause
});
});*/
};
})(jQuery);
and another is easy slider 1.7.
or
can i do it inside the easyslider plugin.
How Can i merge this two plugin and make one.
I got solution for this also.
$(function() {
$.fn.r3dImage = function(param) {
var options = {
url : "",
pause : 2000,
feedFetchDelay : 10
};
this.each(function() {
var element = $(this);
//alert(element.attr('id'));
element.html("<ul></ul>");
options = $.extend(options,param);
if(options.url=="") { console.log("URL is not specified"); }
else {
getJsonFeed(element); //retrives json feed and appends to respective div
setInterval(getJsonFeed, options.feedFetchDelay*1000*60); //Time interval in milli seconds converted to minute using delay*1000*60
}
});
function getJsonFeed(element){
//function to retrive json feed start using post of json data
$.post(
options.url,
function(data) {
//alert(data.dashboard);
html = '';
$.each(data.dashboard, function(k,v) {
html += '<li>';
html += '<a href="'+v.TargetUrl+'" target="'+v.Target+'">';
html += '<img src="' + v.ImageUrl + '" alt="' + v.Alt +'" title="' + v.OverlayText +'" />';
html += '</a><p>'+v.OverlayText+'</p></li>';
});
//alert(html);
$("ul", element).append(html); //appending the json data with respective div
//initialize the slider to easy slider
$(element).easySlider({
auto: true,
continuous: true
});
},
"json"
);
}
}
});

google maps call within a For Loop not returning distance

I am calling google maps within a for loop in my javascript as I have mulitple routes that need to be costed separately based on distances.
Everything works great except that the distance is only returned for one of the routes.
I have a feeling that it is something to do with the way I have the items declared within the ajax call for the maps. Any ideas what could be the issue from the code below?
for (var i = 1; i <= numJourneys; i++) {
var mapContainer = 'directionsMap' + i;
var directionContainer = $('#getDistance' + i);
$.ajax({
async: false,
type: "POST",
url: "Journey/LoadWayPoints",
data: "{'args': '" + i + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
if (msg.d != '[]') {
var map = new GMap2(document.getElementById(mapContainer));
var distance = directionContainer;
var wp = new Array();
//routes
var counter = 0;
$.each(content, function () {
wp[counter] = new GLatLng(this['Lat'], this['Long']);
counter = counter + 1;
});
map.clearOverlays();
map.setCenter(wp[0], 14);
// load directions
directions = new GDirections(map);
GEvent.addListener(directions, "load", function () {
alert(directions.getDistance());
//directionContainer.html(directions.getDistance().html);
});
directions.loadFromWaypoints(wp, { getSteps: true });
}
}
});
}
The issue was down to a non declared variable. Just before the GEvent call there is a variable called 'directions' but this was never actually declared with a var so it wasn't being cleared out.
var directions = new GDirections(map);
Doing the above worked for me.

Resources