Need help creating clickable url link for google map's infowindow - javascript

I'm unable to create a clickable url link for Google Map's infowindow. I'm sure it's a syntax error, just not sure where exactly.
Here's a snippet of my code
var marker = new google.maps.Marker({
map: map,
title: eventName,
position: loc
});
var content =
"<strong>" + "#location.venue_name" + "</strong><br>" +
"#location.venue_address" + " " + "#location.city_name" + "<br>" +
"#location.description" + "<br>" +
"#location.url" + "<br>" + //displays url eg. 'www.google.com'
//"More Details<br>"; // map won't show if this line is uncommented
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', (function (marker, content) {
return function () {
infowindow.setContent(content);
infowindow.open(map, marker);
};
})(marker, content));
Thank you in advance

Please try this one:
var content =
"<strong>" + "#location.venue_name" + "</strong><br>" +
"#location.venue_address" + " " + "#location.city_name" + "<br>" +
"#location.description" + "</div>" +
"#location.url" + "<br>" +
"<a href='" + "#location.url" + "' target='_blank'>More Details</a><br>";
Notice I have changed quotes a little bit in the last line. Hope it helps

preferably in one single string :
"<a href='#location.url' target='_blank'>More Details</a><br>"
thats easier for the eyes
pretty sure the #... injections works in longer strings as well

syntax got a bit messy there on content variable.
change your line as follows
<a href='" + "#location.url" + "' target='_blank'>More Details</a><br>"
also take a look at template literals for js which will make you code much more readable with a "`" (backtick)
var content = `<strong>${#location.venue_name}</strong>
<br>
${#location.venue_address} ${#location.city_name} ${#location.url}
<a href='${#location.url}' target='_blank'>More details</a>
`
this way you can avoid a lot of mess trying to build a string. ${} will allow you to put Js variables inside a backticked string.

Related

Error in line of javascript 'missing ) after argument list"

I am trying to pass variables to a javascript function but i have the Javascript Error: 'missing ) after argument list"
html = html + '' + 'Lugar: ' +name.name +' Coordenadas: Lat '+ name.lat +' Lng'+ name.lng+ '<br>';
It doesn't look like I am missing any ')'s.
I see you have found your solution, but here's an alternative anyway, which reduces your string concatenation a little. There's still a far better way of achieving this, but this may help you start to see the benefit of moving away from building HMTL via string concatenation.
<meta charset="UTF-8">
<span id="spanTest"></span>
<script>
// Or whatever your initMap2 function does...
function initMap2(lat, lng, name) {
console.log('Lat: ' + lat);
console.log('Lng: ' + lng);
console.log('Name: ' + name);
}
var spanTest = document.getElementById('spanTest');
var worldLocation = { name:"test", lat:98.5, lng:-88.45 };
var anchor = document.createElement('a');
anchor.href = 'javascript:initMap2(' + worldLocation.lat +', ' + worldLocation.lng + ', \'' + worldLocation.name + '\');';
anchor.innerHTML = 'Name: ' + worldLocation.name + ', Lat: ' + worldLocation.lat + ' Lng: ' + worldLocation.lng;
spanTest.appendChild(anchor);
</script>
I'm assuming your last argument is expected to be a string, but it's resolved to look like a variable. Try this instead:
html = html + '<a href="javascript:initMap2(' + name.lat +','+ name.lng +',\''+ name.name +'\');">' // etc.
When name.name resolves to a string, it'll be wrapped in single quotes as expected. It'll look something like javascript:initMap2(1, 2, 'someString').

How to add pins to the google maps geocode api

I am trying to combine these three things into one.
http://jsfiddle.net/Dansker/hk5fgbzr/3/ (fiddle 1)
http://jsfiddle.net/Dansker/rnrba8so/10/ (fiddle 2)
data.illinois.gov/resource/wsms-teqm.json (data source)
I want to add pins like I did in fiddle 1 two the code I have in fiddle 2. However I need to use the data different data source. The way I made it work in fiddle 1 was with the latitude and longitude. But because I can not do that with the new data source I need to find a new way. That is why I am trying to add it to fiddle one. Will that work? If so how can I do it? If it wont work what would you suggest using the google maps api?
$.getJSON(URL, function(data, textstatus) {
$.each(data, function(i, entry) {
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">' + entry.name_ + " Library" + '</h1>'+ '<hr>' +
'<div id="bodyContent">'+
'<p>' + entry.address + " " + entry.zip + '.<br>' +
'<p>' + '' + entry.website.url + '' + '</p>'+
'<p>' + entry.hours_of_operation + '</p>'+
'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(entry.location.latitude,
entry.location.longitude),
map: map,
title: entry["dba_name"] + "\n" + entry["address"]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
});
});
Since you have 2 callback functions, the correct way to do this is to first finish work for first callback, in this case, downloading the JSON and parse them, also I would store all the entry into entries just so that we can use the data when we add the markers, which is called at the end of the first callback.
about the API access limit, sadly I think you have to use the paid google maps geocoding API, or other services like openStreetmaps.
I also have a jsfiddle setup, hope this help.

Detect event in Google Marker

In my code, how can I get the name of the User that someone clicked on in the marker?
Currently my code has:
function createMarker(point, user, studytopic) {
var marker = new GMarker(point);
var currUser = user;
var html = '<b>' + user + '</b> <br/>' + studytopic + '<br/>' +
' Contact ' + user + '' ;
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
currUser is a global field, however, it's not updated every time I click on a different marker in Google maps.
Basically what I'm looking for is a event to fire when a link (id=contactSBLink) within any marker is clicked. I want it to get the Username(which is a link) to pass the user variable to another function.
I'm not sure what's the best way to go about to get this?
You can pass the user u to the javascript:showContactSB(u). This is an exercise in setting quotes properly:
var u = "'" + user + "'";
var html = '<b>' + user + '</b> <br/>' + studytopic + '<br/>' +
' Contact ' + user + '' ;
Now, you get the user in the click-function:
function showContactSB(user) {
alert("Hi " + user);
}
BTW, I would recommend you to upgrade to Google Maps v3.

Reading text file from external folder via xml path name (Google maps API)

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?

Variable url in json-script

Messing around for days know. Learning javascript and jquery a few weeks, it goes well, but sometimes...
For an mobile app i'm trying to get the coordinates. Showing them on page isn't a problem, but I want them elsewhere.
In the main.js
var getLocation = function() {
var suc = function(p) {
document.getElementById("locatie").innerHTML = "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20";
};
var locFail = function() {
};
navigator.geolocation.getCurrentPosition(suc, locFail);
};
And in the htmlfile
<body onload="getLocation();" >
<p id="locatie">Finding geolocation...</p></ul>
<div id="geolocation">
Bezig met laden. Momentje geduld</div>
<script type="text/javascript">
jQuery(function(){
var script=document.createElement('script');
script.type='text/javascript';
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
$("body").append(script);
});
function processTheseTerraces(jsonData){
var shtml = '';
var results = jsonData.results;
if(results){
$.each(results, function(index,value){
shtml += "<li class='store'><a class='noeffect' href='#'><span class='image' style='background-image: url(pics/terras1.jpg)'></span><span class='comment'>" + value.address + "</span><span class='name'>" + value.building_name + "</span><span class='stars5'></span><span class='starcomment'>132 Beoordelingen</span><span class='arrow'></span></a></li>";
});
$("#geolocation").html( shtml );
}
}
</script>
Now I want the coordinates passing through json and load the data. I thought to change
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
in
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20";
But that doesn't work. Anyone suggestions how I can solve this.
This: http://www.192.168.1.111 is just a wrong URL. I guess you need just this: http://192.168.1.111
Geolocation can take a long time (multiple seconds). It is an asynchronous request which means that the other javascript code may execute before the geolocation has grabbed the address. The solution is to put any code or function calls that use the location inside the callback function on the navigator.geolocation.getCurrentPosition
The JQuery is building the URL before the lat and lng have been defined.
onload="getLocation();" tells that when the document is loaded call getLocation function and inside this function you set the innerHTML of <P id="locatie"> TAG as: http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20
So problems are:
If you make a script tag and assign source then browser fetch the source data but writing an url on inner html of a <p> tag won't do this and it doesn't make sense.
Code fragment below is loaded before the document is loaded but i guess you do not want this:
jQuery(function(){
var script=document.createElement('script');
script.type='text/javascript';
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
$("body").append(script);
});
If you want: script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20"; then you have to define p.coords first and before calling this otherwise p.coords is undefined.
Solution i am not sure what you exactly asking so could not answer. Do you want to assign inner HTML of the #locatie element or do you want to load customized script as tag?
Either ways, you have to make an ajax call to server which maybe like this:
$.ajax({
url: "http://www.192.168.1.111/tools/gpslocation.php",
data: "lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20",
success: function(Result){
// use Result variable in came from the success function.
document.getElementById("Your_ID_Goes_Here").innerHTML = "do_Something";
}
});

Categories

Resources