Google Map javascript MarkerManager markers not showing - javascript

I have a map that reads an XML file; it's all very simple and copied from here:
http://geochalkboard.wordpress.com/2009/03/30/reading-xml-files-with-the-google-maps-api/
My version is here:
http://www.cloudfund.me/maps/mashup.html and the data file it's reading is here:
converted.xml in the same directory.
I don't get any points at all, when I run it. I put some console logging in to see if I could see anything, but as far as that's concerned, it just runs through without a hitch. The file loads ok, and I can watch the code loop through all the rows (208 in this example) without any problems.
The only warning I'm getting is the 'Resource interpreted as other passed as undefined' one; having had a look at some of the other threads, I can't see anything that helps - no empty src links, etc. As far as I can tell, this shouldn't stop it marking the points, either.
Here's the real kicker - in trying to trace this error, I set up an exact replica of the original code on my own server, and got an error about null fields, which I added some conditional code to to sort; this version works on my server. This is austin.html in the same directory (sorry, can't do more than two links in my first posts!)
So - my code is this:
<title>Test </title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false&key=AIzaSyDgybFoyn3i5j_6d7ul7p2dPNQ5b1xOWnk"
type="text/javascript">console.log("Loaded Maps API");</script>
<script src="http://gmaps-utility-library.googlecode.com/svn/trunk/markermanager/release/src/markermanager.js">console.log("MarkerManager");</script>
<script type="text/javascript">
console.log("Into Main Script");
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(51.39906378, -2.449545605), 13);
map.setUIToDefault();
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
map.addMapType(G_PHYSICAL_MAP);
map.setMapType(G_PHYSICAL_MAP);
console.log("Reached end of map initialising");
addMarkersFromXML();
console.log("MarkersfromXML")
}
}
function addMarkersFromXML(){
var batch = [];
mgr = new MarkerManager(map);
var request = GXmlHttp.create();
console.log("About to open converted.xml")
request.open('GET', 'converted.xml', true);
console.log("Opened Converted.xml")
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200)
{
var xmlDoc = request.responseXML;
var xmlrows = xmlDoc.documentElement.getElementsByTagName("row");
for (var i = 0; i < xmlrows.length; i++) {
var xmlrow = xmlrows[i];
console.log("Running through row number",i)
var xmlcellLongitude = xmlrow.getElementsByTagName("longitude")[0];
console.log(xmlcellLongitude);
var xmlcellLatitude = xmlrow.getElementsByTagName("latitude")[0];
var point = new GLatLng(parseFloat(xmlcellLatitude.firstChild.data),parseFloat(xmlcellLongitude.firstChild.data));
//get the PAO
var xmlcellAssetName = xmlrow.getElementsByTagName("pao")[0];
console.log(xmlcellAssetName);
var celltextAssetName = xmlcellAssetName.firstChild.data;
//get the area
var xmlcellArea = xmlrow.getElementsByTagName("area")[0];
console.log(xmlcellArea);
var celltextArea = xmlcellArea.firstChild.data;
//get the land type
var xmlcellLandType = xmlrow.getElementsByTagName("landtype")[0];
console.log(xmlcellLandType);
var celltextLandType = xmlcellLandType.firstChild.data;
//get the Planning Permissions
var xmlcellPlanning = xmlrow.getElementsByTagName("planning")[0];
console.log(xmlcellPlanning);
var celltextPlanning = xmlcellPlanning.firstChild.data;
var htmlString = "Asset Name: " + celltextAssetName + "<br>" + "Size: " + celltextArea + "<br>" + "Land Type: " + celltextLandType + "<br>" + "Planning Permissions: " + celltextPlanning;
//var htmlString = 'yes'
var marker = createMarker(point,htmlString);
batch.push(marker);
}
mgr.addMarkers(batch,50);
mgr.refresh();
}
}
request.send(null);
}
function createMarker(point,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()">
<div id="map_canvas" style="width: 1100px; height: 700px"></div>
</body>
</html>

Think you have a typo. In your code, you're pulling an incomplete URL for the API:
<script src="//maps.google.com/maps?file=api&v=2&sensor=false&key=AIzaSyDgybFoyn3i5j_6d7ul7p2dPNQ5b1xOWnk"
That errant // seems to be throwing the code off.
Though, to be perfectly honest, the originating example (and austin.html) doesn't exactly work as one would imagine it should. The points do get rendered, but no effective clustering takes place when you zoom out. Suspect that the 2.0 branch of the API got moved to a newer version and created a bit of an incompatibility.
Recommend that you rewrite this in API version 3. There is a cluster manager that works for it quite well.
See http://tools.voanews2.com/nuclear_reactors/

Related

Getting intermittent 'google not defined' and other errors using maps api v3

My application makes api calls to the census and uses that data in combination with Google Maps API v3. It works as expected much of the time, but I’m getting an intermittent error of ‘Initmap is not defined’, or ‘google is not defined’, or ‘TypeError: map.data.getFeatureById(...) is undefined’ without any discernible reason.
HTML:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3&key=KEY1234&callback=initMap" async defer
></script>
<script src="js/mapfunc.js"></script>
</head>
<body>
<div id="map"></div>
<script>var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: 35, lng: -106}
});
}</script>
</body>
</html>
JS:
function loadMapShapes() {
map.data.loadGeoJson('jsonya2.geojson', { idPropertyName: 'STATE' });
variable = 'B01003_001E,NAME';
variable2 = ',B01001F_002E';
loadCensusData(variable);
}
function loadCensusData(variable) {
// load the requested variable from the census API
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.census.gov/data/2014/acs5/?get=' +
variable + '&for=state:*&key=KEY123');
xhr.onload = function() {
var censusData = JSON.parse(xhr.responseText);
censusData.shift(); // the first row contains column names
censusData.forEach(function(row) {
censusMin = 0;
censusMax = 36000000;
var censusVariable = parseFloat(row[0]);
var stateName = row[1];
var stateId = row[2];
// keep track of min and max values
if (censusVariable < censusMin) {
censusMin = censusVariable;
}
if (censusVariable > censusMax) {
censusMax = censusVariable;
}
// update the existing row with the new data
coolid = map.data.getFeatureById(stateId);// <-- Here's where
//I get the error most often: "TypeError: map.data.getFeatureById(...) is undefined"
if (coolid !== undefined) {
map.data
.getFeatureById(stateId)
.setProperty('census_variable', censusVariable);
map.data
.getFeatureById(stateId)
.setProperty('census_variable1', stateName);
}
coolstate = map.data.getFeatureById(stateName);
});
Again - this code works maybe 40% of the time, and throws one of the above-described errors the rest of the time. I may notice an increase in errors during the day but can't be sure.
Thanks a lot for any thoughts, here's a link to a live version of this code with census and google maps API calls:
http://dukecitydigital.com/c1/
loadGeoJson runs asynchronously, use the callback of loadGeoJson to execute further functions which depend on the result of loadGeoJson:
function loadMapShapes() {
variable = 'B01003_001E,NAME';
variable2 = ',B01001F_002E';
map.data.loadGeoJson('jsonya2.geojson', { idPropertyName:'STATE'}, function(){
loadCensusData(variable);
});
}
Here is the code I am using to avoid 'undefined' error:
// update the existing row with the new data
if (typeof(map.data.getFeatureById(stateId)) != "undefined") {
map.data
.getFeatureById(stateId)
.setProperty('census_variable', censusVariable);
}

(PHP / JS) Google Maps API 3 not getting results in IE, FF & iPad (Safari / Chrome) but does on Chrome & M8 Android (Native / Chrome)

Explanation of Issue
This isn't an easy one for me to explain as I'm not sure on what is going on at all. Basically I am currently having a play with the following Google APIs:
Geocoding API
Google Maps JavaScript API v3
Places API
I have been working with Google Chrome on Windows 7, and have successfully been able to create a system which uses the Google Maps API V3 and allows me to search a location and pull back businesses near that location based on the Geocoded LatLng created when the given location is sent through the Google Geocoder.
This is working fine on my PC in Google Chrome, but isn't working in FireFox or Internet Explorer. Further to this, it also does not work on my iPad with either Safari or Chrome, however it does work on my HTC M8 on both the native browsers and Chrome.
Basically a user searches a location (only searching "Southport" in the second input box without anything in the first works at the moment) and gets a list of businesses back within 25km. This search function returns results as expect in Chrome, but doesn't return results or center the map on the correct location otherwise.
There is a businesses xml schema produced during the search. This is empty when checking through Firebug in FireFox.
Imasges for how the system should look when working, and how it looks when it's not working are provided at the bottom as google drive downloads... you will need HTTPS:
How the map is generated
Initially load() is ran onload:
<body class="search" onload="load();">
This fires initialize();
The code that is ran is:
function initialize() {
var input = document.getElementById('loc');
var options = {componentRestrictions: {}};
new google.maps.places.Autocomplete(input, options);
}
google.maps.event.addDomListener(window, 'load', initialize);
FYI: After this, a number of scripts are called, these are included by the Google API I believe as they are not hard coded (In order: common.js, util.js, geocoder.js, controls.js, places_impl.js, map.js, infowindow.js, onion.js, stats.js and marker.js).
Just before the above bit of script is called, I have a reference to the Google Maps API. This again adds some more references to others .js files that aren't hardcoded:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=EXAMPLE_APIKEY&sensor=false&libraries=places"></script>
<script src="https://maps.gstatic.com/maps-api-v3/api/js/20/5/main.js"></script>
<script src="https://maps.gstatic.com/maps-api-v3/api/js/20/5/places.js"></script>
<script type="text/javascript" src="/library/inc/structure/business/widgets/google-map/google-map.js"></script>
As you may notice, after the call to the Google Map API, main.js and places.js are also called, these are not hardcoded, after this google-map.js is called, and then beneath all this the initialize() function is called along with the other mentioned scripts.
load(); results in the following function being called (the vars at top are public vars for all of google-map.js):
//<![CDATA[
var map;
var businesses = [];
var infoWindow;
var locationSelect;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap',
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
infoWindow = new google.maps.InfoWindow();
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var businessNum = locationSelect.options[locationSelect.selectedIndex].value;
if (businessNum != "none"){
google.maps.event.trigger(businesses[businessNum], 'click');
}
};
}
This creates the map, and also listens for when the user selects a location in the search results.
Getting the results
When search.php loads the follow function is ran:
var $_POST = <?php echo json_encode($_POST); ?>;
function searchLocation() {
var address = $_POST["loc"];
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
window.onload = searchLocation;
Which in turn runs searchLocationNear(); :
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = '/library/inc/structure/business/widgets/google-map/google-map.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var businessNodes = xml.documentElement.getElementsByTagName("business");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < businessNodes.length; i++) {
var business_id = businessNodes[i].getAttribute("business_id");
var name = businessNodes[i].getAttribute("name");
var address = businessNodes[i].getAttribute("address");
createSearchResults(name, distance, i, business_id, address);
createMarker(latlng, name, address);
bounds.extend(latlng);
}
map.fitBounds(bounds);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var businessNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(businesses[businessNum], 'click');
};
});
}
This LatLng is pushed through to Google-Map.php through the url:
/library/inc/structure/business/widgets/google-map/google-map.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
In google-map.php the following takes place:
$database="db_name";
$username="db_user";
$password="db_password";
$center_lat = $_GET["lat"];
$center_lng = $_GET["lng"];
$radius = $_GET["radius"];
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("businesses");
$parnode = $dom->appendChild($node);
// Opens a connection to a mySQL server
$connection=mysql_connect ($database, $username, $password);
if (!$connection) {
die("Not connected : " . mysql_error());
}
// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ("Can\'t use db : " . mysql_error());
}
// Search the rows in the markers table
$get_business_query = sprintf("SELECT business_id, address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM businesses HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20", mysql_real_escape_string($center_lat), mysql_real_escape_string($center_lng),
mysql_real_escape_string($center_lat),
mysql_real_escape_string($radius));
$get_business_result = mysql_query($get_business_query);
if (!$get_business_result) {
die("Invalid query: " . mysql_error());
}
header("Content-type: text/xml");
while ($get_business_row = #mysql_fetch_assoc($get_business_result))
{
$businessID = $get_business_row['business_id'];
$node = $dom->createElement("business");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("business_id", $get_business_row['business_id']);
$newnode->setAttribute("name", $get_business_row['name']);
$newnode->setAttribute("address", $get_business_row['address']);
}
echo $dom->saveXML();
A clever MySQL query then works out which of these businesses is located with a 25km radius (this is currently hard coded but will be an option eventually).
$get_business_query = sprintf("SELECT business_id, address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM businesses HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20", mysql_real_escape_string($center_lat), mysql_real_escape_string($center_lng),
mysql_real_escape_string($center_lat),
mysql_real_escape_string($radius));
$get_business_result = mysql_query($get_business_query);
The rows of the result are then iterated through and an XML node is created for each:
while ($get_business_row = #mysql_fetch_assoc($get_business_result))
{
$businessID = $get_business_row['business_id'];
$node = $dom->createElement("business");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("business_id", $get_business_row['business_id']);
$newnode->setAttribute("name", $get_business_row['name']);
$newnode->setAttribute("address", $get_business_row['address']);
}
echo $dom->saveXML();
The generated XML output is then read by Google-Map.js in searchLocationNear();
The rest of the Google-Map.js is as follows:
function createMarker(latlng, name, address) {
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: latlng
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
businesses.push(marker);
}
function createSearchResults(name, distance, num, business_id, address) {
var li = document.createElement("li");
li.value = num;
li.setAttribute("onmouseover", "selectBusinessOnMap(" + num + ")");
li.setAttribute("onmouseout", "deselectBusinessOnMap(" + num + ")");
//Start Search Results ---------------------------------
//Name
li.innerHTML += "<div class=\"result-name\">" + (num + 1) + ". " + name + "</div>";
//Distance
li.innerHTML += "<div class=\"result-distance\">(" + distance.toFixed(1) + ")";
//End Search Results ---------------------------------
locationSelect.appendChild(li);
}
function selectBusinessOnMap(num) {
var businessNum = num;
google.maps.event.trigger(businesses[businessNum], 'click');
}
function deselectBusinessOnMap(num) {
infoWindow.close();
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
function doNothing() {}
//]]>
Link to Site
MyWorthy.Services
Ignore first input box, and enter Southport in the second and search.
As per introduction to question it's only working in Chrome for me, not IE or Firefox etc.
Validation Errors
A couple of validation errors catch my eye but I'm not sure if are the cause, also no values will be submitted into the search through w3c so not sure if that's the reason for some errors
[Errors found while checking this document as HTML 4.01 Transitional!][11]
Links to research I have undertaken
Links to other questions with similar problems that I have attempted to apply to my own situation without much luck due to my lack of understanding of where the issue is actually occuring:
Google maps api 3 with places DEMO works only in Chrome… why? - This one seems to describe my situation the best ...
Same happens in Firefox and IE9... map and elements all fine, but when you press search resets all check boxes, search box and produces no results - effectively resets.
... is mentioned in the comments, and I get the feeling that that is somehow what is happening with my issues, though I'm really not sure.
2. [Google Maps V3 JavaScript works only in Chrome?]
3. [PHP code works on Chrome, but not on Firefox or IE]
4. [Google Maps API GeoJSON not working with IE 11, but works in Chrome] - This link introduced me to this ...
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
... not sure if this will have an affect and will be trying it out as soon as I get home later and will update this question with my findings (EDIT: It appears this is already in my code).
5. [What's the difference if exists or not?]
6. [Google Maps v2 to v3 API wrapper working in Chrome but not in Firefox / IE]
7. [Google Maps V3 JavaScript works only in Chrome?]
8. [Google Maps API and Javascript problem. It works perfectly in Firefox, WHY NOT Internet Explorer?] - Slightly unrelated I would have thought at first as the Error is only with IE, however I noticed this ...
okay i have figured it out. turned out I had a clash of variable names.
I fixed it by renaming the map div DOM element from map to something else.
it works great in Firefox and IE now.
Thanks for all the help i did receive here.
... this has made me think that perhaps I too have the map div DOM element named as 'map'. EDIT: Tried this, changed a few bits called "map" but didn't change anything, not sure if it was the DOM element though.
9. [Google maps api not showing in Firefox and IE but showing in Chrome and safari][9] - I have also seen this error on my travels a number of times but I don't think it is this that is occurring, however I could be wrong. Basically in FF and IE some users get a grey box where the map should be due to a CSS bug. I am actually seeing the map centered on the USA.
So ... Please Help ... !!!
Any feedback on the question, the layout, the research etc etc would be appreciated so I learn how to really contribute to StackOverflow.
Also any help and advice at all would be massively appreciated as I have no idea where to start with this issue as I am not really used to having this only working in Chrome! Normally used to just IE not working!!!
------------ Please view links to question that I couldn't add due to only allowing 2 urls -----------
2: http://gotoanswer.com/?q=Google+Maps+V3+JavaScript+works+only+in+Chrome%3F
3: http://stackoverflow.com/questions/19693799/php-code-works-on-chrome-but-not-on-firefox-or-ie
4: http://stackoverflow.com/questions/26678721/google-maps-api-geojson-not-working-with-ie-11-but-works-in-chrome
5: http://stackoverflow.com/questions/6771258/whats-the-difference-if-meta-http-equiv-x-ua-compatible-content-ie-edge-e
6: http://stackoverflow.com/questions/20099944/google-maps-v2-to-v3-api-wrapper-working-in-chrome-but-not-in-firefox-ie
7: http://stackoverflow.com/questions/9760727/google-maps-v3-javascript-works-only-in-chrome
8: http://software.programming4.us/forums/t/101675.aspx
9: http://groups.google.com/forum/#!topic/google-maps-api/50z4juKrYEM
11: http://validator.w3.org/check?uri=http%3A%2F%2Fmyworthy.services%2Fsearch.php&charset=%28detect+automatically%29&doctype=Inline&ss=1&outline=1&group=1&No200=1&st=1&user-agent=W3C_Validator%2F1.3+http%3A%2F%2Fvalidator.w3.org%2Fservices
EDITS
This is what it should look like when searching "Southport" and getting results:
! http://drive.google.com/file/d/0B7Rzr6uvzmvAUVBfeWUzNU5FX0k/view?usp=sharing
This is what it should look like when it's not working in both FF and IE:
! http://drive.google.com/file/d/0B7Rzr6uvzmvAdzlGTGhiQldpZmM/view?usp=sharing
Your issue is with window.onload that you use in "search.php". It does not fire in IE10 or Firefox for me, but does fire on Chrome.
I did not find what and where but I'm pretty sure there's something else using window.onload somewhere else in your code or some library you are including.
That won't work, only the last callback you assign to window.onload will actually fire. Read this: Best practice for using window.onload

fetching xml data into a div via ajax and javascript

Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps

Getting an GET-error when nestling JQuery/json-calls: Update

So what i'm trying to do is, by using to services for ip-lookup and geo-lookup, placing a marker on a map at the visitors location.. for now.
This is later to be used as a script, to be placed on pages, to feed a database with user locations from where they are visiting our sites.
Then by reading from the db, liveplacing dots on a map where users are located. A sort of dashboard.
Anyhow..
//
[ Above this i've declared a googlemap, hence the google.maps-references ]
$('#addButton').click(function(){
var ipurl = 'http://jsonip.appspot.com/';
//displays the users ip-adress in json-format
$.getJSON(ipurl,function(json){
var ip = json.ip;
//gets the ip from the above url
var geourl='http://freegeoip.appspot.com/json/' + ip;
//gets location details from the ip in json-format
$.getJSON(geourl,function(json){
var myLatlng = new google.maps.LatLng(json.latitude, json.longitude);
//set the position for the map
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
marker.setMap(map);
});
});
});
When I'm trying to run this, I think I've come to the conclusion that I'm getting a GET-error or something when the script tries to run the second JSON-function. It simply skips it.
Any idea what could cause this?
EDIT:
I've changed the variable for the second JSON-request. And it works. But just when i try it out while it's on my local machine. With Safari.
Tried it in Chrome and Firefox. Both local and on a server. Just wont work.
Red marked text in FireBug:
GET http://example.com/json/ 200 OK 168ms
$(document).ready(function(){
$('#addButton').click(function(){
var ipurl = 'http://jsonip.appspot.com/';
$.getJSON(ipurl,function(json){
var ip = json.ip;
var url='http://freegeoip.appspot.com/json/' + ip;
$('#result').append(
'<p>1: ' + ip + '</p>' +
'<p>2: ' + url + '</p>');
$.getJSON(url,function(json2){
$('#result').append('<p>' + json2.longitude + ' / ' + json2.latitude + '</p>');
});
});
});
});
Try changing the json parameter of the second function. I think you get into trouble when using the same parameter name for both functions.

How can I fix this JavaScript syntax error?

This is puzzling me. I'm using Google Map's Geocoding to find locations. I am attempting to use the example here, which is from Google, and it is just not working for me.
Error:
http://maps.gstatic.com/intl/en_us/mapfiles/159e/maps2.api/main.js
Line 174
var point = new GLatLng(,);
Code:
<script src="http://maps.google.com/maps?file=api&v=2&key='.$config['locations.gMaps.key'].'" type="text/javascript"></script>
<script src="http://www.google.com/uds/api?file=uds.js&v=1.0&key='.$config['locations.gMaps.key'].'" type="text/javascript"></script>
<script src="http://www.google.com/uds/solutions/localsearch/gmlocalsearch.js" type="text/javascript"></script>
<style type="text/css">
#import url("http://www.google.com/uds/css/gsearch.css");
#import url("http://www.google.com/uds/solutions/localsearch/gmlocalsearch.css");
</style>
<script type="text/javascript">
function addListener(element, baseName, handler) {
if (element.addEventListener)
element.addEventListener(baseName, handler, false);
else if (element.attachEvent)
element.attachEvent("on"+baseName,handler);
}
var map'.$num.';
function initialize'.$num.'()
{
if (GBrowserIsCompatible())
{
map'.$num.' = new GMap2(document.getElementById("google_map'.$num.'"),{mapTypes:[G_HYBRID_MAP]});
var point = new GLatLng('.$row->LocationLat.','.$row->LocationLon.');
map'.$num.'.setCenter(new GLatLng('.$row->LocationLat.','.$row->LocationLon.'),4);
var mapControl = new GMapTypeControl();
map'.$num.'.addControl(mapControl);
map'.$num.'.addControl(new GLargeMapControl());
map'.$num.'.addControl(new GOverviewMapControl());
map'.$num.'.enableDoubleClickZoom();
map'.$num.'.enableScrollWheelZoom();
var bounds = new GLatLngBounds;
var myIcon = new GIcon();
myIcon.image = "http://www.google.com/mapfiles/marker.png";
myIcon.iconAnchor = new GPoint((markerImage1.width/2),markerImage1.height);
bounds.extend(point);
setBounds(map'.$num.',bounds);
var address = "' . $address . '";
var geocoder = new GClientGeocoder();
showAddress(address, geocoder);
}
}
function showAddress(address, geocoder) {
geocoder.getLatLng(
address,
function(point) {
if (!point) {
alert(address + " not found");
} else {
map'.$num.'.setCenter(point, 13);
var marker = new GMarker(point);
map'.$num.'.addOverlay(marker);
marker.openInfoWindowHtml(address);
}
}
);
}
function setBounds(map'.$num.',bounds)
{
map'.$num.'.setZoom(15);
map'.$num.'.setCenter(bounds.getCenter());
}
function chargement()
{
markerImage1 = new Image();
markerImage1.src = "http://www.google.com/mapfiles/marker.png";
setTimeout("initialize'.$num.'()", 500);
}
addListener(window, "load", chargement);
</script>
My code is generated by PHP, so when there is an ' that means I'm opening or closing the string that is holding the JavaScript.
Maybe I didn't get it, but
var point = new GLatLng(,);
is not valid javascript
It should be either
var point = new GLatLng(param1, param2);
or
var point = new GLatLng();
or
var point = new GLatLng(null,null);
... depending on what the GLatLng constructor is
This statement:
var point = new GLatLng(,);
Is not correct because there isn't a lat or lng number specified. This is because this statement:
var point = new GLatLng('.$row->LocationLat.','.$row->LocationLon.');
Is incorrect. I'd try something like:
var point = new GLatLng(<?php echo $row->LocationLat . ',' . $row->LocationLon; ?>);
If that doesn't work, then $row->LocationLat or $row->LocationLon are possibly empty.
Problem 1- The function showAddress() is not closed.
Problem 2 - your map object needs to be defined outside of the functions so that showAddress() can access it.
Problem 3 - The references to the map object inside of showAddress() are incorrect
check if the php string you are printing into the html+js exists in the first place. php generates the htm and sends it to the user, for now on it's htm+javascript problem.
it looks like a javascript problem, but you really generated a wrong syntax with php to begin with, because you tried to print something problematic and it printed an empty space.
always be careful of that, be sure of what you print.

Categories

Resources