I have searched all over this site to find an answer with no luck. I have an array of lat, and lng markers and I'd like to open an info window based on the array index. I got it to work by replacing markers with variables instead of an array list, but I want to keep my code DRY. Here is my code:
function initMap() {
var locations = [
["blairCountyPA", 40.453132, -78.384223],
["scrantonPA", 41.408969, -75.662412],
["warringtonTownshipPA", 40.250319, -75.166212],
["lancasterCountyPA", 40.046657, -76.178374],
["berkeleyCountyWV", 39.488560, -78.065193],
["bowieMD", 39.006777, -76.779136],
["anneArundelCountyMD", 38.953011, -76.548823],
["shenandoahVA", 38.483457, -78.849748],
["calvertCountyMD", 38.494950, -76.502574],
["salsiburyMD", 38.360674, -75.599369],
["berlinMD", 38.322615, -75.217689],
["ocMD", 38.336503, -75.084906],
["lynchburgVA", 37.413754, -79.142246]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(39.488560, -78.065193)
});
for(var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
icon: 'images/pin-cloud.png',
animation: google.maps.Animation.DROP,
map: map
});
}
var blairCountyContentString =
'<div id="content">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">Blair County, PA</h1>'+
'<div id="bodyContent">'+
"<p>insert info here</p>" +
'<p><b>Resources</b>: <a href="https://efc.umd.edu/assets/sw_case_studies/blair_county_final.pdf" <span>Case Study Blair County, PA</span> </a></p>'+
'</div>'+
'</div>';
var blairCountyInfowindow = new google.maps.InfoWindow({
content: blairCountyContentString,
position: locations[0]
});
marker.addListener('click', function() {
blairCountyInfowindow.open(map, marker);
});
My issue seems to be with the "position: locations[0]" object literal. Sometimes I get an error stating that this needs to be a number value of lng, lat...Tried it though with no luck. The window currently opens but only for the last index of the array. Any ideas?
See updated Code. Now customize the infowindow content
Fiddle link
function initMap() {
var marker = [];
var locations = [
["blairCountyPA", 40.453132, -78.384223],
["scrantonPA", 41.408969, -75.662412],
["warringtonTownshipPA", 40.250319, -75.166212],
["lancasterCountyPA", 40.046657, -76.178374],
["berkeleyCountyWV", 39.488560, -78.065193],
["bowieMD", 39.006777, -76.779136],
["anneArundelCountyMD", 38.953011, -76.548823],
["shenandoahVA", 38.483457, -78.849748],
["calvertCountyMD", 38.494950, -76.502574],
["salsiburyMD", 38.360674, -75.599369],
["berlinMD", 38.322615, -75.217689],
["ocMD", 38.336503, -75.084906],
["lynchburgVA", 37.413754, -79.142246]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(39.488560, -78.065193)
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
var ContentString =
'<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">' + locations[i][0] + '</h1>' +
'<div id="bodyContent">' +
"<p>insert info here</p>" +
'<p><b>Resources</b>: <a href="https://efc.umd.edu/assets/sw_case_studies/blair_county_final.pdf" <span>Case Study ' + locations[i][0] + '</span> </a></p>' +
'</div>' +
'</div>';
return function() {
infowindow.setContent(ContentString);
infowindow.open(map, marker);
}
})(marker, i));
}
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm working on a view of the ASP.NET, using mvc. I using google maps with different markers. Each of those markers have their own infowindows that have 3 buttons each. By clicking a specific button I want the marker to change color. How can I do that?
I have already tried using document.getElementById and using the addEventListner. I also tried to program the button by using the onclick function.
var locations = [
["Recusado", "13/02/2019", 38.776816, -9.441833, 335, "foto.jpg", ],
["Aceite", "15/08/2019",38.817562, -8.941728, 36, "foto.jpg"],
["Em avaliação", "20/07/2019",38.487978, -9.004425, 90,"foto.jpg"],
["Concluído", "01/07/2019",37.045804, -8.898041, 12, "foto.jpg"]
];
var infowindow = new google.maps.InfoWindow({});
function setMarkers(map) {
for (var i = 0; i < locations.length; i++) {
var fire = locations[i];
var marker ;
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<div id="bodyContent">' +
'<p><b>Avaliação da Ocorrência:</b></p>' +
'<p>Fotografias:' + fire[5] + '</p>' +
'<p>Avaliação:' + fire[0] + '</p>' +
'<p>Data:' + fire[1] + '</p></br>' +
'<button id="aceite">Aceite</button>' +
'<button>Recusado</button>' +
'<button> Em avaliação</button>' +
'<button> Concluído</button>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({ content: contentString });
marker = new google.maps.Marker({
position: { lat: fire[2], lng: fire[3] },
map: map,
info: contentString,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(this.info);
infoWindow.open(map, this);
});
}
}
The buttons are represented in the variable contentString, and when I click the button with the id "Aceite", I want to change the color of the marker to green.
Attempt to change the marker to green:
<button id="aceite" onclick="state(marker)">Aceite</button>
function state(marker){
marker.setIcon('google.com/mapfiles/marker_green.png');
}
Simplest would be to add the click listener function when you open the InfoWindow (when you know what marker it is associated with).
Add the click listener to the button when the domready event of the InfoWindow fires (and it has been added to the DOM):
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
Use function closure on the marker in the marker click listener (this references the marker in the click event listener function, but not in the InfoWindow domready event listener, save it so you can use it there):
google.maps.event.addListener(marker, 'click', function() {
var marker = this;
infoWindow.setContent(this.info);
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
infoWindow.open(map, this);
});
proof of concept fiddle
code snippet:
function initMap() {
var myLatLng = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var infowindow = new google.maps.InfoWindow({});
setMarkers(map);
}
var locations = [
["Recusado", "13/02/2019", 38.776816, -9.441833, 335, "foto.jpg", ],
["Aceite", "15/08/2019", 38.817562, -8.941728, 36, "foto.jpg"],
["Em avaliação", "20/07/2019", 38.487978, -9.004425, 90, "foto.jpg"],
["Concluído", "01/07/2019", 37.045804, -8.898041, 12, "foto.jpg"]
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < locations.length; i++) {
var fire = locations[i];
var marker;
var contentString = '<div id="content">' +
'<div id="siteNotice">' +
'</div>' +
'<div id="bodyContent">' +
'<p><b>Avaliação da Ocorrência:</b></p>' +
'<p>Fotografias:' + fire[5] + '</p>' +
'<p>Avaliação:' + fire[0] + '</p>' +
'<p>Data:' + fire[1] + '</p></br>' +
'<button id="aceite">Aceite</button>' +
'<button>Recusado</button>' +
'<button> Em avaliação</button>' +
'<button> Concluído</button>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
marker = new google.maps.Marker({
position: {
lat: fire[2],
lng: fire[3]
},
map: map,
info: contentString,
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
bounds.extend(marker.getPosition());
google.maps.event.addListener(marker, 'click', function() {
var marker = this;
infoWindow.setContent(this.info);
google.maps.event.addListener(infoWindow, 'domready', function() {
google.maps.event.addDomListener(document.getElementById("aceite"), 'click', function(e) {
marker.setIcon('http://maps.google.com/mapfiles/marker_green.png');
})
});
infoWindow.open(map, this);
});
}
map.fitBounds(bounds);
}
html,
body,
#map {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>
I have added marker on google map with some search results.
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
var contentString="";var image_path1="";
contentString += '<div class="browse-map-venue" style="padding:5px;width: 230px;">';
contentString += '<div class="rating" style="float: right; padding-right: 10px;">';
contentString += '<script type="text/javascript" src="<?php echo base_url(); ?>media/front/js/jquery.raty.min.js"><\/script>';
contentString += '<script>';
contentString += '$(function() {';
contentString += '$("#rating_fixed_rate_pop_'+ i +'").raty({';
contentString += 'readOnly: true,';
contentString += 'half: true,';
contentString += 'start: '+ locations[i][6] +',';
contentString += 'score: '+ locations[i][6] +',';
contentString += 'path: "<?php echo base_url(); ?>media/front/img"';
contentString += '});';
contentString += '});';
contentString += '<\/script> ';
contentString += '<div id="rating_fixed_rate_pop_'+ i +'"></div>';
contentString += ''+ locations[i][7] +' reviews';
contentString += '</div>';
contentString += '</div>';
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1],locations[i][2]),
title: locations[i][3],
info: contentString,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.info);
infowindow.open(map, this);
});
}
But I need to add star rating with raty js which not getting applied to it when I click on marker.
Note: When we edit script written for rating from console and just after pressing enter it shows the stars. But I need those to be displayed when I click on marker in infowindow only.
Thanks in advance!
Instead of using a string use a node to create the content(to be able to easily access the content via jQuery)
store the rating as a attribute of the particular node(to be able to use a single function to create the stars)
simple demo:
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(2, 2),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions),
locations = [
[null, 1, 1, 'title#1', null, null, 1.3, 'foo'],
[null, 2, 2, 'title#2', null, null, 3.7, 'bar'],
[null, 3, 3, 'title#3', null, null, 4.3, 'boofar']
],
infowindow = new google.maps.InfoWindow(),
i;
//use the domready-event of the infowindow to execute $.raty
google.maps.event.addListener(infowindow, 'domready', function() {
$(this.getContent()).find('.stars').raty({
half: true,
score: function() {
return $(this).attr('data-score');
},
readOnly: true,
path: 'https://raw.githubusercontent.com/wbotelhos/raty/master/demo/images/'
});
});
for (i = 0; i < locations.length; i++) {
(function(location) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location[1], location[2]),
title: location[3],
map: map,
info: $('<div/>')
//the rating
.append($('<div class="stars"></div>').attr('data-score', location[6]))
//review-link
.append($('' + locations[i][7] + ' reviews'))
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.info[0]);
infowindow.open(map, this);
});
}(locations[i]))
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
margin: 0;
padding: 0
}
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<script src="https://raw.githubusercontent.com/wbotelhos/raty/master/lib/jquery.raty.js"></script>
<div id="map_canvas"></div>
I am having a problem where the google maps will start to slow down and crash after playing around with the draw area function (bottom of page). Wanted to know if I have missed something or I have something in there which is causing it to crash?
var map;
var weatherDisplayIsOn = false;
var markers = [];
var cArea;
function initialize() {
var myLatlng = new google.maps.LatLng(51.488651, -0.063232);
var newYork = new google.maps.LatLng(40.719967, -74.009893);
var paris = new google.maps.LatLng(48.857278, 2.352210);
var london = new google.maps.LatLng(51.519670, -0.125631);
var towerBridge = new google.maps.LatLng(51.506231, -0.075356);
var mapOptions = {
center: myLatlng,
zoom: 8,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var Home = '<div id="content" align="center">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">Home</h1>' +
'<div id="bodyContent">' +
'<p><b>Home</b>, the buidling I had spent the last 13 years living ' +
'in with the locality of Primary Schools, Secondary and Localised ' +
'public transport ' +
'</p>' +
'</div>' +
'</div>';
var infoHome = new google.maps.InfoWindow({
content: Home
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
animation: google.maps.Animation.DROP,
title: 'Homeland'
});
google.maps.event.addListener(marker, 'click', function() {
infoHome.open(map, marker);
});
var NewYork = '<div id="content" align="center">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">New York</h1>' +
'<div id="bodyContent">' +
'<p><b>New York</b>, often called New York City or the City of New York to distinguish ' +
'it from the State of New York, of which it is a part of the most populous city ' +
'in the United States and the center of the New York metropolitan area, the premier gateway for' +
'legal immigration to the United States and one of the most populous urban agglomerations in the world.' +
'</p>' +
'<iframe width="560" height="315" src="https://www.youtube.com/embed/MtCMtC50gwY?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>' +
'</p>' +
'</div>' +
'</div>';
var nyInfo = new google.maps.InfoWindow({
content: NewYork
});
var marker1 = new google.maps.Marker({
position: newYork,
map: map,
animation: google.maps.Animation.DROP,
title: 'New York'
});
google.maps.event.addListener(marker1, 'click', function() {
nyInfo.open(map, marker1);
});
var Paris = '<div id="content" align="center">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">Paris, France</h1>' +
'<div id="bodyContent">' +
'<p><b>Paris</b>, is the capital and most populous city of France. ' +
'Situated on the Seine River, in the north of the country, it is in the centre of the ' +
'Ile-de-France region, also known as the region parisienne.' +
'</p>' +
'<iframe width="560" height="315" src="https://www.youtube.com/embed/hWo-43ObCP8" frameborder="0" allowfullscreen></iframe>' +
'</div>' +
'</div>';
var parisInfo = new google.maps.InfoWindow({
content: Paris
});
var marker2 = new google.maps.Marker({
position: paris,
map: map,
animation: google.maps.Animation.DROP,
title: 'Paris'
});
google.maps.event.addListener(marker2, 'click', function() {
parisInfo.open(map, marker2);
});
var London = '<div id="content" align="center">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">London, United Kingdom</h1>' +
'<div id="bodyContent">' +
'<p><b>London</b>, is the capital city of England and the United Kingdom.' +
'It is the most populous city in the United Kingdom, with a metropolitan area of over ' +
'13 million inhabitants. ' +
'</p>' +
'<iframe width="560" height="315" src="https://www.youtube.com/embed/45ETZ1xvHS0?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>' +
'</div>' +
'</div>';
var londonInfo = new google.maps.InfoWindow({
content: London
});
var marker3 = new google.maps.Marker({
position: london,
map: map,
animation: google.maps.Animation.DROP,
title: 'London'
});
google.maps.event.addListener(marker3, 'click', function() {
londonInfo.open(map, marker3);
});
var TowerBridge = '<div id="content" align="center">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">Tower Bridge,London</h1>' +
'<div id="bodyContent">' +
'<p><b>Tower Bridge</b>, is the capital city of England and the United Kingdom.' +
'It is the most populous city in the United Kingdom, with a metropolitan area of over ' +
'13 million inhabitants. ' +
'</p>' +
'<iframe width="560" height="315" src="https://www.youtube.com/embed/45ETZ1xvHS0?rel=0&controls=0&showinfo=0" frameborder="0" allowfullscreen></iframe>' +
'</div>' +
'</div>';
var towerBridgeInfo = new google.maps.InfoWindow({
content: TowerBridge
});
var marker4 = new google.maps.Marker({
position: towerBridge,
map: map,
animation: google.maps.Animation.DROP,
title: 'Tower Bridge'
});
google.maps.event.addListener(marker4, 'click', function() {
towerBridgeInfo.open(map, marker4)
});
weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.CELCIUS
});
google.maps.event.addDomListener(document.getElementById('weather'), 'click', toggleWeather);
};
google.maps.event.addDomListener(window, 'load', initialize);
function setRoad() {
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
}
function setHYB() {
map.setMapTypeId(google.maps.MapTypeId.HYBRID);
}
function zoomTo() {
var lat = prompt("Enter your latitude");
var lng = prompt("Enter your longtitude");
map.panTo(new google.maps.LatLng(lat, lng));
}
function zoomIn() {
var currentZoomLevel = map.getZoom();
if (currentZoomLevel != 21) {
map.setZoom(currentZoomLevel + 1);
}
}
function zoomOut() {
var currentZoomLevel = map.getZoom();
if (currentZoomLevel != 21) {
map.setZoom(currentZoomLevel - 1);
}
}
function toggleWeather() {
if (weatherDisplayIsOn) {
weatherLayer.setMap(null);
weatherDisplayIsOn = false;
}
else {
weatherLayer.setMap(map);
weatherDisplayIsOn = true;
}
}
function addMarker(myLatlng) {
var customMarker = new google.maps.Marker({
position: myLatlng,
map: map
});
markers.push(customMarker);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
function setAllMap(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
function clearMarkers() {
setAllMap(null);
}
function showMarkers() {
setAllMap(map);
}
function deleteMarkers() {
clearMarkers();
markers = [];
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
function drawArea()
{
var points = new google.maps.MVCArray();
var endPoint = new google.maps.LatLngBounds();
cArea = new google.maps.Polygon({
path: points,
strokeOpacity: 0.7,
strokeWeight: 2,
fillOpacity: 0.2,
fillColor: "#FF0000"
});
cArea.setMap(map);
google.maps.event.addListener(map, 'click', function(e)
{
var path = cArea.getPath();
path.push(e.latLng);
endPoint.extend(e.latLng);
addMarker(e.latLng);
});
}
function deleteArea(){
cArea.setMap(null);
}
You have this function:
function addMarker(myLatlng) {
var customMarker = new google.maps.Marker({
position: myLatlng,
map: map
});
markers.push(customMarker);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
In which you define an event listener for map clicks, which calls... the addMarker function... which defines an event listener for map clicks, which calls... the addMarker function... which defines an event listener for map clicks,... etc etc ad infinitum.
In other words, the error is probably too much recursion.
And to cap it all, you also define the same event listener elsewhere too:
google.maps.event.addListener(map, 'click', function(e)
{
var path = cArea.getPath();
path.push(e.latLng);
endPoint.extend(e.latLng);
addMarker(e.latLng);
});
Although this seems to be in a function ('drawArea') that isn't called from anywhere.
Just move this outside of the addMarker function, to wherever you create the map:
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
Hello I'm retrieving data from SqlServerCe so I created foreach loop to create markers - that works it creates multiple markers but now I wanted to add to each of these marker an infowindow. But now whenever I click on marker the infowindow pops-up on the lastly created marker.
<script>
function initialize() {
var mapProp = {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap")
, mapProp);
$(function () {
#foreach (var row in data)
{
<text>
var marker = new google.maps.Marker({ position: new google.maps.LatLng(#row.GeoLat, #row.GeoLong),
map: map });
marker.info = new google.maps.InfoWindow({
content: "test"
});
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
</text>
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
May someone help me with adding infowindow to each created markers?
Thank you for your responding and your time.
This is how I load from SqlServerCe
var db = Database.Open("StarterSite");
var data = db.Query("SELECT DescriptionService,GeoLong,GeoLat FROM services");
var array = new []{data} ;
You can use the following, written in javascript
var infoWindowContent = [];
for(var index=0; index< places.length; index++){
infoWindowContent[index] = getInfoWindowDetails(places[index]);
var location = new google.maps.LatLng(places[index].latitude,places[index].longitude);
bounds.extend(location);
marker = new google.maps.Marker({
position : location,
map : map,
title : places[index].title
});
google.maps.event.addListener(marker, 'click', (function(marker,index){
return function(){
infoWindow.setContent(infoWindowContent[index]);
infoWindow.open(map, marker);
map.setCenter(marker.getPosition());
map.setZoom(15);
}
})(marker,index));
}
function getInfoWindowDetails(location){
var contentString = '<div id="content" style="width:270px;height:100px">' +
'<h3 id="firstHeading" class="firstHeading">' + location.title + '</h3>'+
'<div id="bodyContent">'+
'<div style="float:left;width:100%">'+ location.address + '</div>'+
'</div>'+
'</div>';
return contentString;
}
I added an array infoWindowContent then added the information to the array. You can use the same logic
I am making a google maps for my website so you can view where each user is.
This works perfect only when you click on an icon of someone it will show you the same every time i cant understand it am i doing something wrong?
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","includes/xml.php",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("USER");
var infoWindow = new google.maps.InfoWindow();
var map;
var users = [];
function initialize() {
var mapOptions = {
zoom: 9,
center: new google.maps.LatLng(52.1424, 5.09428),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
for (i=0;i<x.length;i++) {
var id = x[i].getElementsByTagName("USERID")[0].childNodes[0].nodeValue;
users['USERNAME'+id] = x[i].getElementsByTagName("USERNAME")[0].childNodes[0].nodeValue;
users['CITY'+id] = x[i].getElementsByTagName("CITY")[0].childNodes[0].nodeValue;
users['COUNTRY'+id] = x[i].getElementsByTagName("COUNTRY")[0].childNodes[0].nodeValue;
users['IMAGE'+id] = x[i].getElementsByTagName("IMAGE")[0].childNodes[0].nodeValue;
users['IMAGEPIN'+id] = x[i].getElementsByTagName("IMAGEPIN")[0].childNodes[0].nodeValue;
users['LAT'+id] = x[i].getElementsByTagName("LAT")[0].childNodes[0].nodeValue;
users['LONG'+id] = x[i].getElementsByTagName("LONG")[0].childNodes[0].nodeValue;
users['DATETIME'+id] = x[i].getElementsByTagName("DATETIME")[0].childNodes[0].nodeValue;
users['TWITTER'+id] = x[i].getElementsByTagName("TWITTER")[0].childNodes[0].nodeValue;
users['FA'+id] = x[i].getElementsByTagName("FA")[0].childNodes[0].nodeValue;
users['ACTIVEUSER'+id] = x[i].getElementsByTagName("ACTIVEUSER")[0].childNodes[0].nodeValue;
users['myLatlng'+id] = new google.maps.LatLng(users['LAT'+id],users['LONG'+id]);
users['content'+id] = '<div style="width:220px;"><img id="avatar"style="margin-right: 5px;" src="' + users['IMAGE'+id] + '"></img>' +
'<b>' + users['USERNAME'+id] + '</b><br />' +
users['CITY'+id] + '<br />' + users['COUNTRY'+id] + '<br />' +
'<i>' + users['DATETIME'+id] + '</i><br />' +
'<img src="http://www.kinzart.com/images/fur-affinity-icon.png" Alt="Twitter" width="30" height="30">' +
'<img src="http://biophiliccities.org/wp-content/uploads/2013/06/twitterICON.png" Alt="Twitter" width="30" height="30">';
users['window'+id] = new google.maps.InfoWindow({ content: users['content'+id]});
users['marker'+id] = new google.maps.Marker({ position: users['myLatlng'+id], map: map, title: users['USERNAME'+id], icon: users['IMAGEPIN'+id]});
google.maps.event.addListener(users['marker'+id], 'click', function() { infoWindow.setContent(users['content'+id]); infoWindow.open(map, users['marker'+id]) });
}
}
google.maps.event.addDomListener(window, 'load', initialize);
The problem is that when you setup your event listener within the loop, it ends up that every iteration of the loop sets the infowindow content to be whatever the last value of users['content'+id] is. You need to look into using closures in your code.
Here's another way of doing it that should work:
for (i=0;i<x.length;i++) {
... // trimmed for brevity
users['marker'+id] = new google.maps.Marker({ position: users['myLatlng'+id], map: map, title: users['USERNAME'+id], icon: users['IMAGEPIN'+id]});
bindInfoWindow(users['marker'+id], users['content'+id]);
}
then have this function:
function bindInfoWindow(marker, content) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(content);
infoWindow.open(map, marker)
});
}