I'm working on google map for live tracking. i have to change markers according to database Updation.
This is a testLocs variable. i want to make it dynamic.
var testLocs = {
1: { info:'Demo', lat:31.933517, lng:74.910278 },
2: { info:'Demo', lat:32.073266 , lng:76.997681 },
3: { info:'Demo', lat:32.23139 , lng:78.425903 },
}
setMarkers(testlocs);
So, For that from ajax call every 3000 (3 seconds) i call ajax script.
So, I got response from ajax in this format.
In Console i got 3 Arrays from database in ajax response,
Array-1 : ["Device-1", "Device-2", "Device-3"]; // all device name
Array-2 : ["31.933517", "32.073266", "32.23139"]; // all latitude
Array-3 : ["74.910278", "76.997681", "78.425903"]; // all longitude
Now,I want to use it in Above var testLocs.
Whole Function,
function myTimer(new_latitude, new_longitude,new_name)
{
var new_latitude = new_latitude;
var new_name = new_name;
var new_longitude = new_longitude;
console.log(new_name);
console.log(new_latitude);
console.log(new_longitude);
var testLocs = {
1: { info:'Demo', lat:31.933517, lng:74.910278 },
2: { info:'Demo', lat:32.073266 , lng:76.997681 },
3: { info:'Demo', lat:32.23139 , lng:78.425903 },
}
setMarkers(testlocs);
}
var myVar = setInterval(function(){ myTimer() }, 3000);
I tried with this but its not working.
var testLocs = {
new_latitude.forEach(function(single_value)
{
single_value_latitude = single_value;
// alert(single_value_latitude);
});
}
EDIT :
Ajax code
(function worker() {
$.ajax({
type: "POST",
dataType: "json",
// data: {business1: business1},
url: '<?php echo site_url('home/automatic_fetch_data'); ?>',
success: function (data) {
//alert(data);
var new_lat = [];
var new_lng = [];
var new_name = [];
$.each(data, function(k, v) {
var lati = v['latitude'];
var lngi = v['longitude'];
var namei = v['name'];
new_lat.push(lati);
new_lng.push(lngi);
new_name.push(namei);
});
var new_latitude = new_lat;
var new_longitude = new_lng;
var new_name = new_name;
// console.log(new_latitude);
// console.log(new_longitude);
myTimer(new_latitude, new_longitude,new_name);
},complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 3000);
}
});
})();
I got below array in after ajax response, console.log(data);
Array :
Array with 4 Object and in each object i got all the information device_id, device_name, latitude, longitude.
In Console i got array in this information.
[Object { id="1", device_id="1", device_name="Device-1", latitude="29.630771", longitude="74.910278"}, Object { id="2", device_id="2", device_name="Device-2", latitude="32.073266", longitude="76.997681"}, Object { id="3", device_id="5", device_name="Device-3", latitude="29.630771", longitude="74.910278"}, Object { id="5", device_id="3", device_name="Device-3", latitude="29.630771", longitude="74.910278"}]
transformation code (3 arrays into object with another 3 objects):
var new_name = ["Device-1", "Device-2", "Device-3"];
var new_latitude = ["31.933517", "32.073266", "32.23139"]; // all latitude
var new_longitude = ["74.910278", "76.997681", "78.425903"];
var testLocs = new_name.reduce(function (res, curr, currentIndex) {
res[currentIndex + 1] = {
info: new_name[currentIndex],
lat: new_latitude[currentIndex],
lng: new_longitude[currentIndex]
};
return res;
}, {});
console.log(testLocs);
so, your function may look like:
function myTimer(new_latitude, new_longitude,new_name) {
console.log(new_name);
console.log(new_latitude);
console.log(new_longitude);
var testLocs = new_name.reduce(function (res, curr, currentIndex) {
res[currentIndex + 1] = {
info: new_name[currentIndex],
lat: new_latitude[currentIndex],
lng: new_longitude[currentIndex]
};
return res;
}, {});
setMarkers(testlocs);
}
Related
I am try to call a function onblur of my three elements in my table
but i am getting this error in my console
"((m.event.special[e.origType] || (intermediate value)).handle || e.handler).apply is not a function".
So onblur these elements i want to call my function.Please do have a look at my code once.
Apologies for my bad handwriting here .I am new to javascript
jq.ajax({
url: '/soap/ajax/36.0/connection.js',
dataType: 'script',
success: function() {
jq(document).ready(function() {
// call tookit dependent logic here
jq('#gbMainTable').on('blur', 'tr.dr td[name="v4"] select','tr.dr td[name="v6"] select','tr.dr td[name="v7"] input', function()
{
var thisInput = this;
console.log('thisInput.value',thisInput.value);
var thisInput1 = jq(this);
var thisRow = thisInput1.parents('tr.dr:first');
console.log('thisRow',thisRow);
var agentInput1 = thisRow.find('td:eq(7)');
console.log('agentInput1',agentInput1);
var finds1 = agentInput1.find('select');
console.log('finds1',finds1);
var agentInput2 = thisRow.find('td:eq(8)');
console.log('agentInput2',agentInput2);
var finds2= agentInput2.find('input');
if(agentInput1.text()!=='' & thisInput.value=='Programmable Cntrls/Welders/AC Drives/Soft Starts'){
exampleFunction('Programmable',agentInput1.text(),agentInput2.text());
console.log('YES');
}
else if(agentInput1.text()!=='' & thisInput.value=='Electro Mechanical'){
exampleFunction('Electro-Mechanical',agentInput1.text(),agentInput2.text());
}
});
});
},
async: false
});
function exampleFunction(Warranty,Years,charge) {
var state = { // state that you need when the callback is called
output : null,
startTime : new Date().getTime()};
var callback = {
//call layoutResult if the request is successful
onSuccess: doThis,
//call queryFailed if the api request fails
onFailure: queryFailed,
source: state};
sforce.connection.query(
"SELECT InOut__c,PlantPct__c,T37Pct__c,TotalPct__c,Type__c,Warranty_Code__c,Years__c FROM WarrantySpecialLine__c where InOut__c = '" +charge+"' and Years__c = '"+Years+"' and Type__c = '" +Warranty +"'",
callback);
}
function queryFailed(error, source) {
console.log('error: '+error);
}
/**
* This method will be called when the toolkit receives a successful
* response from the server.
* #queryResult - result that server returned
* #source - state passed into the query method call.
*/
function doThis(queryResult, source) {
if (queryResult.size > 0) {
var output = "";
// get the records array
var records = queryResult.getArray('records');
// loop through the records
for (var i = 0; i < records.length; i++) {
var warrantySpecial = records[i];
console.log(warrantySpecial.PlantPct__c + " " + warrantySpecial.TotalPct__c + " " +warrantySpecial.T37Pct__c );
}
}
}
I am developing an web app in which the user will be able to identify the location from map by clicking on the map (I use jquery 3.1). The problem is that I have to make some ajax calls, one depend on other, and on the last call the result it's not returned as a whole (full array) and I received only a part of array.
The problem survives from var a4.
How I can make that a4 result to be send as a full array because I tried with deferred but with no expecting result?
var getLocDetails = function () {
// Parse a web api based on user lat & lon
var a1 = $.ajax({
method: 'GET',
url: 'http://nominatim.openstreetmap.org/reverse?lat=44.43588&lon=26.04745&accept-language=ro&format=json'
});
// Get osm_type & osm_id and parse another web service to get a XML document (Ex.: https://www.openstreetmap.org/api/0.6/way/28240583)
var a2 = a1.then(function (data) {
return $.ajax({
method: 'GET',
url: 'https://www.openstreetmap.org/api/0.6/' + data.osm_type + '/' + data.osm_id
})
});
// Get all 'ref' attribute from every 'nd' node from XML and make an array with this values
var a3 = a2.then(function (data) {
var osmChildren = data.documentElement.childNodes;
var out = [];
for (var i = 0; i < osmChildren.length; i++) {
if (osmChildren[i].nodeName == 'way') {
var wayChildren = osmChildren[i].childNodes;
for (var j = 0; j < wayChildren.length; j++) {
if (wayChildren[j].nodeName == 'nd') {
var ndRef = Number.parseInt(wayChildren[j].getAttribute('ref'));
out.push(ndRef);
}
}
}
}
return out;
});
// HERE IS THE PROBLEM
// Based on array returned from a3, I am parsing every link like 'https://www.openstreetmap.org/api/0.6/node/ + nodeRef' to extract every lat and lon values for extreme points
var a4 = a3.then(function (data) {
var defer = $.Deferred();
var out = [];
for (var i = 0; i < data.length; i++) {
var nodeRef = data[i];
var nodeUrl = 'https://www.openstreetmap.org/api/0.6/node/' + nodeRef;
$.ajax({
method: 'GET',
url: nodeUrl
}).done(function (response) {
var node = response.documentElement.firstElementChild;
var lat = Number.parseFloat(node.getAttribute('lat'));
var lng = Number.parseFloat(node.getAttribute('lon'));
out.push([lat, lng]);
defer.resolve(out);
});
}
return defer.promise();
});
// When a4 is done, based his result, I have to have an array of lat & lon coordonates, but I recived only 1-2 coordonates even I have 10.
a4.done(function (data) {
console.log(data);
// Here I have to draw a polygon
});
}
you need to handle the requests in an array, as what you are doing tends to resolve the callback for a4 before all are complete.
To do this we can use $.when function
var req = [];
// Based on array returned from a3, I am parsing every link like 'https://www.openstreetmap.org/api/0.6/node/ + nodeRef' to extract every lat and lon values for extreme points
var a4 = a3.then(function (data) {
var defer = $.Deferred();
var out = [];
for (var i = 0; i < data.length; i++) {
var nodeRef = data[i];
var nodeUrl = 'https://www.openstreetmap.org/api/0.6/node/' + nodeRef;
req.push(
$.ajax({
method: 'GET',
url: nodeUrl
}).done(function (response) {
var node = response.documentElement.firstElementChild;
var lat = Number.parseFloat(node.getAttribute('lat'));
var lng = Number.parseFloat(node.getAttribute('lon'));
out.push([lat, lng]);
})
);
}
$.when.apply($, req).done(function(){
return defer.resolve(out);
});
return defer.promise();
});
I have a search form to call a Solr index, filled with geolocations:
jQuery('.form-submit', element).click(function (e) {
e.preventDefault();
search();
});
function search() {
useBBOX = false;
combinedExtent = ol.extent.createEmpty();
data.map.getLayers().forEach(function (layer, index, array) {
if (layer.getSource() instanceof ol.source.Vector) {
var source = layer.getSource().getSource();
var url = data.opt.urls[source.get('machineName')];
var newSource = new ol.source.Vector({
loader: getLoader(data, url),
format: new ol.format.GeoJSON(),
strategy: ol.loadingstrategy.bbox,
reloadOnZoomChange: true,
reloadOnExtentChange: true
});
newSource.set('machineName', source.get('machineName'));
var newCluster = new ol.source.Cluster({
source: newSource,
distance: 200
});
layer.setSource(newCluster);
}
});
}
function getLoader(data, url) {
return function (extent, resolution, projection) {
var bbox = ol.proj.transformExtent(extent, data.map.getView().getProjection(), 'EPSG:4326');
var params = {};
if (data.opt.paramForwarding) {
var get_params = location.search.substring(location.search.indexOf('?') + 1).split('&');
jQuery.each(get_params, function (i, val) {
if (val.length) {
var param = val.split('=');
params[decodeURIComponent(param[0])] = (param[1] !== undefined) ? decodeURIComponent(param[1].replace(/\+/g, ' ')) : '';
}
})
}
if (useBBOX == true) {
params.bbox = bbox.join(',');
params.zoom = data.map.getView().getZoom();
}
var searchQuery = jQuery('#input-search-address').val();
if (searchQuery != 'undefined' && searchQuery != null) {
url = url.substr(0, url.lastIndexOf("/") + 1);
url = url + searchQuery;
}
jQuery(document).trigger('openlayers.bbox_pre_loading', [{
'url': url,
'params': params,
'data': data
}]);
var that = this;
jQuery.ajax({
url: url,
data: params,
success: function (responsdata) {
var features = that.getFeaturesInExtent(extent);
jQuery(features).each(function (i, f) {
that.removeFeature(f);
});
var format = new ol.format.GeoJSON();
var features = format.readFeatures(responsdata, {featureProjection: projection});
that.addFeatures(features);
that._loadingFeatures = false;
if (!ol.extent.isEmpty(that.getExtent())) {
combinedExtent = ol.extent.extend(combinedExtent, that.getExtent());
if (useBBOX == false) {
useBBOX = true;
}
}
}
});
};
}
Basically, it fetches 3 layers, each containing a number of markers. I'ld like to autozoom the map based on those markers. Therefore I'm looking for the extent. The combinedExtent does contain all correct extents...
... but when I add data.map.getView().fit(combinedExtent, data.map.getSize()) INSIDE the getLoader function, it's not working. I looks like only 1 extent get plotted on the map.
Whenever I try to log the combinedExtent in the search() function, I get a weird error...
Google told me I had to wait until the getState() of newSource was ready, but that didn't work out...
So, I'm looking for a solution. My guess would be the use of the ajax return in getLoader...
I just had this issue, so I have a function to listen until the source is ready and finished loading before giving a count of features (otherwise it would update the log with every iteration). Just change my source name (any variable with "parcelquery in it) with yours and hopefully it will at least put you in the right direction.
var listenerKey = wfsSource_parcelquery.on('change', function(e) {
if (wfsSource_parcelquery.getState() == 'ready') { //says source is done loading
var featureCount = wfsSource_parcelquery.getFeatures().length; //getting number of features resulting from query
ol.Observable.unByKey(listenerKey);
// use vectorSource.unByKey(listenerKey) instead
// if you do use the "master" branch of ol3
}
alert("Your query returned "+ featureCount + " results.");
var extent = lyr_parcelquery.getSource().getExtent();
console.log(extent);
map.getView().fit(extent, map.getSize());
});
i have a codepen that basically takes value from openweather and tries to set it according to an app state. I cannot seem to figure out why i am getting an undefined value for this.tempValue and this.tempType. here's the code:
`
var app = {
latitude: '',
longitude: '',
tempType : " C",
tempValue: "",
getGeoLoc: function (id) {
//Removed timeout option due to error
var options = {}; //{ timeout: 3 };
navigator.geolocation.getCurrentPosition(this.foundLoc.bind(this), this.noloc, options);
},
foundLoc : function(position) {
this.latitude = position.coords.latitude;
this.longitude = position.coords.longitude;
console.log('coords ', this.latitude, this.longitude);
// Call your get weather function
// Using call to bind the context of `this`
this.getWather.call(this);
},
// Error method
noloc: function(err) {
console.log(err.message);
},
// Method to get your weather after location is found
getWather: function() {
var url = 'http://api.openweathermap.org/data/2.5/weather?lat=' + this.latitude + '&lon=' + this.longitude +'&APPID=7bda183adf213c8cfa2ef68635588ef3';
console.log('URL is: '+url);
$.getJSON(url, function(data) {
console.log('Your weather data', data);
// Do your dom stuff here
$("#location").text(data.name);
console.log("#5 does this work??? ", data.main.temp.toString().slice(0, 2));
var temp = '';
this.tempValue = data.main.temp.toString().slice(0, 2);
var type = "";
type = this.tempType;
console.log("#6 what's inside tempType. ", this.tempType);
$("#temp").html(this.tempValue + this.tempType);
$("#message").html(data.weather[0].description);
console.log("#3 what is in the description property. ", data.weather[0].description);
//function to convert C to F and vice versa and return a string
function convert (value) {
var celsius = '';
var fahrenheit = '';
var convertedToF = 0;
var convertedToC = 0;
if(value == 'fahrenheit') {
convertedToF = data.main.temp * 9/5 + 32;
this.tempValue = convertedToF;
console.log("#4 fahrenheit value is ", convertedToF);
}
if(value == 'celsius') {
convertedToC = data.main.temp - 32;
convertedToC *= 5/9;
this.tempValue = convertedToC;
}
}
$("#convert").click( function () {
convert('celsius');
}
);
});
},
};
// Make sure to call your initialising function
app.getGeoLoc();
codepen url is: http://codepen.io/rush86999/pen/MKMywE/?editors=1010
Inside the success callBack of getJSON, the this object will point to jqXHR object(as mentioned by #dfsq). That is why you are seeing undefined for that two variables. There a different methods available to fix this. one of them would be,
$.getJSON(url, function(data) {
// ...YOUR CODE...
}.bind(this));
I am pretty new to javascript and jquery. I currently have a xml file that I'm trying to parse by using jquery and javascript, but for some reason the values that I store on the array are not being saved.
var categories = new Array(); // Array for the categories
var data = {
categories: []
};
var sources = [
{
src:'',
title: '',
desc: ''
}];
var i = 0;
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
var el = $(this);
var categoryName = el.find('category').text();
var p = categories.indexOf(categoryName);
sources[i] = [];
sources[i].src = el.find('media\\:content, content').attr('url');
sources[i].title = el.find("title").text();
sources[i].desc = 'Moscone Center';
if( p == -1) {
categories.push(categoryName);
var category = {
name: categoryName,
videos: []
};
}
i++;
});
});
If i do console.log(categories) it prints all the categories on the array but if I do console.log(categories.length) I keep getting 0...
console.log(categories.length); // This should be outputting 5 but I keep getting 0 for the size.
for (var i=0; i<categories.length; i++) {
var category = {
name: categories[i],
videos: []
};
}
I appreciate any help that anybody can give me. Thanks
$.get function is asynchronous so you should try putting the logging inside the callback function.
$.get('fakeFeed.xml', function (info) {
$(info).find("item").each(function () {
....
});
console.log(categories.length);
});