url.content not loading image javascript and asp.net mvc - javascript

I have my javascript in my view and I am trying to load an image from my database into an info window for my google maps but the image does not load.
Javascript code in view:
$.get("#Url.Action("GetMarkers","Donator")", function (json, status) {
//Global infoWindow object that will be reused by all markers
var infoWindow = new google.maps.InfoWindow();
var marker, data;
//Loop through the json data
for (var i = 0; i < json.length; i++) {
data = json[i];
var latLng = new google.maps.LatLng(data.Latitude, data.Longitude)
//Creating marker and putting it on the map
marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.NpoName + ' says Click Me!'
});
// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
(function (marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function (e) {
var imageUrl = '<%=Url.Content(' + data.VerificationIcon + ')%>';
infoWindow.setContent('<h3 class="info-window-title">' + data.NpoName + '</h3>' + '<hr />' + '<p>Npo type: ' + data.NpoType + '</p>' + '<p>' + data.VerificationStatus + '<img src="' + imageUrl + '" alt="verification icon" class="verification-icon" />' + '</p>' + 'Click here to donate!');
infoWindow.open(map, marker);
});
})(marker, data);
};
});
Code in controller:
public JsonResult GetMarkers()
{
//Disable lazy loading
db.Configuration.ProxyCreationEnabled = false;
//Map marker section
var DynamicMapMarkers = db.tblNpo.Include(zz => zz.tblVerification).Include(xx => xx.tblNpo_Type);
//Set map marker values
foreach (var item in DynamicMapMarkers)
{
DonatorUserViewModel MapMarkers = new DonatorUserViewModel();
MapMarkers.NpoID = item.npo_id;
MapMarkers.NpoName = item.npo_name;
MapMarkers.NpoType = item.tblNpo_Type.description;
MapMarkers.VerificationStatus = item.tblVerification.description;
MapMarkers.VerificationIcon = item.tblVerification.verification_icon;
MapMarkers.Longitude = Convert.ToDouble(item.longitude);
MapMarkers.Latitude = Convert.ToDouble(item.latitude);
MapMarkerList.Add(MapMarkers);
}
var json = MapMarkerList;
return Json(json, JsonRequestBehavior.AllowGet);
}
Main focus area from the code above:
var imageUrl = '<%=Url.Content(' + data.VerificationIcon + ')%>';
infoWindow.setContent('<h3 class="info-window-title">' + data.NpoName + '</h3>' + '<hr />' + '<p>Npo type: ' + data.NpoType + '</p>' + '<p>' + data.VerificationStatus + '<img src="' + imageUrl + '" alt="verification icon" class="verification-icon" />' + '</p>' + 'Click here to donate!');
The format of the way the image is stored in the database ~/Images/DbImages/verified.png
I am not sure why the image isn't loading, or how to work around it. Any help would be appreciated.

Related

Trying to add button in googlemap infoWindow

I'm trying to add a button in googlemap infoWindow but I'm beginner in javascript and I have spent weeks on this and still not working... So I hope one of you will be able to help me.
To explain you a litle bit... I get markers from a bdd to display them on a map. Then on marker click, a infoWindow opens with all info marker on it.
This is all working perfectly but then is when I don't get it.
I have added a submit button to each infoWindow markers and I would like an action on submit button click (save to database). But the button is not responding at all...
I removed all the code containing the save function to keep it all clear as there is a alert("click") to test the button...
<script type="text/javascript">
var bounds;
var markers = [];
var markerCount = 0;
function initialize(){
bounds = new google.maps.LatLngBounds();
var myLatLng = new google.maps.LatLng(46.775090, 2.507969);
var mapOptions={
zoom: 6,
center: myLatLng,
maxZoom: 11,
},
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
setMarkers(map,marker);
const geocoder = new google.maps.Geocoder();
document.getElementById("submit").addEventListener("click", () => {
geocodeAddress(geocoder, map);
});
}
function setMarkers(map,locations){
for(var i=0; i<locations.length; i++){
var station = locations[i];
var myLatLng = new google.maps.LatLng(station['marker_latitude'], station['marker_longitude']);
var infoWindow = new google.maps.InfoWindow();
var image = 'https://marchad.fr/wp-includes/images/marchad.png';
var description = station['marker_text'];
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: station['marker_ville'],
id: station['marker_id']
});
(function(marker, i){
google.maps.event.addListener(marker, "click",function(){
var station = locations[i];
var mId = station['marker_id']; //description input field value
var contentString = ("<div id='infoWindow"+station['marker_id']+">"
+"<p class='texte'><strong>"+station['marker_text']+"</strong><p>"
+"<p class='texte'>Ce staliad est géré par un "+station['marker_user_type']+"<p>"
+"<p class='texte'><strong>Adresse : </strong>"+station['marker_adresse']+"<p>"
+"<p class='texte'><strong>Jour de permanence : </strong>"+station['marker_day']+"<p>"
+"<p class='texte'><strong>Dépôts : </strong>de "+station['marker_depot_start_time']+" à "+station['marker_depot_end_time']+"<p>"
+"<p class='texte'><strong>Retraits : </strong>de "+station['marker_start_time']+" à "+station['marker_end_time']+"<p>"
+"<p class='texte'><strong>Téléphone : </strong>"+station['marker_user_contact']+"<p>"
+"<p class='texte'><strong>Mail : </strong>"+station['marker_contact_mail']+"<p>"
+"<p class='texte'><strong>Commentaire : </strong>"+station['marker_commentaire']+"<p>"
+'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker'+station['marker_id']+'">'
+'<input id="idInput'+station['marker_id']+'" type="hidden" name="marker-id" class="marker-id'+station['marker_id']+'" value='+station['marker_id']+' />'+station['marker_id']+'</input>'
+'</form>'
+'<input id="inputButton'+station['marker_id']+'" type="button" id="save-marker'+station['marker_id']+'" name="save-marker" class="save-marker'+station['marker_id']+'" data-id="'+station['marker_id']+'" value="M\'inscrire" />'
+'<div id="test'+station['marker_id']+'">'+vendorId+'</div>'
+'<span class="info-content'+station['marker_id']+'">'
+'<h1 class="marker-heading"></h1>'
+'</span>'
+"</div>"
);
infoWindow.close();
infoWindow.setContent(contentString);
infoWindow.open(map,this);
var class_name_removeBtn = 'remove-marker'+station['marker_id'];
var class_name_saveBtn = 'save-marker'+station['marker_id'];
var removeBtn = document.getElementsByClassName(class_name_removeBtn);
var saveBtn = document.getElementsByClassName(class_name_saveBtn);
console.log(removeBtn);
console.log(saveBtn);
//add click listner to save marker button
google.maps.event.addDomListener(saveBtn, "click", function(event) {
var class_name_mReplace = 'info-content'+station['marker_id'];
var class_name_mName = 'marker-id'+station['marker_id'];
var mReplace = document.getElementsByClassName(class_name_mReplace); //html to be replaced after success
var mName = document.getElementsByClassName(class_name_mName); //name input field value
var mId = station['marker_id'];
var vId = vendorId;
console.log(mReplace);
console.log(mName);
console.log(mId);
console.log(vId);
if(mId !=='')
{
alert("click");
save_marker( mName, mId, mReplace,vId); //call save marker function
}else{
alert("Something went wrong. Please contact admin");
}
});
if(typeof removeBtn !== 'undefined') //continue only when save button is present
{
google.maps.event.addDomListener(removeBtn, "click", function(event) {
var class_name_mName = 'marker-id'+station['marker_id'];
var mName = document.getElementsByClassName(class_name_mName); //name input field value
var vId = vendorId;
remove_marker(mName,vId);
});
}
});
})(marker, i);
}
}
</script>
Your first problem is the saveBtn is not part of the DOM until the InfoWindow has been opened as you are adding as a string in the InfoWindow content.
Relate questions:
using addDomListener with googlemaps not working
Turn off google map's infowindow.open(map) asynchronous behaviour
Adding Event Listener on button - Javascript
The second problem is that document.getElementsByClassName(class_name_saveBtn); returns an array. Instead of:
document.getElementsByClassName(class_name_saveBtn);
for a single marker, you need:
document.getElementsByClassName(class_name_saveBtn)[0];
for multiple markers/infowindows (get the last one created):
var removeBtn = document.getElementsByClassName(class_name_removeBtn);
removeBtn = removeBtn[removeBtn.length-1];
var saveBtn = document.getElementsByClassName(class_name_saveBtn);
saveBtn = saveBtn[saveBtn.length-1];
proof of concept fiddle
code snippet:
var bounds;
var markers = [];
var markerCount = 0;
/* var marker = [{
marker_latitude: 47.394144,
marker_longitude: 0.68484,
marker_id: 1
}] */
var marker = [{"marker_id":"6","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"5","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Toulouse","marker_departement":"31","marker_region":"0","marker_longitude":"1.434917","marker_latitude":"43.573085","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Casino Barri\u00e8re","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"7","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"6","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Toulouse","marker_departement":"31","marker_region":"0","marker_longitude":"1.447856","marker_latitude":"43.604573","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Cinema Gaumont Wilson","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"8","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"6","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Lab\u00e8ge","marker_departement":"31","marker_region":"0","marker_longitude":"1.511496","marker_latitude":"43.53992","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Cinema Gaumont Lab\u00e8ge","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"9","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"6","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Blagnac","marker_departement":"31","marker_region":"0","marker_longitude":"1.373341","marker_latitude":"43.644029","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Cinema Mega CGR Blagnac","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"10","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"4","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Toulouse","marker_departement":"31","marker_region":"0","marker_longitude":"1.435198","marker_latitude":"43.62186","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Bowling Minimes\r\n108 Bis Avenue des Minimes, 31200 Toulouse \u200e\r\n05 61 47 95 60","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"11","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"4","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Montaudran","marker_departement":"31","marker_region":"0","marker_longitude":"1.496152","marker_latitude":"43.568863","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Bowling Montaudran Impasse Louise Lab\u00e9 31400 Toulouse 05 61 20 20 70","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"12","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"4","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Colomiers","marker_departement":"31","marker_region":"0","marker_longitude":"1.304691","marker_latitude":"43.609902","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"Bowling Stadium Colomiers\r\n29 Chemin du Loudet\r\n33770 Colomiers\r\n05 34 36 42 50","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"13","marker_user_id":"0","marker_user_type":"","marker_user_stal":null,"marker_categorie":"10","marker_adresse":"","marker_numero_voie":"","marker_voie":"","marker_zip":"","marker_ville":"Plaisance-du-Touch","marker_departement":"31","marker_region":"0","marker_longitude":"1.260248","marker_latitude":"43.55854","marker_day":"","marker_depot_start_time":"00:00:00","marker_depot_end_time":"00:00:00","marker_start_time":"00:00:00","marker_end_time":"00:00:00","marker_text":"African Safari\r\n41 Rue des Landes\r\n31830 Plaisance-du-Touch\r\n05 61 86 45 03","marker_user_contact":"","marker_contact_mail":"","marker_enable_contact_telephone":"","marker_enable_contact_mail":"","marker_commentaire":null,"marker_actif":"Oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"29","marker_user_id":"2","marker_user_type":"marchand","marker_user_stal":"Aux petits l\u00e9gumes","marker_categorie":"test","marker_adresse":"12 Rue du Bocage, Tr\u00e9gueux, France","marker_numero_voie":"12","marker_voie":"Rue du Bocage","marker_zip":"22950","marker_ville":"Tr\u00e9gueux","marker_departement":"C\u00f4tes-d'Armor","marker_region":"Bretagne","marker_longitude":"-2.7515737","marker_latitude":"48.4831891","marker_day":"Lundi","marker_depot_start_time":"09:00:00","marker_depot_end_time":"12:00:00","marker_start_time":"12:00:00","marker_end_time":"18:46:00","marker_text":"Aux petits l\u00e9gumes","marker_user_contact":"0783312456","marker_contact_mail":"nattydreadnatty#live.fr","marker_enable_contact_telephone":"yes","marker_enable_contact_mail":"yes","marker_commentaire":"test test test test test testing out","marker_actif":"oui","id":null,"mark_id":null,"user_id":null,"user_actif":null},{"marker_id":"30","marker_user_id":"3","marker_user_type":"marchand","marker_user_stal":"Poivrons et compagnie","marker_categorie":"","marker_adresse":"12t Rue du Vau Hello, 22360 Langueux, France","marker_numero_voie":"12","marker_voie":"Rue du Vau Hello","marker_zip":"22360","marker_ville":"Langueux","marker_departement":"C\u00f4tes-d'Armor","marker_region":"Bretagne","marker_longitude":"-2.7262882","marker_latitude":"48.50448799999999","marker_day":"Vendredi","marker_depot_start_time":"08:00:00","marker_depot_end_time":"10:00:00","marker_start_time":"10:00:00","marker_end_time":"18:00:00","marker_text":"Poivrons et compagnie","marker_user_contact":"","marker_contact_mail":"lucbinard4#gmail.com","marker_enable_contact_telephone":"yes","marker_enable_contact_mail":"yes","marker_commentaire":"","marker_actif":"oui","id":null,"mark_id":null,"user_id":null,"user_actif":null}];
var vendorId = "vendorId";
function initialize() {
bounds = new google.maps.LatLngBounds();
var myLatLng = new google.maps.LatLng(46.775090, 2.507969);
var mapOptions = {
zoom: 6,
center: myLatLng,
maxZoom: 11,
},
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
setMarkers(map, marker);
const geocoder = new google.maps.Geocoder();
document.getElementById("submit").addEventListener("click", () => {
geocodeAddress(geocoder, map);
});
}
function setMarkers(map, locations) {
for (var i = 0; i < locations.length; i++) {
var station = locations[i];
var myLatLng = new google.maps.LatLng(station['marker_latitude'], station['marker_longitude']);
var infoWindow = new google.maps.InfoWindow();
var image = 'https://marchad.fr/wp-includes/images/marchad.png';
var description = station['marker_text'];
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: station['marker_ville'],
id: station['marker_id']
});
(function(marker, i) {
google.maps.event.addListener(marker, "click", function() {
var station = locations[i];
var mId = station['marker_id']; //description input field value
var contentString = ("<div id='infoWindow" + station['marker_id'] + ">" +
"<p class='texte'><strong>" + station['marker_text'] + "</strong><p>" +
"<p class='texte'>Ce staliad est géré par un " + station['marker_user_type'] + "<p>" +
"<p class='texte'><strong>Adresse : </strong>" + station['marker_adresse'] + "<p>" +
"<p class='texte'><strong>Jour de permanence : </strong>" + station['marker_day'] + "<p>" +
"<p class='texte'><strong>Dépôts : </strong>de " + station['marker_depot_start_time'] + " à " + station['marker_depot_end_time'] + "<p>" +
"<p class='texte'><strong>Retraits : </strong>de " + station['marker_start_time'] + " à " + station['marker_end_time'] + "<p>" +
"<p class='texte'><strong>Téléphone : </strong>" + station['marker_user_contact'] + "<p>" +
"<p class='texte'><strong>Mail : </strong>" + station['marker_contact_mail'] + "<p>" +
"<p class='texte'><strong>Commentaire : </strong>" + station['marker_commentaire'] + "<p>" +
'<form action="ajax-save.php" method="POST" name="SaveMarker" id="SaveMarker' + station['marker_id'] + '">' +
'<input id="idInput' + station['marker_id'] + '" type="hidden" name="marker-id" class="marker-id' + station['marker_id'] + '" value=' + station['marker_id'] + ' />' + station['marker_id'] + '</input>' +
'</form>' +
'<input id="inputButton' + station['marker_id'] + '" type="button" id="save-marker' + station['marker_id'] + '" name="save-marker" class="save-marker' + station['marker_id'] + '" data-id="' + station['marker_id'] + '" value="M\'inscrire" />' +
'<div id="test' + station['marker_id'] + '">' + vendorId + '</div>' +
'<span class="info-content' + station['marker_id'] + '">' +
'<h1 class="marker-heading"></h1>' +
'</span>' +
"</div>"
);
infoWindow.close();
infoWindow.setContent(contentString);
infoWindow.open(map, this);
var class_name_removeBtn = 'remove-marker' + station['marker_id'];
var class_name_saveBtn = 'save-marker' + station['marker_id'];
google.maps.event.addListenerOnce(infoWindow,'domready', function() {
var removeBtn = document.getElementsByClassName(class_name_removeBtn);
removeBtn = removeBtn[removeBtn.length-1];
var saveBtn = document.getElementsByClassName(class_name_saveBtn);
saveBtn = saveBtn[saveBtn.length-1];
console.log(removeBtn);
console.log(saveBtn);
//add click listner to save marker button
google.maps.event.addDomListener(saveBtn, "click", function(event) {
var class_name_mReplace = 'info-content' + station['marker_id'];
var class_name_mName = 'marker-id' + station['marker_id'];
var mReplace = document.getElementsByClassName(class_name_mReplace); //html to be replaced after success
var mName = document.getElementsByClassName(class_name_mName); //name input field value
var mId = station['marker_id'];
var vId = vendorId;
console.log(mReplace);
console.log(mName);
console.log(mId);
console.log(vId);
if (mId !== '') {
alert("click");
save_marker(mName, mId, mReplace, vId); //call save marker function
} else {
alert("Something went wrong. Please contact admin");
}
});
if (typeof removeBtn !== 'undefined') //continue only when save button is present
{
google.maps.event.addDomListener(removeBtn, "click", function(event) {
var class_name_mName = 'marker-id' + station['marker_id'];
var mName = document.getElementsByClassName(class_name_mName); //name input field value
var vId = vendorId;
remove_marker(mName, vId);
});
}
})
});
})(marker, i);
}
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map-canvas {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<!DOCTYPE html>
<html>
<head>
<title>Simple Map</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<input id="submit" type="button" value="submit" />
<div id="map-canvas"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initialize&libraries=&v=weekly" async></script>
</body>
</html>
Mine works like this.. detect click event within info window
google.maps.event.addListener(infowindow, 'domready', function() {
$('.classname').click(function(){
// code
});

Maximum call stack size exceeded with using google maps and jQuery

Do you know why I get Maximum call stack size exceeded if I insert a code inside a function and execute it.
$(function() {
function loadContent() {
$.getJSON("js/data.json").done(function(data) {
var content = '';
$.each(data, function(i, item) {
content += '<div class="item" id="' + item.id + '" data-lat="' + item.latitude + '" data-lng="' + item.longitude + '" style="background-image: url(img/' + item.photo + ');"><div class="item__wrapper"><h2 class="item__title">' + item.title + '</h2><p class="item__content">' + item.description + '</p><span class="lat"><i class="fa fa-location-arrow"></i> ' + item.latitude + ' N, </span><span class="long">' + item.longitude + ' E</span></div></div>';
var latLng = new google.maps.LatLng(item.latitude, item.longitude);
var marker = new google.maps.Marker({
position: latLng
});
marker.setMap(map);
});
$('#sidebar').html(content);
$('.item').on("click", function() {
$(this).toggleClass("item--expanded").siblings().removeClass("item--expanded");
});
}).fail(function() {
var content = '<p>Błąd wczytywania danych!</p>';
$('#sidebar').html(content);
});
}
loadContent();
});
If I don't use function loadContent() It works fine. I've read it Maximum call stack size exceeded error but I don't execute the loop inside loop.
Edit: The problem is cause by this code:
<script>
var placeList = document.getElementById("sidebar");
placeList.addEventListener("click", getPlace, false);
function getPlace(ev) {
if (ev.target !== ev.currentTarget) {
clickedItem = ev.target.id;
var getItem = document.getElementById(clickedItem);
var lat = getItem.dataset.lat;
var lng = getItem.dataset.lng;
}
var center = new google.maps.LatLng(lat, lng);
map.panTo(center);
map.setZoom(13);
}
</script>
But still don't know why!

Marker click event always opens to the last pushed infowindow

I have a json object infoCentros which I use to construct the map, like this:
for ( var i = 0; i < infoCentros.length; i++ ) {
var centro = infoCentros[i];
var lat = centro.cordenadas.lat;
var lon = centro.cordenadas.long;
if (lat && lon) {
c++;
latlon = new google.maps.LatLng(lat, lon);
var moptions = {
position: latlon,
map: $project.gmap
}
moptions.icon = theme_uri + '/images/marker.png';
var marker = new google.maps.Marker(moptions);
$project.mapMarkers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
$project.mapInfoWindow.setContent(
'<div class="sescam-info-window">' +
'<h3>' + centro.nombre + '</h3>' +
'<p>' + centro.lugar + '</h3>' +
'<p>Coordinador</p>' +
'<p>' + centro.coordinador.nombre + '</p>' +
'<p>' + centro.coordinador.email + '</p>' +
'<p>Responsable</p>' +
'<p>' + centro.responsable.nombre + '</p>' +
'<p>' + centro.responsable.email + '</p>'
+ '</div>'
);
$project.mapInfoWindow.open($project.gmap, marker);
});
$project.mapBounds.extend(latlon);
}
}
It seems to work fine, but if I have 5 markers, It doesn't matter which one I click, the infowindow always corresponds to the last item (position and content),
Any idea what am I missing? I thought that passing marker to the addListener would Do the trick..
Problem is with third argument of google.maps.event.addListener. That anonymous function contains the variable from the parent scope which when evaluated with marker click will always take the last value assigned. Look for closure for more details. However you may able to get the desired behaviour by using "bind" feature of javascript function prototype in below manner:
//inside for loop
google.maps.event.addListener(marker, 'click', handleMarkerClick.bind(undefined, marker, i));
//other codes if any...
defining handleClick
function handleMarkerClick(marker, index) {
if (typeof infowindow === 'undefined') {
infowindow = new google.maps.InfoWindow({});
}
var data = infoCentros[index]//helpful data
//create content with dynamic data
infowindow.setContent("dynamic content");
infowindow.open(marker.getMap(), marker);//modify as per your requirement
}
Duncan is right, he means you have to attach the listener outside of your for loop. It's not specific to Google Maps, it's how javascript works. Try searching for "javascript closures for loop" or visit this link - Closures in Javascript for a simple explanation.

Dropdown menu in google maps info window

I have a dropdown menu that I want to put inside a google maps infowindow. The menu is populated with contents from an array. When I position the menu outside the info window it works fine but when I try and put it inside the infowindow it breaks. The end goal is to get a form inside the info window so when I submit the form I can process the form data and return the directions to the marker. I have attached the code below and the problematic line is denoted by ** and thanks in advance for all your help.
Infowindow code:
google.maps.event.addListener(marker, 'click', function () {
service.getDetails(request, function (place, status) {
var locationofplace = place.geometry.location;
var markerlocation = marker.getPosition();
var markerlat = markerlocation.lat();
var markerlng = markerlocation.lng();
if (status == google.maps.places.PlacesServiceStatus.OK) {
var contentStr = '<h5>' + place.name + '</h5><p>' + place.formatted_address;
if (!!place.formatted_phone_number) contentStr += '<br>' + place.formatted_phone_number;
if (!!place.website) contentStr += '<br><a target="_blank" href="' + place.website + '">' + place.website + '</a>'; * * contentStr += '<form><select id="selectNumber"><option>Change Address</option></select></form>'; * *
contentStr += '<br>Get Directions';
contentStr += '<br>' + place.types + '</p>';
infowindow.setContent(contentStr);
infowindow.open(map, marker);
} else {
var contentStr = "<h5>No Result, status=" + status + "</h5>";
infowindow.setContent(contentStr);
infowindow.open(map, marker);
}
});
});
add data to menu code:
window.addEvent('load', function () {
var select = document.getElementById("selectNumber");
for (var i = 0; i < addresses.length; i++) {
var opt = addresses[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
});
use the domready-event of the infowindow instead of the load-event of the window to manipulate the dropdown(the dropdown hasn't been injected into the document before the domready-event)

how to make a clickable phone number in iphone application by using javascript and html5 applied mysql database?

and I know that 1-801-555-1212 will make this certain number be clickable. I tested it and it works fine.
My question is if I do have a variable phone which will call from database via mysql, how can I make this variable be clickable? I've tried a lot of way but none of them work.
I used the following link to create a store locator page
http://code.google.com/apis/maps/articles/phpsqlsearch.html
and my original code is here.
<!DOCTYPE html>
Store Locate
<script src="http://maps.google.com/maps?file=api&v=2&sensor=true&key=ABQIAAAAtwc3xGzBndDAUOSllG2AkxTnNPa_SyQGEldLwhmK8Cfx_H4lPRTZuzWKU2EDVO1MyUD3Ym_0fNuEiw" type="text/javascript"></script>
<script src="jquery-1.5.2.min.js"></script>
<script>
// One-shot position request.
navigator.geolocation.getCurrentPosition(showMap);
function showMap(position) {
// Show a map centered at (position.coords.latitude, position.coords.longitude).
}
map.setCenter(new google.maps.LatLng(position.coords.latitude,
position.coords.longitude), 13);
<script type="text/javascript">
//<![CDATA[
var map;
var geocoder;
function load() {
if (GBrowserIsCompatible()) {
geocoder = new GClientGeocoder();
map = new GMap2(document.getElementById('map'));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(40, -100), 4);
}
}
function searchLocations() {
var address = document.getElementById('addressInput').value;
geocoder.getLatLng(address, function(latlng) {
if (!latlng) {
alert(address + ' not found');
} else {
searchLocationsNear(latlng);
}
});
}
function searchLocationsNear(center) {
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
GDownloadUrl(searchUrl, function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
var sidebar = document.getElementById('sidebar');
sidebar.innerHTML = '';
if (markers.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setCenter(new GLatLng(40, -100), 4);
return;
}
var bounds = new GLatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var distance = parseFloat(markers[i].getAttribute('distance'));
var phone = markers[i].getAttribute('phone');
var url = markers[i].getAttribute('url');
var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
parseFloat(markers[i].getAttribute('lng')));
var marker = createMarker(point, name, address, phone, url);
map.addOverlay(marker);
var sidebarEntry = createSidebarEntry(marker, name, address, distance, phone, url);
sidebar.appendChild(sidebarEntry);
bounds.extend(point);
}
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
});
}
function createMarker(point, name, address, phone, url) {
var marker = new GMarker(point);
var html = '<b>' + name + '</b> <br/>' + address + '</b> <br/>' + phone + '</b> <br/>' + url + '</b> <br/>'
GEvent.addListener(marker, 'click', function() {
marker.openInfoWindowHtml(html);
});
return marker;
}
function createSidebarEntry(marker, name, address, distance, phone, url) {
var div = document.createElement('div');
var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address + '</b> <br/>' + phone + '</b> <br/>' + url;
div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
GEvent.addDomListener(div, 'click', function() {
GEvent.trigger(marker, 'click');
});
GEvent.addDomListener(div, 'mouseover', function() {
div.style.backgroundColor = '#eee';
});
GEvent.addDomListener(div, 'mouseout', function() {
div.style.backgroundColor = '#fff';
});
return div;
}
//]]>
</script>
I add a variable phone which will call from mysql. and my question is how can I make it clickable?...I tried to modify following code in many ways
function createSidebarEntry(marker, name, address, distance, phone, url) {
var div = document.createElement('div');
var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address + '</b> <br/>' + phone + '</b> <br/>' + url;
but I always just got code error.
anyone can help me??
thanks
You can surround the phone number by a "a" tag with a href="tel:{PHONE NUMBER}"
How to mark-up phone numbers?

Categories