I am needing to clear a DIV that is created from Google maps function.
There are two HTML DIVs. The DIV I am having trouble with is MarkerCount
<div id="sidebar"></div>
<div id="MarkerCount"></div>
function createMarkerCount(count) {
var div = document.createElement('div');
var html = "Results: " + count + " Facilities";
div.innerHTML = html;
div.style.marginBottom = '5px';
return div;
}
This is created when markers are returned to the Google Map. This is basically performing a count on the amount of records currently displayed on the map. This function works fine.
Here is my function to reset the map and clear the markers and another innerhtml DIV called sidebar:
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
sidebar.innerHTML = "";
map.setCenter(new google.maps.LatLng(36.1611, -116.4775), 6);
}
This function works just fine. Now when I want to clear the MarkerCount,
I tried to add the following line to the function clearLocations()
MarkerCount.innerHTML = "";
However when the page first loads, and you perform a search, the clearLocations() function is called before the search is started, because there is not currently an innerhtml created for the CreateMarker function. this throws back an error which states that CreateMarker is NULL as there is nothing there.
So the skinny is, sidebar.innerhtml gets cleared just fine, but when I add the line of code to clear the CreateMarker.innerhtml DIV, I receive an error. Not sure why this might be happening....
EDIT -- Function To Show How CountMarker Gets Count
var markercountEntry = createMarkerCount(markerNodes.length);
MarkerCount.appendChild(markercountEntry);
It sounds like you are having problems with setting an innerHTML on an element that is not defined yet, in your clearLocations() function. I suggest you just handle the case where CreateMarker or MarkerCount is not defined yet.
Something like:
function clearLocations() {
if(CreateMarker && CreateMarker.innerHTML)
CreateMarker.innerHTML = "";
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
sidebar.innerHTML = "";
map.setCenter(new google.maps.LatLng(36.1611, -116.4775), 6);
}
Related
I am using the below code in the google tag manager custom JavaScript variable, but it returns same index value for every line item, what can be the issue?
Web page link: https://www.amity.edu/programe-list.aspx?fd=all
function() {
var elements = document.querySelectorAll('.staff-container');
for (var i = 0; i < elements.length; i++){
(function(index){
elements[i].children[0].children[0].addEventListener("click", myScript);
function myScript(){
return("Clicked : ",index);
}
})(i);
}
}
There is an error in the 5th line.
It should be elements[index].children... in that case.
The updated code:
function() {
var elements = document.querySelectorAll('.staff-container');
for (var i = 0; i < elements.length; i++){
(function(index){
elements[index].children[0].children[0].addEventListener("click", myScript);
function myScript(){
return("Clicked : ",index);
}
})(i);
}
}
Here is an alternative way from Simo's blog
Blog link
Although the post is say about visibility element. I test it with click on my website.
This might work
function() {
var list = document.querySelectorAll('.staff-container a'),
el = {{Click Element}};
return [].indexOf.call(list, el) + 1;
}
If it is not working, you might need to provide the screenshot about the click element from your GTM preview.
I'm trying to create a chrome extension. I had a problem with the affectation of event for the new element that i append to the dom of site with content. Js
If I add an event to an element' 'for example class' exist already in the page, it works correctly. Just for my new appended element((in the code iadded a button ,the event is just an alert to test))
function tst() {
myclass = $("._3hg-._42ft");
myclass = myclass.not(".supp");
myclass.addClass("supp");
var patt = /https:\/\/(.)*\.facebook\.com\/(.)*\/(posts|photos|videos)\/(\w|\.|\d)*/g;
for (i = 0; i < myclass.length; i++) {
result = patt.exec(myclass[i]);
myclass.append('<button class="fact" id=' + result[0] + ' style="position: absolute;">fact</button>');
};
/* this is a simple event*/
/***********************/
$(".fact").on('click', function() {
alert("no event work ");
});
Making somewhat broad assumption here in my answer that it is JavaScript/jQuery related and is NOT an extension...or is so still in that context.
You need to attach the event to the container here perhaps for the dynamically created elements. Lots of global stuff, suggested to not do that, updated there.
Appends a lot of buttons perhaps? might need to only hit DOM once but left as-is in this isolated function.
function tst() {
let myclass = $("._3hg-._42ft")
.not(".supp");
myclass.addClass("supp");
//let result = {};
var patt = /https:\/\/(.)*\.facebook\.com\/(.)*\/(posts|photos|videos)\/(\w|\.|\d)*/g;
var i = 0; //avoid global
for (i; i < myclass.length; i++) {
// broad assumption of the returned value from patt.exec() here
// not even sure why it needs an id, have a class, use for css
let result = patt.exec(myclass[i]);
myclass.append('<button class="fact" id="' + result[0] + '">fact</button>');
}
/* attache event to pre-existing element */
/***********************/
myclass.on('click', ".fact", function() {
alert("event works");
});
}
button.fact {
position: absolute;
}
I am loading markers from a database to display on a google map by this below. This is working fine however, I would like to implement the option of pressing a particular button somewhere else on the page, and then map would dynamically change to only show markers pertaining to what was clicked.
Basically, I would like to filter by the 'type' column in my database but still keep all types loaing by default. eg. Page loads, Map loads and displays all types, User clicks on a button which causes the map to only show markers that have type1 as the value in the db. Kind of like a toggle with a check box.
Any ideas of how to go ahead with this, I don't think reloading markers from the db is the most efficient way, can I simply just hide markers which have this property?
map = new google.maps.Map(document.getElementById("google_map"), googleMapOptions);
//Load Markers from the XML File, Check (map_process.php)
$.get("map_process.php", function (data) {
$(data).find("marker").each(function () {
var name = $(this).attr('name');
var address = '<p>'+ $(this).attr('address') +'</p>';
var type = $(this).attr('type');
var description ='<p>'+ $(this).attr('description') +'</p>';
var point = new google.maps.LatLng(parseFloat($(this).attr('lat')),parseFloat($(this).attr('lng')));
var icon1 = customIcons[type] || {};
create_marker(point, name, address, false, false, false, icon1.icon);//"http://sanwebe.com/assets/google-map-save-markers-db/icons/pin_blue.png");
});
});
You can't just hide some specific markers according to their tag or type, you have to hide/remove them all first and then add those that you need on your map
Here are the functions that you need:
var all_markers = [];
var show_markers = [];
function setMarkers(map) {
for (var i = 0; i < show_markers.length; i++) {
show_markers[i].setMap(map);
}
}
function showMarkers(type) {
setMarkers(null);
show_markers = []
for (var i = 0; i < all_markers.length; i++) {
if (all_markers[i].type == type){
show_markers.push(all_markers[i])
}
}
setMarkers(map);
}
Here is the idea: Load all your markers into the all_markers, on your first loading the markers show_markers must be equal to all_markers. Hitting the button for showing specific markers must trigger function showMarkers which will clear your map and reload just specific ones.
I am pretty sure that I know what the problem is with my code, but I am unsure how to fix it.
I have a google fusion table that i am querying to generate a menu that has radio buttons in it. A map that is a google fusion table visualized like a google map is also on the page.
When i hard code a couple radio buttons and click them it makes the items light up on the map based on the ID of the element. I using google.maps.event.addDomListener to make this magic work. So that works great.
Now i want to take it one step further and actually pull the data from a google fusion table so it shows the most up to date list of items i have in my table. So, I'm using jQuery and a $.get command to get the feed in jsonp. I'm outputting 2 columns of data and dynamically building radio buttons by attaching them with a innerHTML line -- attaching it to a div.
So, I'm thinking the problem has to do with the DOM, but i am not sure how to get the radio buttons to load in first and then load in the map so all is available to the maps events so clikcing the radio actually does something.
The question is what modifications do i need to make so my dynamic generated radio buttons will work with my google fusion map?
Here is my javascript code:
function initialize() {
var table = ########;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(30.6, -108.1),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var layer = new google.maps.FusionTablesLayer();
filterMap(layer, table, map);
getData(table);
google.maps.event.addDomListener(document.getElementById('num1'),
'click', function() {
filterMap(layer, table, map);
});
google.maps.event.addDomListener(document.getElementById('num2'),
'click', function() {
filterMap(layer, table, map);
});
}
// Filter the map based on checkbox selection.
function filterMap(layer, table, map) {
var where = generateWhere();
if (where) {
if (!layer.getMap()) {
layer.setMap(map);
}
layer.setOptions({
query: {
select: "State",
from: table,
where: where
}
});
} else {
layer.setMap(null);
}
}
// Generate a where clause from the checkboxes. If no boxes
// are checked, return an empty string.
function generateWhere() {
var filter = [];
var bugs = document.getElementsByName('bug');
for (var i = 0, bug; bug = bugs[i]; i++) {
if (bug.checked) {
var BugName = bug.value.replace(/'/g, '\\\'');
filter.push("'" + BugName + "'");
}
}
var where = '';
if (filter.length) {
where = "'BugName' IN (" + filter.join(',') + ')';
}
return where;
}
// build the menu
function getData(table) {
var queryUrlHead = 'http://www.google.com/fusiontables/api/query?sql=';
var queryUrlTail = '&jsonCallback=?'; // ? could be a function name
// write your SQL as normal, then encode it
var query = "SELECT BugName, bugAbbr FROM " + table + " LIMIT 1";
var queryurl = encodeURI(queryUrlHead + query + queryUrlTail);
var jqxhr = $.get(queryurl, dataHandler, "jsonp");
}
function dataHandler(d) {
// get the actual data out of the JSON object
var data = d.table.rows;
var ftdata = ['<div>'];
for (var i = 0; i < data.length; i++) {
ftdata.push('<input type="radio" id="'+data[i][1]+'" value="'+data[i][0]+'" name="bug">'+data[i][0]+'');
}
ftdata.push('</div>');
document.getElementById('ft-data').innerHTML = ftdata.join('');
}
google.maps.event.addDomListener(window, 'load', getData);
google.maps.event.addDomListener(window, 'load', initialize);
This site had a bunch of example code.
http://csessig.wordpress.com/category/fusion-tables/
I am working on a Phonegap app, in which I access device's contacts. I then store upto 10 contacts in window.localStorage. To do so, when the user select a button, I create a div which has three elements.
An image (contact icon that represents male/female contact)
The name of the contact
Another image (represents 'add' sign to add it to window.localStorage)
I then associate an event handler, which will first check if the contact already exists in the localStorage and then proceed to add the contact. Here is the code
function checkDuplicate(somevalue)
{
for(var i=0;i<10;i++) {
if(window.localStorage.getItem(i)!=null) {
if(window.localStorage.getItem(i)==somevalue) {
navigator.notification.alert('Entry exists at Button:'+i);
return false;
}
}
}
//chosenButton is a global variable
window.localStorage.setItem(chosenButton,somevalue);
document.getElementById('contactNumberField').textContent=somevalue;
}
//Problem is with the event listener attached to span2. Please read below
function addContact(item)
{
var parentDiv = document.getElementById('thelist');
var childDiv = document.createElement('li');
var span1 = document.createElement('span');
span1.style.float='left';
span1.innerHTML = "<img src='keypad-contact.png'/>";
var span2 = document.createElement('span');
span2.style.float='right';
span2.innerHTML="<img src='keypad-addcontact.png'/>";
span2.addEventListener('click',function({checkDuplicate(item.number);},false);
childDiv.textContent=item.name;
childDiv.style.color='white';
childDiv.appendChild(span1);
childDiv.appendChild(span2);
parentDiv.appendChild(childDiv);
}
function onSuccess(contacts)
{
var objArray = new Array();
for(var i=0; i<contacts.length;i++) {
var tempObj = new Object();
tempObj['name']=contacts[i].displayName;
tempObj['number']=contacts[i].phoneNumbers[0].value;
objArray.push(tempObj);
}
objArray.sort(
function(a,b){
var nameA = a.name.toLowerCase(),nameB=b.name.toLowerCase();
if(nameA < nameB) return -1;
else if(nameA > nameB) return 1;
return 0;
});
for(var i=0; i<objArray.length;i++) addContact(objArray[i]);
}
function onDeviceReady()
{
var options = new ContactFindOptions();
options.multiple=true;
var field = ["displayName","phoneNumbers"];
navigator.contacts.find(field, onSuccess, function(){alert('NA');}, options);
}
Problem
When I try to add a contact which is already present in window.localStorage, for my first touch on span2, I get one alert. If I try to add again by touching it for the second time, I get two alerts.. and this goes on. The trouble is with the event handler associated with span2. However, I don't know how to over come this situation. How can I ensure that irrespective of how many times I press span2, I get alert only once. How to remove the event handler as soon as it is fired?
Please help.
Fixed:
The issue was not with adding event handlers dynamically. I happen to use iScroll (cubiq) for my project and that caused the trouble. Now I am not receiving multiple alerts. The trick is to declare the globlal scroller variable only once.
var scroller = null;
and then in the function
if(!scroller) scroller = new iScroll('scrollableDiv');
I hope this could be a useful tip for people who are using iScroll and struggling with multiple alerts like me.