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.
Related
I want to get the the users current location address(city, street etc) on click event.
I have tried html5 geolocation and tried to console the data. on button click i am checking geo location is supported by creating alert box, and its executes succesfully, But its not printing any values in the console.
HTML
<div id="navbar"><span> Geolocation API</span></div>
<div id="wrapper">
<button id="location-button">Get User Location</button>
<div id="output"></div>
My script
<script>
$('#location-button').click(function(){
if (navigator.geolocation) {
alert("it is supported");
navigator.geolocation.getCurrentPosition(function(position){
console.log(position);
$.get( "http://maps.googleapis.com/maps/api/geocode/json?latlng="+ position.coords.latitude + "," + position.coords.longitude +"&sensor=false", function(data) {
console.log(data);
})
var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + position.coords.latitude + "," + position.coords.longitude + "&zoom=13&size=800x400&sensor=false";
$('#output').html(img);
});
}
else
{
console.log("geo location is not supported")
}
});
</script>
I want to get the full address of the users location.
You may visit this jsfiddle sample that demonstrates your use case.
Kindly note that it is not recommended to use web service in the client side, as web service requests are recommended to be used for server side requests.
As you can see below, what I used is a Geocoder Service instead of the Web Service Geocoding
geocoder.geocode( { 'location': pos}, function(results, status, infowindow) {
if (status == 'OK') {
console.log(results[0].formatted_address);
infoWindow.setContent('Location found: '+ results[0].formatted_address);
infoWindow.setPosition(pos);
infoWindow.open(map);
} else {
console.log('Geocode was not successful for the following reason: ' + status);
}
});
you simply can't! Geolocation use triangulation or GPS from the mobile and you'll get get longitude and latitude values or even the IP and you'll get nearest distributor device(haven't right word in english).
Obviously for geolocation the user have to authorize it too.
So if you want address the simpliest is to ask by a form. You can use a map related with longit/latitude matching but it'll be a pain and waste to do because you've to use all maps and places on earth related to use it that way.
EDIT: Just finished up the project. New link is up here! http://codepen.io/myleschuahiock/full/pyoZge/
I'm in the process of making a Weather Widget App for my Free Code Camp. Everything except the "city" is a static placeholder. I'm using the Open Weather Api, which makes us to a latitude and longitude. For debugging purposes, I placed the longitude and latitude of my area underneath the time placeholder.
My problem is that when I statically input the lat and lon on my API link, it works just fine. It returns "Mandaluyong City", a nearby city where I live:
http://api.openweathermap.org/data/2.5/weather?lat=14.603814400000001&lon=121.04907589999999&id=524901&APPID=ca8c2c7970a09dc296d9b3cfc4d06940
But when I do this, where I dynamically add mylatitude and mylongitude, to complete the API link:
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
I always get "Moscow" as my city.
Please take a closer look at my Javascript/JQuery code here!
http://codepen.io/myleschuahiock/pen/zqYzWm?editors=0010
Thank you very much! Much appreciated!
Easy solution for you.
Move the $.getJSON() into your if condition, why attempt to query the weather if the client blocks the location?
As Jaromanda X has pointed out:
navigator.geolocation.getCurrentPosition is asynchronous. So, you're calling $.getJSON before the location is actually determined.
$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
$('.geo').html(position.coords.latitude+ " " +position.coords.longitude);
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat="+position.coords.latitude+"&lon="+position.coords.longitude+"&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
});
}else{
$(".geo").html("Please turn on Geolocator on Browser.")
}
});
I hope this helps. Happy coding!
Added
getName(mylatitude, mylongitude);
and changed
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
to
function getName(mylatitude, mylongitude){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + mylatitude + "&lon=" + mylongitude + "&id=524901&appid=ca8c2c7970a09dc296d9b3cfc4d06940", function(json) {
$('.city').html(json.name);
});
}
http://codepen.io/anon/pen/Yqzvbd?editors=0010
You can use third-party IP API that provides the name of the city. With use jQuery function $.getJSON()
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather';
var APPID = 'APPID';
var ipAPI = 'http://ip-api.com/json/';
$.getJSON(ipAPI).done(function(location) {
$('.geo').html(location.lat + " " + location.lon);
$('.city').html(location.city);
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
APPID: APPID
}).done(function(weather) {
$('#temperature').html(weather.main.temp - 273.15);
})
})
OpenWeatherMap provides the temperature in Kelvin on this I did weather.main.temp - 273.15 to get Celsius
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
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/
I'm building a webpage based around the Google maps API, per client request. I'm pulling data from a database into xml that is then linked to markers on the map (part of the data for each record is latitude and longitude, which sets the marker). When the user clicks on the marker, they see content relating to that place in a page div (the content is a title, photo, audio file, and transcript of the audio file).
Everything is working except... I can't figure out how to display the transcript, which is a text file. The xml node contains the full pathname, and the folder with the actual file is stored on the server. I know how to do this with php, but can't rename my file with a php extension because the Google Maps API won't allow it (the map disappears).
Here is the relevant part of the code:
downloadUrl("xmlTest.php", function(data)
{
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("Sound_xcrpt");
for (var i = 0; i < markers.length; i++)
{
var title = markers[i].getAttribute("se_title");
var desc = markers[i].getAttribute("se_desc");
var type = markers[i].getAttribute("se_contrib");
var ph_title = markers[i].getAttribute("ph_title");
var ph_web = markers[i].getAttribute("ph_web");
var ph_thumb = markers[i].getAttribute("ph_thumb");
var trans_ex = markers[i].getAttribute("trans_xcrpt");
var audio = markers[i].getAttribute("se_audio_file");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("se_lat")),
parseFloat(markers[i].getAttribute("se_lng")));
var html =
'<head>' +
'<link rel="stylesheet" href="infoStyle.css" type="text/css">' +
'</head>' +
'<html>' +
'<body>' +
'<header id="title">' + title + '</header>' +
'</section id="desc">' + desc +
'</section>' +
'<section id="photo_thumb">' +
'<img src="'+ph_thumb+'"/>' +
'</section>' +
'</body>' +
'</html>';
var winHtml =
'<head>' +
'<link rel="stylesheet" href="styleWin2.css">' +
'</head>' +
'<body>' +
'<header id="title2">' + ph_title + '</header>' +
'<div class="photos">' +
'<img src="'+ph_web+'"/>' +
'</div>' +
'<div class="trans">' +trans_ex+
'</div>' +
'<footer id="audio">' +
'<audio autoplay="autoplay" controls="controls">' +
'<source src="'+audio+'">' +
'</audio>' +
'</footer>' +
'</body>';
var icon = customIcons[type] || {};
var marker = new google.maps.Marker(
{
map: map,
position: point,
icon: icon.icon,
animation: google.maps.Animation.DROP,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
contentBox(marker, map, content, winHtml, infoWindow);
}
});
}
"trans_ex" holds the path name array. The way the code is set up above, it displays the actual path name in the div, not the content of the text file to which that path name points.
Is there a javascript (or jquery) method to do this? I know it's tricky because I've got a server-side request in here.
Thanks for your help, Cheryl
What you need is to call AJAX to get the transcript from the server and append it to the DIV once the marker is clicked. XMLHttpRequest object in your second comment is the foundation of AJAX and jquery has a very nice abstraction to do that via jQuery.ajax() (http://api.jquery.com/jQuery.ajax/).
It basically hides the complexities in your second comments and let you deal with what you want to do once the response comes in. In your case, you would want the DIV for the transcript to be populated with the response from the transcript.
In fact, jQuery made further abstraction by providing load() function (http://api.jquery.com/load/). You need to call this function upon click event for the marker and providing it with the right path for the transcript
Are you wanting to display the contents of the text file? The guy at the following URL needed to read the contents of a text file as well. Maybe this will help?
jquery - Read a text file?