Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I'm trying to execute a function that alerts an array but it doesn't work. When I press the Add button, I'm supposed to have an alert containing Lat/lng, but no alert appears.
You can see my working code here: jsfiddle. Press the Add button to see the phenomenon. I call the function f() in line 195 but I don't get anything.
My HTML code:
<div id="info"></div>
<div id="dvMap"></div>
<div id="directions_panel" style="margin:20px;background-color:#FFEE77;"></div>
<div id="wrapper">Paste coordinate data here:
<form onSubmit="javascript:return false;">
<textarea id="Coords" cols="50" rows="25"></textarea>
<div>
<input type="button" id="btnAdd" class="Button" value="Add Markers" onClick="ProcessData()">
<input type="button" id="btnClear" class="Button" value="Clear Map" onClick="Clear()">
</div>
<br>
</form>
</div>
My Javascript code:
var directionsDisplay = [];
var directionsService = [];
var map = null;
var g = [];
var path = new Array();
var routeSegment = 0;
var k = 0;
function inizialise() {
var mapOptions = {
center: new google.maps.LatLng(33.730166863, 130.7446296584),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
document.getElementById("Coords").value = '33.29702, 130.54948000000002' + '\n' + '33.29764, 130.54986000000002' + '\n' + '33.29793, 130.55010000000001' + '\n' + '33.298730000000006, 130.55066000000002' + '\n' + '33.299620000000004, 130.55129000000002'
// calcRoute() ;
}
var MyArray = [];
function Clear() {
//alert(directionsDisplay.length);
MyArray = [];
for (var i = 0; i < directionsDisplay.length; i++) {
directionsDisplay[i].setMap(null);
}
// directionsDisplay = [];
document.getElementById("Coords").value = "";
document.getElementById("Coords").disabled = false;
document.getElementById("btnAdd").disabled = false;
}
function ProcessData() {
var Points = document.getElementById("Coords").value
if (document.getElementById("Coords").value != '') {
var Points = document.getElementById("Coords").value
calcRoute(Points);
}
}
/*
function ProcessData() {
alert('ok');
if (document.getElementById("Coords").value != '') {
var Points = document.getElementById("Coords").value
AddMarkers(Points);
}
}*/
function AddMarkers(data) {
var MyData = data.substr(0, data.length);
MyArray = MyData.split("\n");
//alert(MyArray[2]);
// calcRoute();
t();
}
function calcRoute(data) {
var MyData = data.substr(0, data.length);
MyArray = MyData.split("\n");
var input_msg = MyArray;
var locations = new Array();
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < input_msg.length; i++) {
var tmp_lat_lng = input_msg[i].split(",");
//var s = new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]);
locations.push(new google.maps.LatLng(tmp_lat_lng[0], tmp_lat_lng[1]));
bounds.extend(locations[locations.length - 1]);
}
/* var mapOptions = {
// center: locations[0],
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions);
*/
map.fitBounds(bounds);
var summaryPanel = document.getElementById("directions_panel");
summaryPanel.innerHTML = "";
var i = locations.length;
var index = 0;
while (i != 0) {
if (i < 3) {
var tmp_locations = new Array();
for (var j = index; j < locations.length; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = 0;
index = locations.length;
}
if (i >= 3 && i <= 10) {
console.log("before :fun < 10: i value " + i + " index value" + index);
var tmp_locations = new Array();
for (var j = index; j < locations.length; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = 0;
index = locations.length;
console.log("after fun < 10: i value " + i + " index value" + index);
}
if (i >= 10) {
console.log("before :fun > 10: i value " + i + " index value" + index);
var tmp_locations = new Array();
for (var j = index; j < index + 10; j++) {
tmp_locations.push(locations[j]);
}
drawRouteMap(tmp_locations);
i = i - 9;
index = index + 9;
console.log("after fun > 10: i value " + i + " index value" + index);
}
}
}
var coord = new Array();
function drawRouteMap(locations) {
var start, end;
var waypts = [];
for (var k = 0; k < locations.length; k++) {
if (k >= 1 && k <= locations.length - 2) {
waypts.push({
location: locations[k],
stopover: true
});
}
if (k == 0) start = locations[k];
if (k == locations.length - 1) end = locations[k];
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: false,
travelMode: google.maps.TravelMode.DRIVING
};
console.log(request);
directionsService.push(new google.maps.DirectionsService());
var instance = directionsService.length - 1;
directionsDisplay.push(new google.maps.DirectionsRenderer({
preserveViewport: true
}));
directionsDisplay[instance].setMap(map);
directionsService[instance].route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log(status);
directionsDisplay[instance].setDirections(response);
var f = response.routes[0];
// var summaryPanel = document.getElementById("directions_panel");
var route = directionsDisplay[instance].getDirections().routes[0];
// var routes = response.routes;
var points = route.overview_path;
//alert(points);
var ul = document.getElementById("directions_panel");
var legs = response.routes[0].legs;
for (i = 0; i < legs.length; i++) {
var steps = legs[i].steps;
for (j = 0; j < steps.length; j++) {
var nextSegment = steps[j].path;
for (k = 0; k < nextSegment.length; k++) {
// alert(nextSegment[k]);
var li = document.createElement('P');
li.innerHTML = getLatLng(nextSegment[k]);
ul.appendChild(li);
// polyline.getPath().push(nextSegment[k]);
//bounds.extend(nextSegment[k]);
coord.push( getLatLng(nextSegment[k]));
f(coord);
}
}
}
} else {
alert("directions response " + status);
}
});
}
function f( r) {
alert(r);
}
function getLatLng(point) {
//alert(MyArray.length);
var lat = point.lat(),
lng = point.lng();
var tmp = MyArray[k].split(",");
// alert( Math.abs(parseFloat(tmp[0]- lat)) )
if (Math.abs(parseFloat(tmp[0] - lat)) < 0.00009 && Math.abs(parseFloat(tmp[1] - lng)) < 0.00009) {
k++;
// alert(k);
//if(k==MyArray.length) { f('animation'); }
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 1},";
} else {
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 0},";
}
}
google.maps.event.addDomListener(window, 'load', inizialise);
The problematic code is in line 195: I call f(coord), but the alert doesn't appear. I have defined the f function as such:
function f(r) {
alert(r);
}
You're overwriting f with an object in line 173:
var f = response.routes[0];
So when you try to call f, it's not a function, but an object (try logging typeof f before the call: you will get 'object').
I managed to fix the problem. I edite my function 'getLatLng()' such as :
function getLatLng(point, array) {
//alert(k);
var lat = point.lat(),
lng = point.lng();
var tmp = MyArray[k].split(",");
// alert( Math.abs(parseFloat(tmp[0]- lat)) )
if (Math.abs(parseFloat(tmp[0] - lat)) < 0.00009 && Math.abs(parseFloat(tmp[1] - lng)) < 0.00009) {
k++;
array.push({
"lat": lat ,
"lng": lng,
"stop":1
});
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 1},";
} else {
array.push({
"lat": lat ,
"lng": lng,
"stop":1
});
return " { \"lat\": " + lat + " ,\"lng\" : " + lng + " ,\"waypoint\" : 0},";
}
}
Now I can acess to the element of my array. Here my code
Related
function initialize(woeid) {
$.ajax({
url: "php/getMapping.php",
type: 'get',
cache: false,
success: function(overallArray) {
console.log(overallArray);
console.log(overallArray.length);
for (var i = 0; i < overallArray.length; i++) {
if (overallArray[i].woeid == woeid) {
var cityArray = overallArray[i];
break;
}
}
var cityHashTags = cityArray.hashTags.split(";");
document.getElementById("cityTitle").innerHTML = cityArray.name;
document.getElementById("rssLink").href = "php/getRssFeed.php?woeid=" + cityArray.woeid;
document.getElementById("cityDescription").innerHTML = cityArray.desc;
document.getElementById("cityPopulation").innerHTML = `Population: ${cityArray.curPop}`;
document.getElementById("cityCountry").innerHTML = `Country: ${cityArray.country}`;
document.getElementById("cityLat").innerHTML = `Lat : ${cityArray.lat}`;
document.getElementById("cityLong").innerHTML = `Long : ${cityArray.lng}`;
for (var j = 0; j < cityHashTags.length; j++) {
document.getElementById("cityTwitter").innerHTML += "<a href='https://twitter.com/search?q=" + cityHashTags[j] + "' target='_blank'>#" + cityHashTags[j] + "</a>  ";
}
if (0 < cityArray.images.length) {
for (var i = 0; i < cityArray.images.length; i++) {
document.getElementById("cityPhotos").innerHTML += '<div class="w3-display-container mySlides w3-animate-opacity"><img src="pictures/poi/' + cityArray.images[i].imageFle + '" style="width:100%;height:100%;"><h4>' + cityArray.images[i].name + '</h4><p style="text-align:center;">' + cityArray.images[i].desc + '</p></div>';
}
}
var mapCanvas = document.getElementById('mapCanvas');
var mapOptions = {
center: new google.maps.LatLng(cityArray.lat, cityArray.lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.TERRAIN,
disableDefaultUI: 1
}
var map = new google.maps.Map(mapCanvas, mapOptions);
setMarkers(map, cityArray.poi);
}
});
}
I have attached the code of my Javascript. The array "overallArray" contains a JSON object. I attached a picture of the array. How can I put this whole data into 2 array? Two array should be based on the two woeid. Rest of the data goes under those two. I can hardcode the data but I am looking for a way to dynamically assign the key and value. I hope it all make sense.
This will work something like , push Json array in existing Empty / jsonArray
cityArray [];
let valuesX = {
mapTypeId: document.getElementsByName('mapTypeId')[i].value,
cityArray.push(valuesX);
}
var cityArray = JSON.stringify(cityArray);
This is the code I have to show the markers on the map:
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(map);
}
}
It's working, but I can't zoom to view all markers in the window when I refresh the page.
I tried:
map.fitBounds(coordinates.getBounds());
But it's not working.
Update your code to:
var fg = L.featureGroup();
fg.addTo(map)
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(fg);
}
}
map.fitBounds(fg.getBounds());
I' m having this problem , when I load my page and insert Origin and Destination, after clicking the button "locate" it doesn't show anything in the google map, because it says Response is not an object , so I tried to stamp it with console.log and it says Response=null , but if I reload the page and click fast on Locate , then it draws the route.
Here's the code
function init(){
var latlng = new google.maps.LatLng(40.635636, 17.942414);
var mapOptions = { zoom: 12, center: latlng };
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function updateMap(){
init();
var originGeocoder = new google.maps.Geocoder();
var destinationGeocoder = new google.maps.Geocoder();
var origin = document.getElementById( "origin" ).value + " Brindisi 72100";
var destination = document.getElementById( "destination" ).value + " Brindisi 72100";
var directionsService2 = new google.maps.DirectionsService();
originGeocoder.geocode( { 'address': origin }, function(results, status) {
if ( status == google.maps.GeocoderStatus.OK ) {
var startLatLng = results[0].geometry.location;
var oLat = startLatLng.lat();
var oLng = startLatLng.lng();
document.getElementById('cStart').innerHTML = oLat + " " + oLng;
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
//Chiamata asincrona alle API per ottenere Lat e Lng dell' indirizzo di destinazione
destinationGeocoder.geocode( { 'address': destination }, function(results, status) {
if ( status == google.maps.GeocoderStatus.OK ) {
var destLatLng = results[0].geometry.location;
var dLat = destLatLng.lat();
var dLng = destLatLng.lng();
document.getElementById('cDestination').innerHTML = typeof dLat;
document.getElementById('cDestination').innerHTML = dLat + " " + dLng;
}
else{
alert("Geocode was not successful for the following reason: " + status);
}
});
//Salva in req[] le varie distanze tra le paline e la destinazione
singleObjToStop(origin,destination,function(paline,req,reqO){
console.log("1");
//Trova la palina piĆ¹ vicina alla destinazione
calcSingleDis(paline,req,reqO,function(w2,w1){
console.log("2");
//Disegna i waypoints(?)
reqEnd(origin,destination,w1,w2,function(request){
console.log("3");
directionsService2.route(request, function(response, status) {
console.log("4");
console.log(response);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById("distance");
summaryPanel.innerHTML = "";
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += "<b>Route Segment: " + routeSegment + "</b><br />";
summaryPanel.innerHTML += route.legs[i].start_address + " to ";
summaryPanel.innerHTML += route.legs[i].end_address + "<br />";
summaryPanel.innerHTML += route.legs[i].distance.text + " ";
summaryPanel.innerHTML += route.legs[i].duration.text + "<br /><br />" ;
}
computeTotalDistance(response);
}
else{
console.log("ENTRA QUA STRONZO");
console.log("Fermata partenza = " + w1);
console.log("Fermata arrivo = " + w2);
}
});
directionsDisplay.setMap(map);
});
});
});
}
function singleObjToStop(origin,destination,callback){
var data=<?php echo $data; ?>;
var a,b,i=0;
var paline = new Array();
var req = new Array();
var reqO = new Array();
var num = <?php echo $n; ?>;
$.each(data, function(fieldName, fieldValue) {
a=fieldValue.geoLat;
b=fieldValue.geoLong;
a=parseFloat(a);
b=parseFloat(b);
paline[i]=new google.maps.LatLng(a,b);
req[i] = {
origin:paline[i],
destination:destination,
travelMode: google.maps.TravelMode.WALKING
};
reqO[i] = {
origin:origin,
destination:paline[i],
travelMode: google.maps.TravelMode.WALKING
};
i++;
if(i==num){
callback(paline,req,reqO);
}
});
}
function calcSingleDis(paline, req, reqO, callback) {
var directionsService = new google.maps.DirectionsService();
var c = 10000000;
var w2 = new google.maps.LatLng(0, 0);
var w1 = new google.maps.LatLng(0, 0);
var num = <?php echo $n; ?>;
var j = (num - 1);
var t;
var cO = 10000000;
var numO = <?php echo $n; ?>;
var jO = 0;
for (j = 0; j < num; j++) {
t = 0;
directionsService.route(req[j], function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
//directionsDisplay.setDirections(response);
var troute = response.routes[0];
var dis = parseFloat((troute.legs[0].distance.text).replace(",", "."));
document.getElementById('test').innerHTML = dis;
//se distanza minore di quella minore trovata fin ora la cambia
if (dis < c) {
w2 = paline[j - num];
c = dis;
}
if (t == (num - 1)) {
console.log("QUA ENTRA LOL");
for (jO = 0; jO < numO; jO++) {
console.log("E NON ENTRA MANNAC");
t = 0;
directionsService.route(reqO[jO], function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
console.log("E NON ENTRA MANNAC22222");
//directionsDisplay.setDirections(response);
var troute = response.routes[0];
var disO = parseFloat((troute.legs[0].distance.text).replace(",", "."));
document.getElementById('test').innerHTML = dis;
//se distanza minore di quella minore trovata fin ora la cambia
if (disO < cO) {
w1 = paline[jO - numO];
cO = disO;
}
if (t == (numO - 1)) {
console.log("W1 = " + w1);
console.log(response);
callback(w2, w1);
}
}
jO++;
t++;
});
}
}
}
j++;
t++;
});
}
}
function reqEnd(origin,destination,w1,w2,callback){
var request = {
origin:origin,
destination:destination,
waypoints: [{location: w1} , {location: w2}],
//waypoints: [{location: w2}],
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.WALKING
};
callback(request);
}
function computeTotalDistance(result) {
var totalDist = 0;
var totalTime = 0;
var myroute = result.routes[0];
for (i = 0; i < myroute.legs.length; i++) {
totalDist += myroute.legs[i].distance.value;
totalTime += myroute.legs[i].duration.value;
}
totalDist = totalDist / 1000.
document.getElementById("total").innerHTML = "total distance is: "+ totalDist + " km<br>total time is: " + (totalTime / 60).toFixed(2) + " minutes";
}
google.maps.event.addDomListener( window, 'load', init );
The problem is related to the limit of query that you can use with Google Maps API v3.
You can take a look here: https://developers.google.com/maps/documentation/business/faq#google_maps_api_services
You probably do lots of requests to the API with your program, while you have quite restrictive limits as you can see from google Q&A.
Applications should throttle requests to avoid exceeding usage limits,
bearing in mind these apply to each client ID regardless of how many
IP addresses the requests are sent from.
You can throttle requests by putting them through a queue that keeps
track of when are requests sent. With a rate limit or 10 QPS (queries
per second), on sending the 11th request your application should check
the timestamp of the first request and wait until 1 second has passed.
The same should be applied to daily limits.
Even if throttling is implemented correctly applications should watch
out for responses with status code OVER_QUERY_LIMIT. If such response
is received, use the pause-and-retry mechanism explained in the Usage
limits exceeded section above to detect which limit has been exceeded.
You could find useful: How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?
The Google Maps API provides a geocoder class for geocoding and reverse geocoding dynamically from user input. read more check Geolocation demo here and more HTML5 Geolocation to check here
I have a list of latitude and longitude in database and I want to draw more polyline on google maps.
For example:
var i, j;
var polyline1 = new Array(latt.length);
str = new Array(latt.length);
for (var k = 0; k < latt.length; k++) {
i = latt[k].split(',');
j = longg[k].split(',');
str[k] = 'new GLatLng(' + i[0] + ',' + j[0] + ')' + ',';
for (var count = 1; count < i.length; count++) {
str[k] += 'new GLatLng(' + i[count] + ',' + j[count] + ')' + ',';
}
str[k] = str[k] + 'new GLatLng(' + i[0] + ',' + j[0] + ')';
polyline1[k] = new GPolyline([str[k]], "#ff0000", 6);
map.addOverlay(polyline1[k]);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
}
but I'm getting error
I don't understand the error - I can't see an a anywhere - but you're almost certainly using GPolyline wrong. It wants an array of objects, not a single-element array of a string of JavaScript:
var polyline1 = new Array(latt.length);
str = new Array(latt.length);
for (var k = 0; k < latt.length; k++) {
var i = latt[k].split(',');
var j = longg[k].split(',');
var latlngs = [];
for (var count = 0; count < i.length; count++) {
latlngs.push(new GLatLng(parseFloat(i[count]), parseFloat(j[count])));
}
polyline1[k] = new GPolyline(latlngs, "#ff0000", 6);
map.addOverlay(polyline1[k]);
}
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
I don't know if the parseFloats are actually necessary. You probably want to move the control adds outside the loop too.
Could anyone suggest performance improvements for the function I've written (below, javascript with bits of jquery)? Or point out any glaring, basic flaws? Essentially I have a javascript Google map and a set of list based results too, and the function is fired by a checkbox click, which looks at the selection of checkboxes (each identifying a 'filter') and whittles the array data down accordingly, altering the DOM and updating the Google map markers according to that. There's a 'fake' loader image in there too at the mo that's just on a delay so that it animates before the UI hangs!
function updateFilters(currentCheck) {
if (currentCheck == undefined || (currentCheck != undefined && currentCheck.disabled == false)) {
var delay = 0;
if(document.getElementById('loader').style.display == 'none') {
$('#loader').css('display', 'block');
delay = 750;
}
$('#loader').delay(delay).hide(0, function(){
if (markers.length > 0) {
clearMarkers();
}
var filters = document.aspnetForm.filters;
var markerDataArray = [];
var filterCount = 0;
var currentfilters = '';
var infoWindow = new google.maps.InfoWindow({});
for (i = 0; i < filters.length; i++) {
var currentFilter = filters[i];
if (currentFilter.checked == true) {
var filtername;
if (currentFilter.parentNode.getElementsByTagName('a')[0].textContent != undefined) {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].textContent;
} else {
filtername = currentFilter.parentNode.getElementsByTagName('a')[0].innerText;
}
currentfilters += '<li>' + $.trim(filtername) +
$.trim(document.getElementById('remhide').innerHTML).replace('#"','#" onclick="toggleCheck(\'' + currentFilter.id + '\');return false;"');
var nextFilterArray = [];
filterCount++;
for (k = 0; k < filterinfo.length; k++) {
var filtertype = filterinfo[k][0];
if (filterinfo[k][0] == currentFilter.id) {
var sitearray = filterinfo[k][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
if (filterCount > 1) {
nextFilterArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
} else {
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
if (filterCount > 1) {
var itemsToRemove = [];
for (j = 0; j < markerDataArray.length; j++) {
var exists = false;
for (k = 0; k < nextFilterArray.length; k++) {
if (markerDataArray[j] == nextFilterArray[k]) {
exists = true;
}
}
if (exists == false) {
itemsToRemove.push(j);
}
}
var itemsRemoved = 0;
for (j = 0; j < itemsToRemove.length; j++) {
markerDataArray.splice(itemsToRemove[j]-itemsRemoved,1);
itemsRemoved++;
}
}
}
}
if (currentfilters != '') {
document.getElementById('appliedfilters').innerHTML = currentfilters;
document.getElementById('currentfilters').style.display = 'block';
} else {
document.getElementById('currentfilters').style.display = 'none';
}
if (filterCount < 1) {
for (j = 0; j < filterinfo.length; j++) {
var filtertype = filterinfo[j][0];
if (filterinfo[j][0] == 'allvalidsites') {
var sitearray = filterinfo[j][1];
for (m = 0; m < sitearray.length; m++) {
var thissite = sitearray[m].split(',');
markerDataArray.push(thissite[2] + '|' + thissite[1]
+ '|' + thissite[0]);
}
}
}
}
var infoWindow = new google.maps.InfoWindow({});
var resultHTML = '<div id="page1" class="page"><ul>';
var count = 0;
var page = 1;
var paging = '<li class="selected">1</li>';
for (i = 0; i < markerDataArray.length; i++) {
var markerInfArray = markerDataArray[i].split('|');
var url = '';
var name = '';
var placename = '';
var region = '';
var summaryimage = 'images/controls/placeholder.gif';
var summary = '';
var flag = 'images/controls/placeholderf.gif';
for (j = 0; j < tsiteinfo.length; j++) {
var thissite = tsiteinfo[j].split('|');
if (thissite[0] == markerInfArray[2]) {
name = thissite[1];
placename = thissite[2];
region = thissite[3];
if (thissite[4] != '') {
summaryimage = thissite[4];
}
summary = thissite[5];
if (thissite[6] != '') {
flag = thissite[6];
}
}
}
for (k = 0; k < sitemapperinfo.length; k++) {
var thissite = sitemapperinfo[k].split('|');
if (thissite[0] == markerInfArray[2]) {
url = thissite[1];
}
}
var markerLatLng = new google.maps.LatLng(markerInfArray[1].toString(), markerInfArray[0].toString());
var infoWindowContent = '<div class="infowindow">' + markerInfArray[2] + ': ';
var siteurl = approot + '/sites/' + url;
infoWindowContent += '<strong>' + name + '</strong>';
infoWindowContent += '<br /><br/><em>' + placename + ', ' + region + '</em></div>';
marker = new google.maps.Marker({
position: markerLatLng,
title: $("<div/>").html(name).text(),
shadow: shadow,
icon: image
});
addInfo(infoWindow, marker, infoWindowContent);
markers.push(marker);
count++;
if ((count > 20) && ((count % 20) == 1)) { // 20 per page
page++;
resultHTML += '</ul></div><div id="page' + page + '" class="page"><ul>';
paging += '<li>' + page + '</li>';
}
resultHTML += '<li><div class="namehead"><h2>' + name + ' <span>' + placename + ', ' + region + '</span></h2></div>' +
'<div class="codehead"><h2><img alt="' + region + '" src="' + approot +
'/' + flag + '" /> ' + markerInfArray[2] + '</h2></div>' +
'<div class="resultcontent"><img alt="' + name + '" src="' + approot +
'/' + summaryimage +'" />' + '<p>' + summary + '</p>' + document.getElementById('buttonhide').innerHTML.replace('#',siteurl) + '</div></li>';
}
$('#filteredmap .paging').each(function(){
$(this).html(paging);
});
document.getElementById('resultslist').innerHTML = resultHTML + '</ul></div>';
document.getElementById('count').innerHTML = count + ' ';
document.getElementById('page1').style.display = 'block';
for (t = 0; t < markers.length; t++) {
markers[t].setMap(filteredMap);
}
});
}
}
function clearMarkers() {
for (i = 0; i < markers.length; i++) {
markers[i].setMap(null);
markers[i] = null;
}
markers.length = 0;
}
However, I'm suffering from performance issues (UI hanging) specifically in IE6 and 7 when the number of results is high, but not in any other modern browsers, i.e. FF, Chrome, Safari etc. It is much worse when the Google map markers are being created and added (if I remove this portion it is still slugglish, but not to the same degree). Can you suggest where I'm going wrong with this?
Thanks in advance :) Please be gentle if you can, I don't do much javascript work and I'm pretty new to it and jquery!
This looks like a lot of work to do at the client no matter what.
Why don't you do this at the server instead, constructing all the HTML there, and just refresh the relevant sections with the results of an ajax query?