Building Drop Down Options from Object - javascript

I have a landing page I'm working on, where I want the user to select a state, and then when the state is selected, the select dropdown below it will show the locations within that state. The list of locations comes from a json file where there is a list of store locations, with their attributes such as store name, state, etc. I've created an object, but I'm not sure how to populate the select based on the state. Also, the way I'm building the list of states may not be the best way either, so any help there would be great also. Thanks!
$(document).ready(function(){
var buildLocations = {
'settings': {
directoryListingItems : {},
directoryListingArray : [],
globalLatLong : null,
globalLatitude : geoip_latitude(),
globalLongitude : geoip_longitude(),
globalCity : geoip_city(),
globalState : geoip_region_name(),
locationRadius : 30,
NearbyLocationsCount : 0,
locationTotalPlaceholder: $('#location-number'),
locationNamePlaceholder : $('#location-name'),
stateDropdownArray : [],
stateDropdown : $('#state'),
locationDropdownArray : [],
locationDropdown : $('#location'),
},
init: function() {
bLs = this.settings;
buildLocations.getJSONLocations();
},
getJSONLocations: function() {
$.ajax({
url: "data/data.json",
dataType: "JSON",
success: buildLocations.getLocations
});
},
getLocations: function(results) {
// creating objects
for(var i = 0; i < results.locations.length; i++) {
bLs.directoryListingItems = {
store_id: results.locations[i].storeid,
title: results.locations[i].title,
latitude: results.locations[i].latitude,
longitude: results.locations[i].longitude,
state: results.locations[i].state,
distance: buildLocations.getLocationDistance(bLs.globalLatitude, bLs.globalLongitude, results.locations[i].latitude, results.locations[i].longitude)
};
bLs.directoryListingArray.push(bLs.directoryListingItems);
//Check if a state is already in the states array, if not, add it
if ($.inArray('<option value=\"' + bLs.directoryListingArray[i].state + '\">'+ bLs.directoryListingArray[i].state + '</option>', bLs.stateDropdownArray)==-1) {
bLs.stateDropdownArray.push('<option value=\"' + bLs.directoryListingArray[i].state + '\">'+ bLs.directoryListingArray[i].state + '</option>');
//alert("added"+ value.state);
}
//get selected state value
//if in state in bLs.directoryListingItems array matches this value, add item to array
//Add Each location to the locations dropdown
bLs.locationDropdownArray.push('<option value=\"' + bLs.directoryListingArray[i].storeid + '\">'+ bLs.directoryListingArray[i].title + '</option>');
//Count the number of locations that are within the set location radius of the users detected location
if (bLs.directoryListingArray[i].distance < bLs.locationRadius) {
bLs.NearbyLocationsCount++;
}
}
//Sort the states array in alphabetical order
bLs.stateDropdownArray.sort();
//run function to populate dropdowns
buildLocations.populateDOM();
},
compareDistances: function(a,b) {
if (a.distance < b.distance)
return -1;
if (a.distance > b.distance)
return 1;
return 0;
},
populateDOM: function() {
//populate the number inside the map marker
bLs.locationTotalPlaceholder.text(bLs.NearbyLocationsCount);
//populate the area next to the map marker with the users location and state
bLs.locationNamePlaceholder.text(bLs.globalCity + ", " + bLs.globalState);
//build state select dropdown
bLs.stateDropdown.html(bLs.stateDropdownArray);
buildLocations.populateDOMlocations();
},
populateDOMlocations: function() {
//$.each(bLs.directoryListingItems, function(index, value) {
//if (value.state="Florida") {
//alert(index)
///}
//});
//$.each(bLs.directoryListingItems, function(index, obj) {
//$.each(obj, function(attr, value) {
// console.log( attr + ' == ' + value );
//});
//});
//build locations select dropdown
bLs.locationDropdown.html(bLs.locationDropdownArray);
},
getLocationDistance : function(lat1,lon1,lat2,lon2) {
function deg2rad(deg) {
return deg * (Math.PI/180)
};
var R = 6371; // Radius of the earth in km
var dLat = deg2rad(lat2-lat1); // deg2rad below
var dLon = deg2rad(lon2-lon1);
var a =
Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2)
;
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = (R * c) * 0.6214; // Distance in miles
return Math.round( d * 10 ) / 10
},
};
// ====================================================== //
// Populate Locations
buildLocations.init();
});

I figured it out,
populateDOMlocations: function() {
bLs.currState = bLs.stateDropdown.val();
bLs.locationDropdownArray = [];
for(var l = 0; l < bLs.directoryListingArray.length; l++) {
if (bLs.directoryListingArray[l].state == bLs.currState ) {
bLs.locationDropdownArray.push('<option value=\"' + bLs.directoryListingArray[l].storeid + '\">'+ bLs.directoryListingArray[l].title + '</option>');
}
}
bLs.locationDropdownArray.sort();
//build locations select dropdown
bLs.locationDropdown.html(bLs.locationDropdownArray);
},

Related

if value is in array using includes not working

I have 2 arrays:
ids = [a,b,c,d,e,f....];
savedRepods = [e,f];
function getPoints(){
for (var i = 0; i < savedRepods.length; i++) {
if(ids.includes(savedRepods[i]) ) {
console.log(savedRepods[i]);
}
}
}
I know the value is in the array but this won't show me the value console.log(savedRepods[i]);
Full code:
/** get saved values from the server */
var savedRepods = <?php echo json_encode($userPostsInternal); ?> ;
savedRepods = savedRepods.split(",");
/** create single arrays for the values */
var date = [],
coords = [],
ids = [],
metal = [],
plastic = [],
paper = [],
glass = [],
indirizzo = [];
/** convert to a variable ALL the other values form the server */
var array = <?php echo $contents; ?> ;
/** push single values into correspondent arrays */
array.map(function(item) {
coords.push(item.Lat + "," + item.Lng);
ids.push(item.ID);
date.push(item.Date);
plastic.push(item.Plastic);
paper.push(item.Paper);
glass.push(item.Glass);
metal.push(item.Metal);
});
/**
* Now process the response from locationData
*/
var locations = getPoints();
/**
* findLatLang
*/
function findLatLang(location, geocoder, value) {
/**
* Return new Promise what resolves when
* the geocoder is successfull
* and push in the array of promises
*/
return new Promise(function(resolve, reject) {
/** Do geocoder */
geocoder.geocode({
'location': location
}, function(results, status) {
/**
* If geocoder is Ok
*/
if (status === 'OK') {
/**
* When the geocoder is successfull located
* resolve the promise and send the response of formate address
*/
resolve([results[0].formatted_address, value]);
} else {
/**
* Reject the promise
*/
reject(new Error('Couldnt\'t find the location ' + location));
}
})
})
}
/**
* processData
* return an array of promises
*/
function getPoints(){
/**
* Declare a variable of promises that have a geocoder
*/
let locationData = [];
for (var i = 0; i < savedRepods.length; i++) {
if(ids.includes(savedRepods[i]) ) {
console.log(savedRepods[i]);
var geocoder = new google.maps.Geocoder;
var latlngStr = coords[a].split(',', 2);
var latlng = {
lat: parseFloat(latlngStr[0]),
lng: parseFloat(latlngStr[1])
};
/**
* Push geocoder in array of locationdata
* Send the geocoder object on function and send the map
*/
locationData.push(findLatLang(latlng, geocoder, a))
}
}
/** return array of promises */
return locationData;
}
Promise.all(locations)
.then(function(returnVals){
indirizzo = returnVals;
doAddress(indirizzo)
});
var usedId = [],
usedMetal = [],
usedGlass = [],
usedPaper = [],
usedLocation = [],
usedPlastic = [];
const data = [];
function doAddress(indirizzo) {
indirizzo.forEach(function(item){
var a = item[1];
var location = item[0];
let newObj = {};
newObj.idValue = ids[a];
newObj.addressValue = location;
newObj.metalValue = metal[a];
newObj.glassValue = glass[a];
newObj.plasticValue = plastic[a];
newObj.paperValue = paper[a];
data.push(newObj);
$("#eachValue ul").append("<li class='list-group-item'>repod id= " + ids[a] + "<br> Indirizzo = " + location + "<br> Metallo = " + metal[a] + ", <br> Plastica = " + plastic[a] + ", <br> Vetro = " + glass[a] + ", <br> Carta = " + paper[a] + "</li>");
})
const resultMetal = data.sort((a, b) => b.metalValue - a.metalValue)[0];
const resultGlass = data.sort((a, b) => b.glassValue - a.glassValue)[0];
const resultPaper = data.sort((a, b) => b.paperValue - a.paperValue)[0];
const resultPlastic = data.sort((a, b) => b.plasticValue - a.plasticValue)[0];
$("#metal p").html("Il repod con id "+resultMetal.idValue+"<br>situato in <br>" + resultMetal.addressValue + "<br> ha consumato più metallo con un valore di " + resultMetal.metalValue);
$("#vetro p").html("Il repod con id "+resultGlass.idValue+"<br>situato in <br>" + resultGlass.addressValue + "<br> ha consumato più vetro con un valore di " + resultGlass.glassValue);
$("#plastica p").html("Il repod con id "+resultPlastic.idValue+"<br>situato in <br>" + resultPlastic.addressValue + "<br> ha consumato più plastica con un valore di " + resultPlastic.plasticValue);
$("#carta p").html("Il repod con id "+resultPaper.idValue+"<br>situato in <br>" + resultPaper.addressValue + "<br> ha consumato più carta con un valore di " + resultPaper.paperValue);
}
Probably because of array entries are object types. Array.prototype.contains are not working for object types. Because in js:
var a = {
prop: 'value'
}
var b = {
prop: 'value'
}
if (a != b) {
console.log('a is not equal to b');
}
In javascript = (equals) operator checks for references are same or not for object types. Reference is address of the object in memory. In my first example a and b has its own different reference so for javascript a is not equals to b.
Instead of contains you can use some method which requires a callback to manually check matches. Here's an example using some method to find an element is exists or not.
var array = [
{ name: 'Anna', age: 19 },
{ name: 'Sara', age: 17 },
{ name: 'John', age: 21 },
{ name: 'Doe', age: 34 }
]
var john = { name: 'John', age: 21 };
if (array.some((other) => {
return other.name == john.name && other.age == john.age
})) {
console.log('John is exists in the array');
}
If you don't want to check each property for objects you may check for JSON.stringfy(other) == JSON.stringfy(john).

Value is not show when I create a gauge dynamically with justgage plugin

I'm trying to add gauges dynamically and actually it works but not with the expected behavior, the graphics are shown but the value is 0 even when the graph shows that is not 0, my gauges will be show in a onclick event the divs and the gauges are created in a ajax request.
function getLocationsGauge(row, countryId) {
var chartsDataTemp;
var requestData = {
countryId: $("#hCountryName" + countryId).val()
};
$("div").removeClass("blurELearning");
$("#gg" + countryId).addClass("blurELearning");
$.ajax({
type: 'GET',
dataType: 'json',
contentType: 'application/json',
url: '../XXX/GetLocations',
async: false,
data: requestData,
success: function (chartsdata) {
chartsDataTemp = chartsdata;
$(".location").remove();
$("#divLocations").remove();
var count = chartsdata.length / 6;
$('#countryGraphs section:eq(' + (row) + ')').after('<div id="divLocations" class="card card-info"><div class="card-header"><strong class="header-block">' + $("#hCountryName" + countryId).val() + '</strong></div></div>');
for (var i = 0; i <= count; i++) {
$('#divLocations').append('<section id="location' + i + '" class="section location"><div id="rowLocation' + i + '" class="row"></div></section>');
for (var j = i * 6; j < (i + 1) * 6; j++) {
$('#rowLocation' + i).append('<div class="col-md-2"><div id= "ggLocation' + (j + 1) + '" ></div ></div >');
}
}
for (var i = 0; i < chartsdata.length; i++) {
var limit = Number(chartsdata[i].total) * 0.8;
var total = Number(chartsdata[i].total);
var approved = Number(chartsdata[i].approved);
var name = chartsdata[i].location;
var percentage = approved * 100 / total;
percentage = parseFloat(Math.round(percentage * 100) / 100).toFixed(2)
var x = "ggLocation" + (i + 1);
objectsLocation[i] = new JustGage({
id: x,
value: approved,
min: 0,
max: total,
gaugeWidthScale: 1,
counter: true,
hideInnerShadow: true,
title: name + ' ' + percentage + '%',
label: "approved",
levelColors: ["#a9d70b", "#ffd6b6", "#fe9e50"],
levelColorsGradient: true,
pointer: true,
pointerOptions: {
toplength: 1,
bottomlength: -40,
bottomwidth: 6,
color: '#8e8e93'
}
});
}
},
complete: function () {
},
error: function () {
alert("Error loading data for location! Please try again.");
}
});}
After a lot of effort I decide to modify the html code directly with javascript.
After creating the object (JustGage) in the for I accessed the span object which contains the text and modified the value
var list = document.getElementById(x);
var list2 = list.childNodes[0];
list2.childNodes[6].childNodes[0].innerHTML = approved;

How to set the order of dropdown list items according to their ID numbers in GeoJSON properties

It is my fiddle: http://jsfiddle.net/anton9ov/d8yga33f/
I need to organize an order of items in my selector according to the ID numbers in the GeoJSON file. It is a part of my code where the items appear in the list:
map.on("layeradd", function(e) {
if(!e.layer.options) {
return;
}
if((e.layer.options.id != "markerLayer1") && (e.layer.options.id != "markerLayer2")) {
return;
}
var markers = e.layer.getLayers();
var mySelector = $("#mySelector");
for(var i = 0; i < markers.length; i++) {
mySelector.append("<option value='" + L.stamp(markers[i]) + "'>" + markers[i].feature.properties.name + "</option>");
}
});
Try using Array.prototype.sort():
map.on("layeradd", function(e) {
// ...
var markers = e.layer.getLayers();
// Get the dropdown
var mySelector = $("#mySelector");
markers.sort(function(a,b) {
// get the ids, and parse them as int
var aId = parseInt(a.feature.properties.id,10),
bId = parseInt(b.feature.properties.id,10);
return aId < bId ? -1 : aId > bId ? 1 : 0
}).forEach(function(marker) {
mySelector.append("<option value='"
+ L.stamp(marker) + "'>"
+ marker.feature.properties.id // I added the marker id
+ '. '
+ marker.feature.properties.name
+ "</option>");
})
});
See forked fiddle

Sorting different ajax calls before writing them on page

I'm looping through an array an show the data on my screen. This part is working perfectly.
Now I want to sorting the elements on 'Startdate'.
for (var i = 0; i < schedule_id.length; i++) {
//Ajax call maken
$.ajax({
url: "http://api.viewer.zmags.com/schedules/" + schedule_id[i] + "?key=" + api_key
})
//WdInit after 10 calls
.done(function(data){
//Check publicatieID is not null
if (undefined === data.scheduleEntries[default_pub]|| null === data.scheduleEntries[default_pub]) {
}
else
{
//loopen doorheen resultaat call
$.each(data.scheduleEntries, function(index, entry){
//Datums
var sdate = moment(entry.startDate).format('DD/MM');
var edate = moment(entry.endDate).format('DD/MM');
var sdatecheckformat = moment(entry.startDate).format('YYYY/MM/DD');
var edatecheckformat = moment(entry.endDate).format('YYYY/MM/DD');
var sdatecheck = new Date(sdatecheckformat);
var edatecheck = new Date(edatecheckformat);
var today = new Date();
var timeDiff = Math.abs(sdatecheck.getTime() - today.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
//Check geldig
if(today<=edatecheck && diffDays<=14){
// Decide list order, load the thumbnail for each publication.
var place = "first";
$('#archive').prepend('<div class="container" id="'+entry.publicationID+'"></div>');
$('.container:' + place).append('<div class="thumb"></div>');
$('.thumb:' + place).css("background-image", 'url(' + entry.thumbnailURL + ')');
$('.thumb:' + place).css("filter", 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + entry.thumbnailURL + ',sizingMethod="scale")');
$('.thumb:' + place).css("-ms-filter", 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=' + entry.thumbnailURL + ',sizingMethod="scale")');
// Load the publication title below each thumbnail.
$('.thumb:' + place).after('<div class="title"></div>');
$('.title:' + place).append(entry.publicationName);
// Load the publication startsdate & enddate.
$('.title:' + place).after('<div class="date"></div>');
$('.date:' + place).append(sdate + " tot " + edate);
// Set up publication links.
$('.container:' + place).click(function(){
loadPub(entry.publicationID, entry.publicationName);
setActive(entry.publicationID);
//Change css of current element
});
}
//Eerste element tonen
if(0===first_element){
first_element++;
loadPub(entry.publicationID, entry.publicationName);
initFirst(entry.publicationID);
}
});
}
});
//Einde loop
}
Within this loop it is not possible to sort because we are writing the element immediately. Can you please help me a way to sort the data. Maybe getting all data first and sorting them by creating an array with the same schedules ID's but in a correct sorted way.
My code so far:
//Sortering
var arr = [];
var arr1 = [];
//Loopen 10 keer
for (var i = 0; i < schedule_id.length; i++) {
arr1.push("test");
//Ajax call maken
$.ajax({
url: "http://api.viewer.zmags.com/schedules/" + schedule_id[i] + "?key=" + api_key,
success: function(data) {
arr.push(data);
}
})
}
//Know looping throught array or something and sorting
You can use $.when() to wait for multiple deferreds to resolve.
For example:
var arrayOfAjaxPromises = [$.ajax("/page1"), $.ajax("/page2"), $.ajax("/page3")];
$.when.apply($, arrayOfAjaxPromises).done(function() {
// this callback gets called when all the promises are resolved
// responses are passed in the array-like arguments object, so they can be read sequentially
// or you can sort or process the way you want
var i;
for (i = 0; i < arguments.length; i+= 1) {
alert(arguments[i]);
}
});

How to change google maps marker icon dynamically

I am using ajax and php and I grabbing all of the points out of my database and plotting them on the map. Which works fine. However I want to change the icon of the marker depending on if status in the database is 100 or 200 or 300 for each record. I can't seem to get anything to work. Here is my code:
if (localStorage.getItem('type2') !== null) {
$(function ()
{
var radius2 = localStorage.getItem("radius2");
var lat2 = localStorage.getItem("lat2");
var long2 = localStorage.getItem("long2");
var type2 = localStorage.getItem("type2");
var city2 = localStorage.getItem("city2");
var rep2 = localStorage.getItem("rep2");
var size2 = localStorage.getItem("size2");
var status2 = localStorage.getItem("status2");
$.ajax({
url: 'http://example.com/Test/www/22233333.php',
data: "city2=" + city2 + "&rep2=" + rep2 + "&status2=" + status2 + "&size2=" + size2 + "&type2=" + type2 + "&long2=" + long2 + "&lat2=" + lat2 + "&radius2=" + radius2,
type: 'post',
dataType: 'json',
success: function (data) {
$.each(data, function (key, val) {
var lng = val['lng'];
var lat = val['lat'];
var id = val['id'];
var name = val['name'];
var address = val['address'];
var category = val['category'];
var city = val['city'];
var state = val['state'];
var rep = val['rep'];
var status = val['status'];
var size = val['size'];
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': 'images/hospital.png'
}).click(function () {
$('div#google-map').gmap('openInfoWindow', {
'backgroundColor': "rgb(32,32,32)",
'content': "<table><tr><td>Name:</td><td>" + name + "</td></tr><tr><td>Address:</td><td>" + address + ", " + city + " " + state + "</td></tr><tr><td>Category:</td><td>" + category + "</td></tr><tr><td>Rep:</td><td>" + rep + "</td></tr><tr><td>Status:</td><td>" + status + "</td></tr><tr><td>Size:</td><td>" + size + "</td></tr></table>"
}, this);
});
})
}
});
})
}
Looks like you are using jquery-ui-map?
I haven't used this abstraction
You can call the setIcon function - on a marker you can set it's icon this way for the main API
https://developers.google.com/maps/documentation/javascript/reference#Marker
So your addMarker method will return a marker instance by the look of it so once you have that run setIcon
Do something like this in your success function with in $.each.
Status is the database field
var size = val['size'];
var status = val['status'];
var icon = '';
if (status == 100){
icon = 'images/icon1.png'; //your icon1
}else if (status == 100){
icon = 'images/icon1.png'; //your icon2
}
...
$('div#google-map').gmap('addMarker', {
'position': new google.maps.LatLng(lat, lng),
'bounds': true,
'icon': icon //your dynamic icon
})
Hope this helps

Categories

Resources