looped values are not printing in div via javascript - javascript

I am trying to print the address and details of my clinics in various locations. However, when i try to do that it is only printing the first element in my div.
Here is my code
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var id = markerNodes[i].getAttribute("id");
var locname = markerNodes[i].getAttribute("locationName");
var locaddress = markerNodes[i].getAttribute("locationAddress1");
var address = markerNodes[i].getAttribute("locationAddress1");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var servicename = markerNodes[i].getAttribute("serviceName");
var clinicfname= markerNodes[i].getAttribute("clinicFname");
var cliniclname= markerNodes[i].getAttribute("clinicLname");
var clinicname= clinicfname + ' ' + cliniclname ;
var clinicAddress= markerNodes[i].getAttribute("clinicAddress");
var clinicCity= markerNodes[i].getAttribute("clinicCity");
var clinicPhone= markerNodes[i].getAttribute("clinicPhone");
var cname= markerNodes[i].getAttribute("cname");
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("locationLat")),
parseFloat(markerNodes[i].getAttribute("locationLong")));
document.getElementById('details_name').innerHTML = clinicname;
//console.log (parseFloat(markerNodes[i].getAttribute("locationLong")));
createdetails(clinicname,clinicAddress)
bounds.extend(latlng);
}
In above code am calling a function name createdetails
function createdetails(clinicname,clinicAddress)
{
document.getElementById("details_name").innerHTML=clinicname;
document.getElementById("details_address").innerHTML=clinicAddress;
}
But this div is priniting only first name and first addrees.It have 9 diffrent values for name and address.When i consoled it,it prints.
What is the problem here?

When you are calling document.getElementById("details_name").innerHTML = ..., you are overwriting the current value. Maybe you should append the new name to the existing content with +=:
function createdetails(clinicname,clinicAddress)
{
document.getElementById("details_name").innerHTML+=clinicname;
document.getElementById("details_address").innerHTML+=clinicAddress;
}

Related

Dynamically creating google maps using javascript

I have a website that gets locations out of a MySQL database and passes it to a JavaScript function as a JSON object. The JavaScript function dynamically creates tables for each row returned from the database. Each location object returned includes a latitude and longitude and I want to create a Google map for each object. I can successfully create 1 map on the page using data returned from the database but when I add the map creation code to the loop that builds tables it begins throwing this error:
TypeError: Cannot read property 'offsetWidth' of null
I have gone through other questions that people have posted about this error. The two causes that it can have are either (1) the <div> I am trying to add the map to doesn't exist, or (2) I am trying to display the map before it is created. I know that the <div>s exist as they exist in the page when it is displayed. I am not sure how to check for or fix the other issue.
This is my JavaScript that retrieves data and builds the tables:
google.maps.event.addDomListener(window, "load");
//THIS FUNCTIONS BUILD THE MAPS
//PASS LAT, LONG, AND ID FOR DIV
function initializeMap(latitude,longitude, mapID)
{
var myCenter = new google.maps.LatLng(latitude, longitude);
var mapProp =
{
center:myCenter,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById(mapID), mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
}
function removeTable()
{
$("#tableID").remove();
}
/*
ajaxRequest variable receives and parses a JSON object into a 2 dimensional array
an example of what a single row returned will look like: [["2","Alexandra","33 GRANT STREET","ALEXANDRA","3714","57721040","-37.18859863281250000000","145.70799255371094000000","","security"]]
when trying to access elements in the array using a loop, columns are as follows:
ajaxRequest[i][0] = database id
ajaxRequest[i][1] = name
ajaxRequest[i][2] = address
ajaxRequest[i][3] = suburb
ajaxRequest[i][4] = postcode
ajaxRequest[i][5] = phone
ajaxRequest[i][6] = latitude
ajaxRequest[i][7] = longitude
ajaxRequest[i][8] = description
ajaxRequest[i][9] = service_type
*/
function search(option)
{
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
/*
1 = unsafe
2 = depressed
3 = sad
*/
if(option == 1)
{ajaxRequest.open("GET", "securitymodel.php", true);}
if(option == 2)
{ajaxRequest.open("GET", "depressedModel.php", true);}
if(option == 3)
{ajaxRequest.open("GET", "sadmodel.php", true);}
ajaxRequest.send(null);
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
var ajaxResult = 1;
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
var ajaxDisplay = document.getElementById('ajaxDiv');
//ajaxDisplay.innerHTML = ajaxRequest.responseText;
ajaxResult = JSON.parse(ajaxRequest.responseText);
if(ajaxResult.length > 0)
{
//IF SOMETHING IS RETURNED BEGIN BUILDING THE TABLE
var tableLocation = document.getElementById('suggestionTable');
var tableArea = document.createElement('table');
tableArea.id = 'tableID';
for(var i = 0; i < ajaxResult.length; i++)
{ //create inner row
var innerRow = document.createElement('tr');
var innerTD = document.createElement('td');
//WE MUST GO DEEPER!!!
var innerTable = document.createElement('table');
var superInnerTD = document.createElement('td');
var secondSuperInnerTD = document.createElement('td');
//row 1
var nameTR = document.createElement('tr');
var nameHead = document.createElement('td');
var name = document.createTextNode('Name:');
nameHead.appendChild(name);
nameTR.appendChild(nameHead);
var nameTD = document.createElement('td');
var nameText = document.createTextNode(ajaxResult[i][1]);
nameTD.appendChild(nameText);
nameTR.appendChild(nameTD);
superInnerTD.appendChild(nameTR);
//row 2
var descTR = document.createElement('tr');
var descHead = document.createElement('td');
var desc = document.createTextNode('Description:');
descHead.appendChild(desc);
descTR.appendChild(descHead);
var descTD = document.createElement('td');
var descText = document.createTextNode(ajaxResult[i][8]);
descTD.appendChild(descText);
descTR.appendChild(descTD);
superInnerTD.appendChild(descTR);
//row 3
var addTR = document.createElement('tr');
var addressHead = document.createElement('td');
var address = document.createTextNode('Address:');
addressHead.appendChild(address);
addTR.appendChild(addressHead);
var addTD = document.createElement('td');
var addressText = document.createTextNode(ajaxResult[i][2]);
addTD.appendChild(addressText);
addTR.appendChild(addTD);
superInnerTD.appendChild(addTR);
//row 4
var subTR = document.createElement('tr');
var suburbHead = document.createElement('td');
var suburb = document.createTextNode('Suburb:');
suburbHead.appendChild(suburb);
subTR.appendChild(suburbHead);
var subTD = document.createElement('td');
var subText = document.createTextNode(ajaxResult[i][3]);
subTD.appendChild(subText);
subTR.appendChild(subTD);
superInnerTD.appendChild(subTR);
//row 5
var postTR = document.createElement('tr');
var postcodeHead = document.createElement('td');
var postcode = document.createTextNode('Postcode:');
postcodeHead.appendChild(postcode);
postTR.appendChild(postcodeHead);
var postTD = document.createElement('td');
var postText = document.createTextNode(ajaxResult[i][4]);
postTD.appendChild(postText);
postTR.appendChild(postTD);
superInnerTD.appendChild(postTR);
//row 6
var phoneTR = document.createElement('tr');
var phoneHead = document.createElement('td');
var phone = document.createTextNode('Phone:');
phoneHead.appendChild(phone);
phoneTR.appendChild(phoneHead);
var phoneTD = document.createElement('td');
var phoneText = document.createTextNode(ajaxResult[i][5]);
phoneTD.appendChild(phoneText);
phoneTR.appendChild(phoneTD);
superInnerTD.appendChild(phoneTR);
//The divContainer requires an id
//ID IS AUTOMATICALLY GENERATED BY CONACTENATING THE NAME AND ADDRESS TOGETHER
var mapID = ajaxResult[i][1]+ajaxResult[i][2];
var divContainer = document.createElement("div");
divContainer.setAttribute("id", mapID);
secondSuperInnerTD.appendChild(divContainer);
initializeMap(ajaxResult[i][6],ajaxResult[i][7],mapID);
innerTable.appendChild(superInnerTD);
innerTable.appendChild(secondSuperInnerTD);
innerTD.appendChild(innerTable);
innerRow.appendChild(innerTD);
tableArea.appendChild(innerRow);
}
tableLocation.appendChild(tableArea);
}
}
}
}
An example of a completed table looks like:
We want to put the map in the <td> on the right.
To reiterate, the map generation works when we are trying to build 1 map in a <div> that is coded in html on the page. When we try to create several maps inside <div>s that are dynamically created it fails.
The call to initialize the map happens before the div is added to the DOM.
initializeMap(ajaxResult[i][6],ajaxResult[i][7],mapID);
The above line is called before the following line :
tableLocation.appendChild(tableArea);
The map divs that you create dynamically are added to the page when this line is executed. Due to this you are getting the error.
One workaround would be to use settimeout so that the initialize function is called after the map divs are added to the DOM.
setTimeout(function(){ initializeMap(ajaxResult[i][6],ajaxResult[i][7],mapID); }, 500);
Another option is to push the data into an array and iterate that array after the tableLocation.appendChild(tableArea); line and then call the intializeMap function using that data

How would I go about iterating over this JSON data

I'm pulling in the below json data from a database using ajax.
{"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]}
How would I got about iterating over it to get lat/long pairs to plot on a map?
Assign the JSON data to a variable, and loop through the route object like below:
var j = {"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]}
for(i=0; i<=j.route.length; i++){
var thisRoute = j.route[i];
}
Give it a try:
var j = {"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]};
for(var i= 0,len=j.route.length; i<len; i++){
var lat = j.route[i].latitude;
var long = j.route[i].longitude;
console.log(lat+' '+long);
}
var o = {"route":[{"latitude":-27.38851,"longitude":153.11606},{"latitude":-27.47577,"longitude":153.01693}]};
var i = 0;
var lat, long;
var len=o.route.length;
for(i,i<len; i++){
lat = o.route[i].latitude;
long = o.route[i].longitude;
console.log(lat+' '+long);
}
Here's a full implementation of what you're trying to achieve:
JSFIddle with a map
function createMarker(options) {
var marker = new google.maps.Marker(options);
return marker;
}
for (i = 0; i < data.route.length; i++) {
createMarker({
position: new google.maps.LatLng(data.route[i].latitude, data.route[i].longitude),
map: map
});

Adding destination lat and lon to destinations variable distancematricx API Success and Fail

I'm trying to get the lat and lon from a Json encoded file for use as destinations for the distance Matrix API rather than add var destinationA = new google.maps.LatLng(??.????, ???.?????); multiple times.
I thought I managed it, as both ways seem to produce the same variable destinations when viewed, yet method two produces an error Uncaught TypeError: a.lat is not a function
This is method one which gives var destination a length of 7:
var destinationA = new google.maps.LatLng(13.7373393, 100.5558883);
var destinationB = new google.maps.LatLng(13.735132, 100.55611199999998);
var destinationC = new google.maps.LatLng(13.736953, 100.55819300000007);
var destinationD = new google.maps.LatLng(13.736244, 100.55694100000005);
var destinationE = new google.maps.LatLng(13.736166, 100.557203);
var destinationF = new google.maps.LatLng(13.738747, 100.55587700000001);
var destinationG = new google.maps.LatLng(13.733558, 100.56020699999999);
var destinations = [destinationA,destinationB,destinationC,destinationD,destinationE,destinationF,destinationG];
works great, will return the distances for each from a given centre point on google map.
Method two:
This is method Two which gives var destination a length of 1, which I am stuck on finding out why its a single length and not 7 as above:
var location_lat_lon = <?php echo json_encode( $properties_data ); ?>;
var destinations = []
var first = true;
for (var i=0; i < location_lat_lon.length; i++) {
var sep = first ? '' : ',';
var lat = location_lat_lon[i].latitude;
var lon = location_lat_lon[i].longitude;
var destination1 = new google.maps.LatLng(lat, lon);
var destinations = [destinations+sep+destination1] ;
first = false;
}
which returns exactly the same result when viewing the variable destinations, yet this returns the error Uncaught TypeError: a.lat is not a function.
Any advice or guidance?
Is it not possible to pass destinations this way to the calculateDistances function?
Thanks in Advance :)
Try this:
var location_lat_lon = <?php echo json_encode( $properties_data ); ?>;
var destinations = []
for (var i=0; i < location_lat_lon.length; i++) {
var lat = location_lat_lon[i].latitude;
var lon = location_lat_lon[i].longitude;
var destination1 = new google.maps.LatLng(parseFloat(lat), parseFloat(lon));
destinations.push(destination1);
}

Populating 2D Array in JS

I am trying to popoulate a 2D array using Firebug API,
var sites = [];
var siteCounter = 0;
//Firebase API Calls
var messageListRef = new Firebase('https://my.firebaseio.com');
messageListRef.once('value', function(allMessagesSnapshot) {
allMessagesSnapshot.forEach(function(messageSnapshot) {
var latitude = messageSnapshot.child('latitude').val();
var longitude = messageSnapshot.child('longitude').val();
sites[siteCounter][0] = 'siteCounter';
sites[siteCounter][1] = latitude;
sites[siteCounter][2] = longitude;
sites[siteCounter][3] = siteCounter;
sites[siteCounter][4] = 'This is siteCounter.';
siteCounter++;
alert(sites[siteCounter][1] + " " + sites[siteCounter][2] );
});
});
But this breaks for sites[siteCounter][0] and says it is undefined. Any clue how to work with this ?
if you want 2D array, you must to initialize like this :
var tab = new Array();
after
tab[0] = new Array();
Try this code
sites[siteCounter] = new Array();
sites[siteCounter][0] = 'siteCounter';
sites[siteCounter][1] = latitude;
sites[siteCounter][2] = longitude;
sites[siteCounter][3] = siteCounter;
sites[siteCounter][4] = 'This is siteCounter.';
or directly
sites[siteCounter] = new Array("siteCounter", latitude, longitude, siteCounter, "This is siteCounter.");
Have you tried to do a
sites[siteCounter] = [];
before sites[siteCounter][0]?
I assume you have to declare it as an array to be able to put stuff in the array.

If data is null, dont show

This is my code. I get the data from xml. What I want is:
if a piece of data is null, don't show that row. How can I do it?
downloadUrl("xml/cat.xml", function(doc) {
var xml = xmlParse(doc);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var kWa = markers[i].getAttribute("kWa");
var html = 'rows here ';
Sorry for wrong question..
i want to hide here
var html = '
id='+id+', kwa='+kwa+' // if id is null how can hide item in here..?
';
You can do this with if checks like:
if(markers[i].getAttribute("lat") != NULL) // or "NULL" as a string if thats what is returned."
var lat = parseFloat(markers[i].getAttribute("lat));
Or you could put it in a try - catch statement:
for (//codes){
try{
//try parsing here
}catch(e){
if(e) // do something with the error
}
Which has the advantage of letting you do something for each error message. But the disadvantage of being slow. (though not as slow as it used to be in javascript)

Categories

Resources