Getting an id array to pass to onclick function - javascript

I have a jQuery code that parses a JSON encoded string like this:
var results = JSON.parse(msg);
Then it does a foreach statement as such:
jQuery.each( results.stores,function(k,v){
var store_id = v.id;
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(v.lat,v.lng),
icon: image,
shadow: shadow,
shape: shape,
title: v.name+' : '+v.address
});
I need to be able to pass the id of the item that has been clicked to the onclick event so it can be passed to the PHP script to do the query properly. I am guessing I will have to create a function and then make that function call inside this area.
Here is the working onclick function, but it will only pass the first id within the JSON string:
Updated code
$("#list li").click(function(){
//var store_id = $(this).store_id;
var pathname = "ajax=1&store_id="+store_id+"&action=get_nearby_stores&distance="+distance+"&lat="+lat+"&lng="+lng+"&products="+$('#edit-products').val();
$("#pocp_content").load("file1.php?" + pathname)
});

Related

Create 2D Array out of another Array which is casted against an API

I'm working on a project using the opengeodata and some company-internal APIs. Therefore the code I'm using here is slightly changed.
First I'm using the Opencagedata Javascript API to get the lat/lng-Coordinates out of an address.
<script>
function geocode(query) {
$.ajax({
url: 'https://api.opencagedata.com/geocode/v1/json',
method: 'GET',
data: {
'key': 'MyKey',
'q': query,
'no_annotations': 1
},
dataType: 'json',
statusCode: {
200: function(response){ // success
var lat = response.results[0]['geometry']['lat'];
var lng = response.results[0]['geometry']['lng'];
$('#geo_result').text(lat + ' , ' + lng);
After that I'm using another internal API to get some information about places surrounding this location. Lets call them POI.
After getting those POIs I'm using splice to filter the three nearest POIs to the lat/lng Coordinates and filter on some specific keywords.
var radius = 1.5;
var POI = [];
var apiCall = $.get("CoorpAPI/" + radius + "/around/" + lat + "," + lng);
apiCall.done(function(result) {
var myLoc = result.filter(function(loc) {
return loc.id.substr(0, 3) != 'keyword';
});
$.each(myLoc, function(n, loc) {
POI.push(loc.id)
})
var top3 = POI.slice(0,3);
console.log(top3);
Now I want to run those three "top3" POIs ["AB1234", "BC2345", "CD3456"] against a second API which is returns location information.
Those information are supposed to be written into the same array into the second second dimension.
In the end I want to have something Like:
[
0: AB1234
Location Information: A
Location Information: B
1: CD2345
Location Information: C
Location Information: D
...
]
I guess the loop would have to look somewhat like this, but I'm not sure how to call the API and create a 2d-array out of the "top3" locations and the location information returned by the api:
for (var i = 0; i < top3.length; i++) {
var apiCall_2 = $.get("CoorpAPI_2"+top3[i]);
// ???
}
If I understand you correctly, you want to use a nested array inside POI to add more information after a second API call. One thing you can try is to push an array instead of just loc.id in the following manner:
POI.push([loc.id]);
Now you have a nested array in POI instead of a single string ID (I am guessing the ID is string; can be a number as well). For the second API call you can modify your code like this:
var apiCall_2 = $.get('CoorpAPI_2'+top3[i][0]);
In this way, you are using the ID which, is the first element in the nested array. Once you process all your data from API call 2, you can either push each data point separately into the nested array or, as another array like this:
// pushing each data points separately
top3[i].push(dataPoint1);
// ... up to say N data points
top3[i].push(dataPointN);
// adding as an array
top3[i].push([dataPoint1, dataPoint2, dataPointN]);
Your result will be like this:
[ ["AB1234", "dataPoint1", "dataPoint2"] ]
if you use the first approach and like this
[ [ "AB1234", ["dataPoint1", "dataPointN"] ], ]
if you use the second approach. Hope this helps.

How to create a json object with input variable

I want to create a JSON object with input variable. I have a 2 input field. when I click button i want to take input values and make a JSON object with that value. I cannot create a JSON object with entered value.
I try that
//getting the value of input as a variable
let id=document.querySelector("#id");
let title=document.querySelector("#title");
first I try the below. it sends a blank value instead of variable string
var vObj= '{"id":'+id.value+',"title":'+title.value+'}'
I also try that to
var vObj = {"id":{},"v_title":{}, "v_category":{}};
vObj.id=id.value;
vObj.title=title.value;
tried that
let asd=id.value;
let bsd=title.value;
var vObj = {id:asd, title:bsd}
it returns a blank value instead of variable value.
i am making a mistake that the trigger button has typo. i couldn't see that. sorry
You can create an object with name proeprties and then use JSON.stringify to turn this into valid JSON:
//let id = document.querySelector("#id").value;
let id = 'my_id';
//let title = document.querySelector("#title").value;
let title = 'my_title';
console.log('ID: ' + id);
console.log('Title: ' + title);
var vObj = { id: id, title: title };
var json = JSON.stringify(vObj);
console.log(json);
This line:
var vObj = { id: id, title: title };
Creates an object with an id with the value of the id variable, and a title with the value of the title variable.
This line:
var json = JSON.stringify(vObj);
Converts the object vObj to a JSON string.
Output:
ID: my_id
Title: my_title
{"id":"my_id","title":"my_title"}
Edit followimg #FelixKling comment
In ES6 it is possible to simplify the declaration of vObj using:
var vObj = {id, title};
This will create the same object with the assumed property names id and title. Obviously if your variable is not named id or title this will not work.
First create an object, then stringify it to JSON.
var jsonObj = JSON.stringify( { "id" : id, "title" : title } );

.map multiple entries from DB Query

I am trying to work out if you can have multiple "map objects" in the .set?
For example I have employees... I need one array per employee, or multiple map "key" objects maybe?
So maybe I need something like Map(0).get('UserID')
Map(1).get('UserID')
etc?
var map = new Map();
while not rs.eof
map.set('UniqueID', i)
.set('UserID', UserID)
.set('FullURL', URL)
.set('Age', 39)
.set('XXXX', XXX)
rs.movenext
wend
What I am looking to do is have multiple map objects i.e. 1 = UniqueID 1, 2 = UniqueID = 2.
Right now it brings back the last record.
You are setting the value against same variable again and again that's why in the end map shows you the last value. If you want to save an object against every unique value you can do it like that. You can use array if you want to instead of object. I hope this will solve your query.
Map overwrite the existing value that's what you are doing
var map1 = new Map();
var object={
UserID: 'UserID',
FullURL :'URL'};
map1.set('id', object);
map1.set('id', "2");
console.log(map1.get('id'))
Solution
var map = new Map();
var object = {};
while not rs.eof
object = {
UserID : UserID,
FullURL : URL
}
map.set(i, object )
rs.movenext
wend

How to get an array and use in datasource

So I have an ajax call that gathers an array:
function test(){
$.ajax({
url: '/whatever/here'.
data: data,
}).done(function(newData){
var getArray = newData.SubData;
newResults.push(getArray);
}
}
var newResults = [];
My issue is I have to save the array thats in the ajax call and use it outside of the function. So by pushing it into a new array, it creates another level of objects. So when I do a datasource call:
function standardCategoryDropDownEditor(container, options) {
$("<input data-bind='value:" + options.field + "'/>")
.appendTo(container)
.kendoDropDownList({
dataSource: newResults,
dataTextField: "Value",
dataValueField: "Key",
});
}
this produces nothing as there isn't anything on the first level since its now an object that has more objects in it. So how do I either go down a level to get the data or get it to be on the first level initially?
Hopefully I'm not misunderstanding, but if newData.SubData is an array that you want to add to newResults, but you actually want to append the newData.SubData array at the top level of newResults instead of pushing a new array into newResults (which would create an array of arrays), use concat instead of push.
So
var getArray = newData.SubData;
newResults.push(getArray);
becomes
var getArray = newData.SubData;
newResults = newResults.concat(getArray);
I figured it out. It's as simple as giving it an index so:
datasource = newResults[0];
This selects the first object so it gives you the rest of the objects.

How to set array value as function parameter, when iterating

I use google maps API to display markers on a map.
Each marker points to a shop on the map.
My problem is with creating the event handler for each mark, which will display the tooltip with information about the shop when the given mark will be clicked.
I use the text input to let the user type the city, and with jquery I handle the click event on the nearby submit button. Then I send the query to the php site, get following object back:
d: Object
error: false
lat: "52.3744440000"
lng: "9.7386110000"
shop: Array[2]
0: Object
address: "Addressstreet 12"
lat: "52.3761209000"
lng: "9.7387242000"
name: "Shop 1"
tel: "1234"
__proto__: Object
1: Object
length: 2
etc.
Now I use the lat and lng values which are coordinates of the city to center the map.
Then I send the shop array to the paintShops(shops) method:
function paintShops(shops){
for (var i = 0; i < shops.length; i++){
kl = shops[i];
var ka = parseFloat(kl.lat);
var kb = parseFloat(kl.lng);
tel = kl.tel;
address = kl.address;
var son = new google.maps.Marker({
position: new google.maps.LatLng(ka, kb),
map: map,
title: kl.name,
clickable: true
});
google.maps.event.addListener(son, 'click', function(son, tel, address) {
displayShopTooltip(son, tel, address);
}
My problem is in the last line of the above snippet: when I click on the mark, the parameters tel and address of the displayShopTooltip are undefined.
I'd like to know what to do to do not have this problem, or alternatively another approach.
Thanks in advance.
The problem you have is that by declaring tel and address within the listener you are setting them to undefined within the event handler callback (as there is no mechanism for passing in arbitrary parameters). The solution is to make sure the handler is within the same scope as (i.e. wrapped inside a function with) the marker. I'd recommend reading up about scope in javascript as there were one or two other errors you made (e.g. not properly declaring variables) - scope in javascript is handled very differently to other programming languages and takes a bit of getting used to.
function paintShops(shops){
for (var i = 0; i < shops.length; i++){
makeMarker(shops[i]);
}
function makeMarker(kl) {
var ka = parseFloat(kl.lat);
var kb = parseFloat(kl.lng);
var tel = kl.tel;
var address = kl.address;
var son = new google.maps.Marker({
position: new google.maps.LatLng(ka, kb),
map: map,
title: kl.name,
clickable: true
});
google.maps.event.addListener(son, 'click', function(son) {
displayShopTooltip(son, tel, address);
}
}
You have defined tel and address as parameters of your click handler, which doesn't make sense. You probably wanted to access your global variables instead:
google.maps.event.addListener(son, 'click', function(son) {
displayShopTooltip(son, tel, address);
}
Still, this way there can be only one shop (there is only one global tel and address). Use local variables and a closure instead:
function paintShops(shops) {
for (var i = 0; i < shops.length; i++) {
(function() {
var kl = shops[i];
var ka = parseFloat(kl.lat);
var kb = parseFloat(kl.lng);
var tel = kl.tel;
var address = kl.address;
var son = new google.maps.Marker({
position: new google.maps.LatLng(ka, kb),
map: map,
title: kl.name,
clickable: true
});
google.maps.event.addListener(son, 'click', function(son) {
displayShopTooltip(son, tel, address);
}
})();
}
}
The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.

Categories

Resources