I am using google earth api and I want to draw multiple placemark (points and polygons) on the map at once. The actual scenario is that the user have a list of its and he can click them to draw them 1 by 1 or click the draw all button which will then start drawing about 3000 placemarks. The problem is after a few second the browser/plugin crashes or prompts the user to stop the plugin from executing.
This is an example code I made :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<head>
<title>Many Points Test!</title>
<script src="http://www.google.com/jsapi?key=ABQIAAAAwbkbZLyhsmTCWXbTcjbgbRSzHs7K5SvaUdm8ua-Xxy_-2dYwMxQMhnagaawTo7L1FE1-amhuQxIlXw"></script>
<script>
google.load("earth", "1");
var ge = null;
function init() {
google.earth.createInstance("map3d", initCallback, failureCallback);
}
function initCallback(object) {
ge = object;
ge.getWindow().setVisibility(true);
// Get the current view.
var lookAt = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
// Set new latitude and longitude values.
lookAt.setLatitude(37.802);
lookAt.setLongitude(-122.448425);
lookAt.setRange(1000);
// Update the view in Google Earth.
ge.getView().setAbstractView(lookAt);
addPoints(1);
}
function failureCallback(object) {
}
function addPoints(num) {
for(var i = 0; i < num; i++)
{
var x = "37.802" + i.toString();
var kmlString = ''
+ '<?xml version="1.0" encoding="UTF-8"?>'
+ '<kml xmlns="http://www.opengis.net/kml/2.2">'
+ '<Document>'
+ ' <Placemark>'
+ ' <name>Placemark from KML string</name>'
+ ' <Point>'
+ ' <coordinates>-122.448425,'+x+',0</coordinates>'
+ ' </Point>'
+ ' </Placemark>'
+ '</Document>'
+ '</kml>';
var kmlObject = ge.parseKml(kmlString);
ge.getFeatures().appendChild(kmlObject);
}
}
</script>
</head>
<body onload='init()' id='body'>
<center>
<div id='map3d' style='border: 1px solid silver; height: 600px; width: 800px;'></div>
<input onclick="addPoints(10000)" value="Add Many Points" type="button" />
</center>
</body>
</html>
Anyone know How I can keep the browser responsive or even load the placemarks in an asynchronous way?
What seemed to solve it was pausing between every placemark I drew using setTimeout :
function addPoints(arr, index) {
var end = Math.min(arr.length, index + 1);
for (var i = index; i < end; i++) {
var kmlObject = ge.parseKml(arr[i]);
ge.getFeatures().appendChild(kmlObject);
document.getElementById('done').innerHTML = i;
}
if (end != arr.length) {
setTimeout(function () {
addPoints(arr, end);
}, 1);
} else {
alert('done');
}
}
addPoints(arr, 0); /* Function Call */
Related
I cannot figure out how to edit this to make it so the map does not refresh but it continues to refresh the marker to get the updated positions.
the positions are coming from
this line
<?php
$json_pos = file_get_contents("C:\Users\KLAUS\Desktop\New\This SAMP\scriptfiles\positions.json");
?>
right there
<?php
$json_pos = file_get_contents("C:\Users\KLAUS\Desktop\New\This SAMP\scriptfiles\positions.json");
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="refresh" content="1" />
<title>SA:MP live map</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<style type="text/css">
#map-canvas { display: inline-block; height: 800px; width: 800px; }
#map-legend { padding: 10px; background-color: rgba(141, 142, 127, 0.46);}
</style>
</head>
<body>
<div id="map-canvas"></div>
<script src="js/SanMap.min.js"></script>
<script type="text/javascript">
var p_pos = <?php echo (empty($json_pos)) ? "" : $json_pos ?>;
var mapType = new SanMapType(0, 1, function (zoom, x, y) {
return x == -1 && y == -1
? "images/tiles/map.outer.png"
: "images/tiles/map." + zoom + "." + x + "." + y + ".png";//Where the tiles are located
});
var satType = new SanMapType(0, 3, function (zoom, x, y) {
return x == -1 && y == -1
? null
: "images/tiles/sat." + zoom + "." + x + "." + y + ".png";//Where the tiles are located
});
var map = SanMap.createMap(document.getElementById('map-canvas'),
{'Map': mapType, 'Satellite': satType}, 2, SanMap.getLatLngFromPos(0,0), false, 'Satellite');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(document.getElementById('map-legend'));
if(p_pos !== "")
{
for (var i = 0; i < Object.keys(p_pos).length; i++)
{
if(p_pos[i].online == 1) createMarker(i);
}
}
google.maps.event.addListener(map, 'click', function(event) {
var pos = SanMap.getPosFromLatLng(event.latLng);
console.log(pos.x + "," + pos.y);
});
function createMarker(id)
{
var p_windows = new google.maps.InfoWindow({
content: "<p>"+p_pos[id].name+" <b>(ID: "+id+")</b><br>Ping: "+p_pos[id].ping+"</p>"
});
var p_marker = new google.maps.Marker({
position: SanMap.getLatLngFromPos(p_pos[id].x, p_pos[id].y),
map: map,
icon: "images/marker.png"
});
google.maps.event.addListener(p_marker, 'click', function() {
p_windows.open(map,p_marker);
});
}
</script>
</body>
Remove the top header line: <meta http-equiv="refresh" content="1" /> to disable refresh the page. And then add a setInterval function to get the new data from your php service, in the call back --
first use marker.setMap(null) to clear the previous marker and then call your CreateMarker(id).
Or
you can write an updateMarker(id) function, and use marker.setPosition() to update the location.
These are generally idea for you to implement your own code.
This is kind of an update to a question I asked earlier but never got an answer here previous question. I've got a google map that creates and loads different categories of markers from an xml file when the corresponding checkbox is clicked and then updates the list on a sidebar. I'd like to load each category into its own separate sidebar so I can split them up or stack them side-by-side, etc. When I click the check-boxes the first list (the list of huts) gets loaded into both sidebars but the second list (list of yurts) gets loaded correctly into its corresponding sidebar. I don't understand why one list gets loaded into both sidebars but the other list gets loaded correctly into just one. Thanks in advance for any help. The code is all below:
Javascript
var side_bar_html = "";
//var for kml route layers
var routes = {
y: {
name: "Winter Routes",
url: "http://www.huts.org/Tests/Maps/GPSTracks/Margys_MacV2.kml"
},
z: {
name: "Summer Routes",
url: "http://www.huts.org/Tests/Maps/GPSTracks/Telluride_to_Last_Dollar.kml"
},
};
var gmarkers = [];
var gicons = [];
var map = null;
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(100,150)
});
gicons["ltblue"] = new google.maps.MarkerImage("images/marker2_ltblue.png");
var iconImage = new google.maps.MarkerImage('images/marker2_ltblue.png');
function getMarkerImage(iconColor) {
if ((typeof(iconColor)=="undefined") || (iconColor==null)) {
iconColor = "ltblue";
}
if (!gicons[iconColor]) {
gicons[iconColor] = new google.maps.MarkerImage("images/marker2_"+ iconColor +".png");
}
return gicons[iconColor];
}
function category2color(category) {
var color = "ltblue";
switch(category) {
case "huts": color = "ltblue";
break;
case "yurts": color = "orange";
break;
case "demohuts": color = "red";
break;
default: color = "ltblue";
break;
}
return color;
}
gicons["huts"] = getMarkerImage(category2color("huts"));
gicons["yurts"] = getMarkerImage(category2color("yurts"));
gicons["demohuts"] = getMarkerImage(category2color("demohuts"));
// A function to create the marker and set up the event window
function createMarker(latlng,name,html,category) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
icon: gicons[category],
map: map,
title: name,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
// === Store the category and name info as a marker properties ===
marker.mycategory = category;
marker.myname = name;
gmarkers.push(marker);
//google.maps.event.addListener(marker, 'click', function() {
// infowindow.setContent(contentString);
// infowindow.open(map,marker);
// });
google.maps.event.addListener(marker, 'click', function() {
var testimonial = document.getElementById('hutMapinfo');
testimonial.innerHTML = contentString;
});
}
// == shows all markers of a particular category, and ensures the checkbox is checked ==
function show(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(true);
}
}
// == check the checkbox ==
document.getElementById(category+"box").checked = true;
}
// == hides all markers of a particular category, and ensures the checkbox is cleared ==
function hide(category) {
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].mycategory == category) {
gmarkers[i].setVisible(false);
}
}
// == clear the checkbox ==
document.getElementById(category+"box").checked = false;
// == close the info window, in case its open on a marker that we just hid
infowindow.close();
}
// == a checkbox has been clicked ==
function boxclick(box,category) {
if (box.checked) {
show(category);
} else {
hide(category);
}
// == rebuild the side bar
makeSidebar();
}
function myclick(i) {
google.maps.event.trigger(gmarkers[i],"click");
}
// == rebuilds the sidebar to match the markers currently displayed ==
function makeSidebar() {
var html = "";
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
html += '<a href="javascript:myclick(' + i + ')" onmouseover="gmarkers['+ i +'].setAnimation(google.maps.Animation.BOUNCE)" onmouseout="gmarkers['+ i +'].setAnimation(null)">' + gmarkers[i].myname + '<\/a><br>';
}
document.getElementById(gmarkers[i].mycategory+"side_bar").innerHTML = html;
}
}
function initialize() {
var myOptions = {
zoom: 7,
center: new google.maps.LatLng(39.192948, -105.089823),
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//google.maps.event.addListener(map, 'click', function() {
// infowindow.close();
// });
// Read the data
downloadUrl("coloradoYurtsToggleTest.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 name = markers[i].getAttribute("label");
var html = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
var category = markers[i].getAttribute("category");
var season = markers[i].getAttribute("season");
// create the marker
var marker = createMarker(point,name,html,category);
}
// == show or hide the categories initially ==
show("huts");
hide("yurts");
// == create the initial sidebar ==
makeSidebar();
});
createRouteTogglers();
}
// the important function... routes[id].xxxxx refers back to the top
function toggleRoute(checked, id) {
if (checked) {
var layer = new google.maps.KmlLayer(routes[id].url, {
preserveViewport: true,
suppressInfoWindows: false
});
// store kml as obj
routes[id].obj = layer;
routes[id].obj.setMap(map);
}
else {
routes[id].obj.setMap(null);
delete routes[id].obj;
}
};
// create the Routes controls
function createRouteTogglers() {
var html = "<form><ul>";
for (var prop in routes) {
html += "<li id=\"selector-" + prop + "\"><input type='checkbox' id='" + prop + "'" +
" onclick='highlight(this,\"selector-" + prop + "\"); toggleRoute(this.checked, this.id)' \/>" +
routes[prop].name + "<\/li>";
}
html += "<\/ul><\/form>";
document.getElementById("routeLayers").innerHTML = html;
};
// Append Class on Select
function highlight(box, listitem) {
var selected = 'selected';
var normal = 'normal';
document.getElementById(listitem).className = (box.checked ? selected: normal);
};
html
<!DOCTYPE html>
<html>
<head>
<title>10th Mountain Division Hut Association</title>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>Google Maps Javascript API v3 Example: Marker Categories</title>
<link rel="stylesheet" href="css/foundation.css" />
<link rel="stylesheet" href="css/10thMtn2.css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="GXml.js"></script>
<script type="text/javascript" src="downloadxml.js"></script>
<script type="text/javascript" src="xmlToggle2.js"></script>
<title>Google Maps</title>
</head>
<body onload="initialize()">
<?php include('includes/header3.php'); ?>
<div id="map_canvas" style="width:65%; height:625px;"></div>
<div id="toggle_box">
<div id="routeLayers"></div>
<form action="#">
<img src="images/marker2_ltblue.png"> Huts: <input type="checkbox" id="hutsbox" onclick="boxclick(this,'huts')" />
<img src="images/marker2_orange.png"> Yurts: <input type="checkbox" id="yurtsbox" onclick="boxclick(this,'yurts')" />
</form>
<div id="hutsside_bar">
</div>
<div id="yurtsside_bar">
</div>
</div>
<div id="hutMapinfo"></div>
<?php include('includes/footer.php'); ?>
<noscript><b>JavaScript must be enabled in order for you to use Google Maps.</b>
However, it seems JavaScript is either disabled or not supported by your browser.
To view Google Maps, enable JavaScript by changing your browser options, and then
try again.
</noscript>
</body>
</html>
xml snippet
<?xml version="1.0" encoding="UTF-8"?>
<markers>
<marker lat="39.369804" lng="-106.388725" label="10th Mountain Division Hut" category="huts" season="winter">
<infowindow>
<![CDATA[
<div class="info">
<button class="tiny radius" id="closer">X</button>
<h5>10th Mountain Division Hut</h5>
<div class="hutMapTitle">
<img src="http://www.huts.org/images/10thMtn/10thMountainsmall.jpg"/>
<h6>10th Mountain Hut System</h6>
<h6>(970)925-5775</h6>
</div>
<div class="hutMapList">
<ul>
<li>10th Mtn Division Huts Website</li>
<li>Book This Hut</li>
<li><span class="subheading">Seasons:</span> Winter & Summer</li>
<li><span class="subheading">Price:</span> $33 per person</li>
<li><span class="subheading">Capacity:</span> 16 people</li>
<li><span class="subheading">Distance:</span> 4.4 miles</li>
<li><span class="subheading">Elevation Gain:</span> 1200ft
</ul>
</div>
<p>Nestled at timberline below the majestic peaks of the Colorado Continental Divide, 10th Mountain Division Hut forms a perfect destination for a single hut trip or ski-through using other nearby huts. In summer, dozens of hiking and cycling routes start or end just outside the door.</p></div>]]></infowindow>
</marker>
<marker lat="37.059971" lng="-106.480865" label="Trujillo Meadows Yurt" category="yurts">
<infowindow>
<![CDATA[
<div class="info">
<button class="tiny radius" id="closer">X</button>
<h5>Trujillo Meadows Yurt</h5>
<div class="hutMapTitle">
<img src="http://www.huts.org/images/GMaps/trujilloMeadowsYurt.jpg"/>
<h6>Southwest Nordic Center</h6>
<h6>(575)758-4761</h6>
</div>
<div class="hutMapList">
<ul>
<li>Southwest Nordic Website</li>
<li>Book This Hut</li>
<li><span class="subheading">Seasons:</span> Winter & Summer</li>
<li><span class="subheading">Price:</span> $125 per night</li>
<li><span class="subheading">Capacity:</span> 10 people</li>
<li><span class="subheading">Distance:</span> 4.1 miles</li>
<li><span class="subheading">Elevation Gain:</span> 380ft</li>
</ul>
</div>
<p>Located north Cumbres Pass in south central Colorado, the Trujillo Meadows Yurt is gentle open slopes out the front door of the yurt perfect for beginning and intermediate telemarkers. Advanced skiers will have fun looking for shots on the extensive north facing tree slopes. A full day loop is possible up to the Flat Mtn. ridge and back via the Los Pinos Creek.</p></div>]]></infowindow>
</marker>
</markers>
Your makeSidebar function has an issue (it is doing what you coded it to do, which is the behavior you are seeing):
function makeSidebar() {
var html = "";
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
html += '<a href="javascript:myclick(' + i + ')" onmouseover="gmarkers['+ i +'].setAnimation(google.maps.Animation.BOUNCE)" onmouseout="gmarkers['+ i +'].setAnimation(null)">' + gmarkers[i].myname + '<\/a><br>';
}
document.getElementById(gmarkers[i].mycategory+"side_bar").innerHTML = html;
}
}
If you want unique text for each "sidebar", you should make a unique version of "html" for each sidebar. Something like this:
var html = null;
function makeSidebar() {
// empty any pre-existing sidebar entries
for (i in html) {
document.getElementById(i+"side_bar").innerHTML = "";
}
html = []; // make html an array
for (var i=0; i<gmarkers.length; i++) {
if (gmarkers[i].getVisible()) {
// make entry for category if it doesn't already exist
if (!html[gmarkers[i].mycategory])
html[gmarkers[i].mycategory] = "";
// add the entry to the sidebar specific to the category
html[gmarkers[i].mycategory] += '<a href="javascript:myclick(' + i + ')" onmouseover="gmarkers['+ i +'].setAnimation(google.maps.Animation.BOUNCE)" onmouseout="gmarkers['+ i +'].setAnimation(null)">' + gmarkers[i].myname + '<\/a><br>';
}
}
for (i in html) {
document.getElementById(i+"side_bar").innerHTML = html[i];
}
}
working fiddle
Im currently making a simple color picker for school. Well it should be simple, however my programming in Javascript is really bad. It contains an array with the names, and a array with the codes. The codes will only contain 00, 33, 66, 99, ff, cc and the code is only 6 chars long as some of you know. With a loop i manage to print everything on screen, but now i want to make the background color the same color as the one im clicking. And i want the code of the one that im clicking in a textbox.
So heres my code:
DHTML with jQuery: Opdracht 4
<script type="text/javascript">
function showPicker(source) {
var hex = new Array('00', '33', '66','99','CC','FF');
var colorNames = new Array(
"black", // #000000
"weak blue", // #000033
"obsure dull blue", // #000066
"dark faded blue", // #000099
);
var count = 0;
document.writeln('<table width="1200" height="600">');
for(var x in hex) {
document.writeln('<tr>');
for(var y in hex) {
for(var z in hex) {
var color = hex[x] + "" + hex[y] + "" + hex[z];
document.writeln('<td bgcolor="#'+color+'" title="#'+color + ' ' + colorNames[count] + '" onclick="'+source+' (\''+color+'\',\''+colorNames[count]+'\')"></td>');
count++;
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
}
showPicker('showFontColor');
</script>
</head>
<body>
<input type="text" id="color"/>
</body>
</html>
I tried a line in the onclick button, but i realised that wont work. Do you guys have any suggestions? And sorry if it looks a little messy, as I said I am a real nub in javascript.
EDIT:
Working code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>DHTML with jQuery: Opdracht 4</title>
<link href="style.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
function changeBg(color){
var currentColor = $('#printColor').val();
$('#input').css('background', currentColor);
}
function printColor(color) {
$('#printColor').val(color);
$("#input").on("click", function() {
$(this).css("background", "printColor");
});
}
function changeFG() {
var currentColor = $('#printColor').val();
$('#input').css('color', currentColor);
}
function showPicker(source) {
var hex = new Array('00', '33', '66','99','CC','FF');
var colorNames = new Array(
"black", // #000000
"weak blue", // #000033
"obsure dull blue", // #000066
);
var count = 0;
document.writeln('<table width="800" height="300">');
for(var x in hex) {
document.writeln('<tr>');
for(var y in hex) {
for(var z in hex) {
var color = hex[x] + "" + hex[y] + "" + hex[z];
document.writeln('<td bgcolor="#' + color + '" title="#' + color + ' ' + colorNames[count] + '" onclick="javascript:printColor(\'#'+color+'\')" ' + source + '(\'' + color + '\',\'' + colorNames[count] + '\')"></td>');
count++;
var source = function(color){
document.body.style.background = "#" + color;
}
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
}
showPicker('showFontColor');
</script>
</head>
<body>
<div id="input">
<input type="text" id="printColor" name="printColor" />
Change Background / Foreground color!
<p> Lorem ipsum blablabla</p>
</div>
</body>
</html>
Without making too much changes to your code I think this is what you want.
I just changed your array into an object so that you can map the hex code of the color to the name and declared the changeBg function. Just fill in the rest of the colors.
<body>
<script type="text/javascript">
(function(){
var colorNames = {
"000000": "black",
"000033": "weak blue",
"000066": "obsure dull blue",
"000099": "dark faded blue"
//...rest of colors
};
window.changeBg = function(color){
document.body.style.background = "#" + color;
document.getElementById("color").value = colorNames[color];
}
var showPicker = function(source) {
var hex = new Array('00', '33', '66','99','CC','FF');
var count = 0;
document.writeln('<table width="1200" height="600">');
for(var x in hex) {
document.writeln('<tr>');
for(var y in hex) {
for(var z in hex) {
var color = hex[x] + "" + hex[y] + "" + hex[z];
document.writeln('<td bgcolor="#'+color+'" title="#'+color +'" onclick=changeBg(\''+color+'\')></td>');
count++;
}
}
document.writeln('</tr>');
}
document.writeln('</table>');
}
showPicker();
})();
</script>
<input type="text" id="color" readonly = true/>
</body>
I'm very new to both JQuery and Javascript. I have an feed, I would like to display these feed inside a collapsible div AS a collapsible div. I have the following Javascript file:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("feeds", "1");
google.setOnLoadCallback(showFeed);
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.setNumEntries(10);
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
di.innerHTML = '<h3>' + entry.title + '</h3>';
di.innerHTML += '<p>' + entry.contentSnippet + '</p>';
container.appendChild(di);
}
} else {
var container = document.getElementById("headlines");
container.innerHTML = '<li>Get your geek news fix at site</li>';
}
});
}
</script>
<body>
<div data-role="collapsible-set" id="headlines"></div>
</body>
This should fetch all my feed names and put them in a collapsible div, it does exactly that but it shows the names as plain HTML text instead of a JQuery Mobile collapsible div.
#AML, that is more a comment than an answer because a don't analyse your entire code, but I will put here for formatting purposes.
In the line:
var di = document.createElement("div").setAttributeNode("data-role", "collapsible");
You don't take a pointer(di) to the new created element, you take a result of the setAttributeNode(...), You need to split the code in two lines like that:
var di = document.createElement("div");
di.setAttribute("data-role", "collapsible");
There are a problem with setAttributeNode actually is setAttribute.
Now is working, see at http://pannonicaquartet.com/test/feeds.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
.collapsible{
display : none;
}
h3{
background-color : lightgray;
}
</style>
<script src="https://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load("feeds", "1");
function showFeed() {
var feed = new google.feeds.Feed("http://www.varzesh3.com/rss");
feed.load(function(result) {
if (!result.error) {
var container = document.getElementById("headlines");
for (var i = 0; i < result.feed.entries.length; i++) {
var entry = result.feed.entries[i];
var div = document.createElement("div");
div.onclick = function(evt){
var elP = this.children[1];
if(elP.style.display == 'inline'){
elP.style.display = 'none';
}else{
elP.style.display = 'inline';
}
};
div.innerHTML = '<h3>' + entry.title + '</h3>';
div.innerHTML += '<p class="collapsible">' + entry.contentSnippet + '</p>';
container.appendChild(div);
}
}
});
}
google.setOnLoadCallback(showFeed);
</script>
I am trying to get tweets from different zip codes.For doing this, I am using latitude and longitude values for each zip code. So far I want to get 3 tweets for each zip code(I have 2 zip codes), but it is working only for one zip code.
Any suggestion will be appreciated. Thank you in advance!
Here is my code:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var lat=[41.9716,42.0411];
var lng=[-87.7026,-87.6900];
$(document).ready(function() {
for(var i=1; i<2; i++)
{
$.getJSON('http://search.twitter.com/search.json?q=business&geocode='+lat[i]+','+lng[i]+',5mi&lang=en&callback=?', function(data) {
var data = data.results;
var html = "";
for(var j=0; j<3;j++){
html += "<div style='width:600px;border:solid thin blue'><img src='"+data[j].profile_image_url+"'/><a href='http://twitter.com/" + data[j].from_user + "'>#"+ data[j].from_user + "</a>: " + data[j].text + "</div>";
}
$('.content'+i).html(html);
}); }
});
</script>
</head>
<body>
<div class="content1"></div>
<div class="content2"></div>
</body>
I found 2 problems with your code:
1) If you want to iterate 2 times, your for function should be like this: for (var i = 0; i < 2; i++)
2) You must have in consideration that the function that gets called in $.getJSON runs asynchronously, so when that function gets called the for will have already finished, therefore you can't use the i value with that purpose inside that function.
So, after correcting those 2 things in your code you should be able to get what you want. Try with something like this:
<!DOCTYPE HTML>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
var lat = [41.9716, 42.0411];
var lng = [-87.7026, -87.6900];
var count = 1;
$(document).ready(function () {
for (var i = 0; i < 2; i++) {
$.getJSON('http://search.twitter.com/search.json?q=business&geocode=' + lat[i] + ',' + lng[i] + ',5mi&lang=en&callback=?', function (data) {
var data = data.results;
var html = "";
for (var j = 0; j < 3; j++) {
html += "<div style='width:600px;border:solid thin blue'><img src='" + data[j].profile_image_url + "'/><a href='http://twitter.com/" + data[j].from_user + "'>#" + data[j].from_user + "</a>: " + data[j].text + "</div>";
}
$('.content' + count++).html(html);
});
}
});
</script>
</head>
<body>
<div class="content1"></div>
<div class="content2"></div>
</body>
</html>