Trouble creating Google Map infowindow by passing information into an IIFE - google-maps-api-3

I am trying to create an infowindow with an IIFE. I am having quite a bit of trouble passing information into it.
As you can see I retrieved an array of places using the searchBox Class, which was instantiated and correctly implemented in order to properly use the getPlaces() method.
Places is an array of objects and I use the information to create a marker and infowindow. The markers show up! However, I can't seem to pass the object, places[i], into the IIFE.
There's NOT even an error in the console, which is why I am in desperate need of your help.
My ultimate goal is to have an infowindow open on the clicked marker with the the corresponding information.
Can anyone spot what I am doing wrong here?
var places = searchBox.getPlaces(); // array of place objects
var placeMarkers = [];
var placeInfoWindow = new google.maps.InfoWindow();
var placeBounds = new google.maps.LatLngBounds();
if (!places || places === null || places.length === 0) {
alert("No Places Founds");
} else {
for (var i = 0, l = places.length; i < l; i++) {
// MARKER
var loc = places[i].geometry.location;
var placeMarker = new google.maps.Marker({
position: loc,
title: places[i].name,
animation: google.maps.Animation.DROP,
icon: places[i].icon
});
placeMarkers.push(placeMarker); // save each marker
placeMarker.setMap(map); // display marker immediately
// extend boundary to include each marker location
placeBounds.extend(loc);
//REGISTER MARKER CLICK HANDLER WITH CURRENT places[i] INFO
placeMarker.addListener("click", (function(placeCopy) {
return function() {
var infoWindowContentStr = '<div>';
if (placeCopy.name) {
infoWindowContentStr += '<div>' + placeCopy.name + '</div><br>';
}
if (placeCopy.formatted_address) {
infoWindowContentStr += '<div>' + placeCopy.formatted_address + '</div>';
}
infoWindowContentStr += '</div>';
placeInfoWindow.setContent(infoWindowContentStr);
placeInfoWindow.open(map, this);
};
}), places[i]);
}
map.fitBounds(placeBounds);
}

You have a typo in your IIFE function definition, it isn't executing the function and getting closure until the click happens.
related question: Google Maps API Places Library SearchBox (used to create the MCVE)
placeMarker.addListener("click", (function(placeCopy) {
return function() {
var infoWindowContentStr = '<div>';
if (placeCopy.name) {
infoWindowContentStr += '<div>' + placeCopy.name + '</div><br>';
}
if (placeCopy.formatted_address) {
infoWindowContentStr += '<div>' + placeCopy.formatted_address + '</div>';
}
infoWindowContentStr += '</div>';
placeInfoWindow.setContent(infoWindowContentStr);
placeInfoWindow.open(map, this);
};
})(places[i])); // you had }), places[i]);
proof of concept fiddle
code snippet:
function initialize() {
map = new google.maps.Map(document.getElementById('map_canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(41.7033177, -93.0573533),
new google.maps.LatLng(41, -93)
);
map.fitBounds(defaultBounds);
var input = document.getElementById('target');
var searchBox = new google.maps.places.SearchBox(input);
searchBox.setBounds(defaultBounds);
var markers = [];
service = new google.maps.places.PlacesService(map);
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces(); // array of place objects
var placeMarkers = [];
var placeInfoWindow = new google.maps.InfoWindow();
var placeBounds = new google.maps.LatLngBounds();
if (!places || places === null || places.length === 0) {
alert("No Places Founds");
} else {
for (var i = 0, l = places.length; i < l; i++) {
// MARKER
var loc = places[i].geometry.location;
var placeMarker = new google.maps.Marker({
position: loc,
title: places[i].name,
animation: google.maps.Animation.DROP,
icon: places[i].icon
});
placeMarkers.push(placeMarker); // save each marker
placeMarker.setMap(map); // display marker immediately
// extend boundary to include each marker location
placeBounds.extend(loc);
//REGISTER MARKER CLICK HANDLER WITH CURRENT places[i] INFO
placeMarker.addListener("click", (function(placeCopy) {
return function() {
var infoWindowContentStr = '<div>';
if (placeCopy.name) {
infoWindowContentStr += '<div>' + placeCopy.name + '</div><br>';
}
if (placeCopy.formatted_address) {
infoWindowContentStr += '<div>' + placeCopy.formatted_address + '</div>';
}
infoWindowContentStr += '</div>';
placeInfoWindow.setContent(infoWindowContentStr);
placeInfoWindow.open(map, this);
};
})(places[i]));
}
map.fitBounds(placeBounds);
}
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#search-panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
width: 350px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
#target {
width: 345px;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<div id="search-panel">
<input id="target" type="text" placeholder="Search Box">
</div>
<div id="map_canvas"></div>

Related

markers places are incorrect in KML google map

I made a map on Google Maps, I downloaded the KML file and used it in a map with sidebar. But the places of the markers are incorrect. All of them are below the correct places. The code is as below. Example page is on test page .If I use the simple KML layer example of Google, same errors occur.
<style type="text/css">
html, body, #map_canvas {
width: 750px;
height: 600px;
margin: 0;
padding: 0;
}
.infowindow * {font-size: 90%; margin: 0}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/branches/polys/geoxml3.js">
</script>
<script type="text/javascript" src="http://geoxml3.googlecode.com/svn/trunk/ProjectedOverlay.js">
</script>
<script type="text/javascript">
var geoXml = null;
var geoXmlDoc = null;
var map = null;
var myLatLng = null;
var myGeoXml3Zoom = true;
var sidebarHtml = "";
var infowindow = null;
var kmlLayer = null;
var filename = "europeancapitals.xml";
function MapTypeId2UrlValue(maptype) {
var urlValue = 'm';
switch(maptype){
case google.maps.MapTypeId.HYBRID: urlValue='h';
break;
case google.maps.MapTypeId.SATELLITE: urlValue='k';
break;
case google.maps.MapTypeId.TERRAIN: urlValue='t';
break;
default:
case google.maps.MapTypeId.ROADMAP: urlValue='m';
break;
}
return urlValue;
}
// ========== This function will create the "link to this page"
function makeLink() {
// var a="http://www.geocodezip.com/v3_MW_example_linktothis.html"
var url = window.location.pathname;
var a = url.substring(url.lastIndexOf('/')+1)
+ "?lat=" + map.getCenter().lat().toFixed(6)
+ "&lng=" + map.getCenter().lng().toFixed(6)
+ "&zoom=" + map.getZoom()
+ "&type=" + MapTypeId2UrlValue(map.getMapTypeId());
if (filename != "europeancapitals.xml") a += "&filename="+filename;
document.getElementById("link").innerHTML = '<a href="' +a+ '">Link to this page<\/a>';
}
function initialize() {
myLatLng = new google.maps.LatLng(46,14);
// these set the initial center, zoom and maptype for the map
// if it is not specified in the query string
var lat = 46;
var lng = 14;
var zoom = 8;
var maptype = google.maps.MapTypeId.ROADMAP;
// If there are any parameters at eh end of the URL, they will be in location.search
// looking something like "?marker=3"
// skip the first character, we are not interested in the "?"
var query = location.search.substring(1);
// split the rest at each "&" character to give a list of "argname=value" pairs
var pairs = query.split("&");
for (var i=0; i<pairs.length; i++) {
// break each pair at the first "=" to obtain the argname and value
var pos = pairs[i].indexOf("=");
var argname = pairs[i].substring(0,pos).toLowerCase();
var value = pairs[i].substring(pos+1).toLowerCase();
// process each possible argname - use unescape() if theres any chance of spaces
if (argname == "id") {id = unescape(value);}
if (argname == "filename") {filename = unescape(value);}
if (argname == "marker") {index = parseFloat(value);}
if (argname == "lat") {lat = parseFloat(value);}
if (argname == "lng") {lng = parseFloat(value);}
if (argname == "zoom") {
zoom = parseInt(value);
myGeoXml3Zoom = false;
}
if (argname == "type") {
// from the v3 documentation 8/24/2010
// HYBRID This map type displays a transparent layer of major streets on satellite images.
// ROADMAP This map type displays a normal street map.
// SATELLITE This map type displays satellite images.
// TERRAIN This map type displays maps with physical features such as terrain and vegetation.
if (value == "m") {maptype = google.maps.MapTypeId.ROADMAP;}
if (value == "k") {maptype = google.maps.MapTypeId.SATELLITE;}
if (value == "h") {maptype = google.maps.MapTypeId.HYBRID;}
if (value == "t") {maptype = google.maps.MapTypeId.TERRAIN;}
}
}
if (!isNaN(lat) && !isNaN(lng)) {
myLatLng = new google.maps.LatLng(lat, lng);
}
var myOptions = {
zoom: zoom,
center: myLatLng,
// zoom: 5,
// center: myLatlng,
mapTypeId: maptype
};
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
infowindow = new google.maps.InfoWindow({});
geoXml = new geoXML3.parser({
map: map,
infoWindow: infowindow,
singleInfoWindow: true,
zoom: myGeoXml3Zoom,
markerOptions: {optimized: false},
afterParse: useTheData
});
geoXml.parse(filename);
google.maps.event.addListener(map, "bounds_changed", makeSidebar);
google.maps.event.addListener(map, "center_changed", makeSidebar);
google.maps.event.addListener(map, "zoom_changed", makeSidebar);
// Make the link the first time when the page opens
makeLink();
// Make the link again whenever the map changes
google.maps.event.addListener(map, 'maptypeid_changed', makeLink);
google.maps.event.addListener(map, 'center_changed', makeLink);
google.maps.event.addListener(map, 'bounds_changed', makeLink);
google.maps.event.addListener(map, 'zoom_changed', makeLink);
};
function kmlPgClick(pm) {
if (geoXml.docs[0].placemarks[pm].polygon.getMap()) {
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polygon,"click");
} else {
geoXmlDoc.placemarks[pm].polygon.setMap(map);
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polygon,"click");
}
}
function kmlPlClick(pm) {
if (geoXml.docs[0].placemarks[pm].polyline.getMap()) {
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polyline,"click");
} else {
geoXmlDoc.placemarks[pm].polyline.setMap(map);
google.maps.event.trigger(geoXmlDoc.placemarks[pm].polyline,"click");
}
}
function kmlClick(pm) {
if (geoXml.docs[0].placemarks[pm].marker.getMap()) {
google.maps.event.trigger(geoXml.docs[0].placemarks[pm].marker,"click");
} else {
geoXmlDoc.placemarks[pm].marker.setMap(map);
google.maps.event.trigger(geoXmlDoc.placemarks[pm].marker,"click");
}
}
function kmlShowPlacemark(pm) {
if (geoXmlDoc.placemarks[pm].polygon) {
map.fitBounds(geoXmlDoc.placemarks[pm].polygon.bounds);
} else if (geoXmlDoc.placemarks[pm].polyline) {
map.fitBounds(geoXmlDoc.placemarks[pm].polyline.bounds);
} else if (geoXmlDoc.placemarks[pm].marker) {
map.setCenter(geoXmlDoc.placemarks[pm].marker.getPosition());
}
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
var placemark = geoXmlDoc.placemarks[i];
if (i == pm) {
if (placemark.polygon) placemark.polygon.setMap(map);
if (placemark.polyline) placemark.polyline.setMap(map);
if (placemark.marker) placemark.marker.setMap(map);
} else {
if (placemark.polygon) placemark.polygon.setMap(null);
if (placemark.polyline) placemark.polyline.setMap(null);
if (placemark.marker) placemark.marker.setMap(null);
}
}
}
var highlightOptions = {fillColor: "#FFFF00", strokeColor: "#000000", fillOpacity: 0.9, strokeWidth: 10};
var highlightLineOptions = {strokeColor: "#FFFF00", strokeWidth: 10};
function kmlHighlightPoly(pm) {
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
var placemark = geoXmlDoc.placemarks[i];
if (i == pm) {
if (placemark.polygon) placemark.polygon.setOptions(highlightOptions);
if (placemark.polyline) placemark.polyline.setOptions(highlightLineOptions);
} else {
if (placemark.polygon) placemark.polygon.setOptions(placemark.polygon.normalStyle);
if (placemark.polyline) placemark.polyline.setOptions(placemark.polyline.normalStyle);
}
}
}
function kmlUnHighlightPoly(pm) {
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
if (i == pm) {
var placemark = geoXmlDoc.placemarks[i];
if (placemark.polygon) placemark.polygon.setOptions(placemark.polygon.normalStyle);
if (placemark.polyline) placemark.polyline.setOptions(placemark.polyline.normalStyle);
}
}
}
function showAll() {
map.fitBounds(geoXmlDoc.bounds);
for (var i=0;i<geoXmlDoc.placemarks.length;i++) {
var placemark = geoXmlDoc.placemarks[i];
if (placemark.polygon) placemark.polygon.setMap(map);
if (placemark.polyline) placemark.polyline.setMap(map);
if (placemark.marker) placemark.marker.setMap(map);
}
}
function highlightPoly(poly, polynum) {
// poly.setOptions({fillColor: "#0000FF", strokeColor: "#0000FF", fillOpacity: 0.3}) ;
google.maps.event.addListener(poly,"mouseover",function() {
var rowElem = document.getElementById('row'+polynum);
if (rowElem) rowElem.style.backgroundColor = "#FFFA5E";
if (geoXmlDoc.placemarks[polynum].polygon) {
poly.setOptions(highlightOptions);
} else if (geoXmlDoc.placemarks[polynum].polyline) {
poly.setOptions(highlightLineOptions);
}
});
google.maps.event.addListener(poly,"mouseout",function() {
var rowElem = document.getElementById('row'+polynum);
if (rowElem) rowElem.style.backgroundColor = "#FFFFFF";
poly.setOptions(poly.normalStyle);
});
}
// == rebuilds the sidebar to match the markers currently displayed ==
function makeSidebarPolygonEntry(i) {
var name = geoXmlDoc.placemarks[i].name;
if (!name || (name.length == 0)) name = "polygon #"+i;
// alert(name);
sidebarHtml += '<tr id="row'+i+'"><td onmouseover="kmlHighlightPoly('+i+');" onmouseout="kmlUnHighlightPoly('+i+');">'+name+' - show</td></tr>';
}
function makeSidebarPolylineEntry(i) {
var name = geoXmlDoc.placemarks[i].name;
if (!name || (name.length == 0)) name = "polyline #"+i;
// alert(name);
sidebarHtml += '<tr id="row'+i+'"><td onmouseover="kmlHighlightPoly('+i+');" onmouseout="kmlUnHighlightPoly('+i+');">'+name+' - show</td></tr>';
}
function makeSidebarEntry(i) {
var name = geoXmlDoc.placemarks[i].name;
if (!name || (name.length == 0)) name = "marker #"+i;
// alert(name);
sidebarHtml += '<tr id="row'+i+'"><td>'+name+'</td></tr>';
}
function makeSidebar() {
sidebarHtml = '<table><tr><td>Show All</td></tr>';
var currentBounds = map.getBounds();
// if bounds not yet available, just use the empty bounds object;
if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
if (geoXmlDoc) {
for (var i=0; i<geoXmlDoc.placemarks.length; i++) {
if (geoXmlDoc.placemarks[i].polygon) {
if (currentBounds.intersects(geoXmlDoc.placemarks[i].polygon.bounds)) {
makeSidebarPolygonEntry(i);
}
}
if (geoXmlDoc.placemarks[i].polyline) {
if (currentBounds.intersects(geoXmlDoc.placemarks[i].polyline.bounds)) {
makeSidebarPolylineEntry(i);
}
}
if (geoXmlDoc.placemarks[i].marker) {
if (currentBounds.contains(geoXmlDoc.placemarks[i].marker.getPosition())) {
makeSidebarEntry(i);
}
}
}
}
sidebarHtml += "</table>";
document.getElementById("sidebar").innerHTML = sidebarHtml;
}
function useTheData(doc){
var currentBounds = map.getBounds();
if (!currentBounds) currentBounds=new google.maps.LatLngBounds();
// Geodata handling goes here, using JSON properties of the doc object
sidebarHtml = '<table><tr><td>Show All</td></tr>';
// var sidebarHtml = '<table>';
geoXmlDoc = doc[0];
for (var i = 0; i < geoXmlDoc.placemarks.length; i++) {
// console.log(doc[0].markers[i].title);
var placemark = geoXmlDoc.placemarks[i];
if (placemark.polygon) {
if (currentBounds.intersects(placemark.polygon.bounds)) {
makeSidebarPolygonEntry(i);
}
var normalStyle = {
strokeColor: placemark.polygon.get('strokeColor'),
strokeWeight: placemark.polygon.get('strokeWeight'),
strokeOpacity: placemark.polygon.get('strokeOpacity'),
fillColor: placemark.polygon.get('fillColor'),
fillOpacity: placemark.polygon.get('fillOpacity')
};
placemark.polygon.normalStyle = normalStyle;
highlightPoly(placemark.polygon, i);
}
if (placemark.polyline) {
if (currentBounds.intersects(placemark.polyline.bounds)) {
makeSidebarPolylineEntry(i);
}
var normalStyle = {
strokeColor: placemark.polyline.get('strokeColor'),
strokeWeight: placemark.polyline.get('strokeWeight'),
strokeOpacity: placemark.polyline.get('strokeOpacity')
};
placemark.polyline.normalStyle = normalStyle;
highlightPoly(placemark.polyline, i);
}
if (placemark.marker) {
if (currentBounds.contains(placemark.marker.getPosition())) {
makeSidebarEntry(i);
}
}
/* doc[0].markers[i].setVisible(false); */
}
sidebarHtml += "</table>";
document.getElementById("sidebar").innerHTML = sidebarHtml;
};
function hide_kml(){
geoXml.hideDocument();
}
function unhide_kml(){
geoXml.showDocument();
}
function reload_kml(){
geoXml.hideDocument();
delete geoXml;
geoXml = new geoXML3.parser({
map: map,
singleInfoWindow: true,
afterParse: useTheData
});
geoXml.parse(filename);
}
function hide_markers_kml(){
for (var i=0;i<geoXmlDoc.markers.length;i++) {
geoXmlDoc.markers[i].setVisible(false);
}
}
function unhide_markers_kml(){
for (var i=0;i<geoXmlDoc.markers.length;i++) {
geoXmlDoc.markers[i].setVisible(true);
}
}
function hide_polys_kml(){
for (var i=0;i<geoXmlDoc.gpolylines.length;i++) {
geoXmlDoc.gpolylines[i].setMap(null);
}
}
function unhide_polys_kml(){
for (var i=0;i<geoXmlDoc.gpolylines.length;i++) {
geoXmlDoc.gpolylines[i].setMap(map);
}
}
function load_kmlLayer() {
kmlLayer = new google.maps.KmlLayer(filename);
google.maps.event.addListener(kmlLayer, "status_changed", function() {
document.getElementById('kmlstatus').innerHTML = "Kml Status:"+kmlLayer.getStatus();
});
kmlLayer.setMap(map);
}
function hide_kmlLayer() {
kmlLayer.setMap(null);
}
function show_kmlLayer() {
kmlLayer.setMap(map);
}
</script>
</head>
<body onload="initialize()">
<h4>Reading a KML file with Google Maps JavaScript API Version 3 and geoxml3.</h4>
<!-- <button onclick="hide_polys_kml();">hide polylines</button>
<button onclick="unhide_polys_kml();">unhide polylines</button> -->
<button onclick="hide_kml();">hide</button>
<button onclick="unhide_kml();">unhide</button>
<button onclick="hide_markers_kml();">hide markers</button>
<button onclick="unhide_markers_kml();">show markers</button>
<button onclick="load_kmlLayer();">load kmlLayer</button>
<button onclick="hide_kmlLayer();">hide kmlLayer</button>
<button onclick="show_kmlLayer();">show kmlLayer</button>
<!-- <button onclick="reload_kml();">reload</button> -->
<table style="width:100%;"><tr><td>
<div id="map_canvas">
</div>
</td><td>
<div id="sidebar" style="width:300px;height:600px; overflow:auto"></div>
</td></tr>
<tr><td colspan="2"> <div id="link"></div></td></tr>
</table>
<div id="map_text">
</div>
<div id="kmlstatus"></div>
</body>
</html>
You need to set the "hotSpot" for your custom icons.
<hotSpot x="0.5" y="0.5" xunits="fraction" yunits="fraction">
Specifies the position within the Icon that is "anchored" to the specified in the Placemark. The x and y
values can be specified in three different ways: as pixels ("pixels"), as fractions of the icon ("fraction"), or as
inset pixels ("insetPixels"), which is an offset in pixels from the upper right corner of the icon. The x and y
positions can be specified in different ways—for example, x can be in pixels and y can be a fraction. The origin of > the coordinate system is in the lower left corner of the icon.
The hotSpot tag is (now) supported (correctly) in the kmz branch of geoxml3:
working example

Google Map V3: markerCluster onclick display all the infoboxes for the markers inside the cluster in one infobox list style.

Am retrieving pin or marker details from json response, What I need is to retrieve the particular marker details which are clustered,
For example from the screenshot consider the clusterer with 3 marker count, now am able to retrieve only 3 marker details from the start of the array, I need to retrieve the particular three marker details clustered.
Following method is used to retrieve and display marker detail in infoWindow,
function displayClusterInfo(cluster,info,pins,infowindow)
{
var text="";
var markers = cluster.getMarkers();
for(var i=0; i<markers.length; i++)
{
text += "" + pins[i].Date + "</br>" + "<b>Fire Type : </b>" + pins[i].Inc_Code_descr + "</br>";
}
infowindow.close(map, info);
infowindow.setContent(text); //set infowindow content
infowindow.open(map, info);
}
mouse event action on marker and cluster are performed by the following code:
function displayPins(pins) {
infowindow = new google.maps.InfoWindow({
content: "holding..."
});
var markers = [];
var boxList = [];
var pinList = [];
latLng = [];
$.each(pins, function(i, pin) {
var pinText = document.createElement("div");
pinText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
pinText.innerHTML = "" + pin.Date + "</br>" + "<b>Fire Type : </b>" + pin.Inc_Code_descr + "</br>";
var pinOptions = {
content: pinText,
boxStyle: {
opacity: 0.75,
width: "220px"
},
enableEventPropagation: false,
closeBoxMargin: "12px 4px 2px 2px"
};
var ip = new InfoBox(pinOptions);
pinList.push(ip);
var boxText = document.createElement("div");
boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background: yellow; padding: 5px;";
boxText.innerHTML = "" + pin.Date + "</br>" + pin.Address + "</br><b>Incident No : </b><a class=no_image href=./info/?id=" + pin.Div_id + ">" + pin.Incident_no + "</a><br/>" + "</br><b>Fire Type : </b>" + pin.Inc_Code_descr + "</br><b>Casuality : </b>" + pin.Casualty + "</br><b>Property Damage : </b>" + pin.Prop_loss + "</br><b>Fire cause : </b>" + pin.Cause_Code_descr + "</br><b>GRANULARITY: </b>" + pin.granularity + "</br><b>COLOUR: </b>" + pin.colour + "</br><b><p class='red'>CONFIDENCES: </b>" + pin.confidence + "'</P>";
var myOptions = {
content: boxText,
boxStyle: {
opacity: 0.75,
width: "280px"
},
enableEventPropagation: false,
closeBoxMargin: "12px 4px 2px 2px"
};
latLng = new google.maps.LatLng(pin.Latitude, pin.Longitude);
var marker = new google.maps.Marker({'position': latLng
, map: map,
draggable: true,
optimized: false,
visible: true});
markers.push(marker);
var ib = new InfoBox(myOptions);
boxList.push(ib);
google.maps.event.addListener(marker, 'mouseover', function(markers, i) {
return function() {
hoverInfoBox = pinList[i];
if (clickInfoBox) {
if ((clickInfoBox.getMap()) == null)
{
clickInfoBox = null;
hoverInfoBox.open(map, this);
} else
{
console.log(" Click infobox not closed");
}
} else
{
clickInfoBox = null;
hoverInfoBox.open(map, this);
}
}
}(markers, i));
google.maps.event.addListener(marker, 'click', function(boxList, i) {
return function() {
if (clickInfoBox) {
clickInfoBox.close(map, this);
}
clickInfoBox = boxList[i];
if (clickInfoBox) {
hoverInfoBox.close(map, this);
clickInfoBox.open(map, this);
}
}
}(boxList, i));
google.maps.event.addListener(marker, 'mouseout', function(markers, i) {
return function() {
if (clickInfoBox) {
if ((clickInfoBox.getMap()) == null)
{
hoverInfoBox.close(map, this);
} else
{
console.log(" Click infobox not closed");
}
} else
{
hoverInfoBox.close(map, this);
}
}
}(markers, i));
});
var infowindow = new google.maps.InfoWindow();
var clusterOptions = {zoomOnClick: false, styles: [{height: 53, width: 53, url: "http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/images/m1.png"}]}
var markerCluster = new MarkerClusterer(map, markers, clusterOptions);
var infoList = new google.maps.InfoWindow();
google.maps.event.addListener(markerCluster, 'clusterclick', function(cluster) {
var content = '';
displayClusterInfo(cluster,info,pins,infowindow);
});
}
You have add your data to the marker object . so cluster.getMarker() will give the marker which are clustered in that pin. create a attribute in marker and access it whenever you need.
var marker = new google.maps.Marker({'position': latLng
, map: map,myData: boxText.innnerHtml
draggable: true,
optimized: false,
visible: true});
And in displayClusterInfo method
for(var i=0; i<markers.length; i++)
{
text += markers[i].myData;
}

Google Maps changing a marker back to its original image

A wee bit out of my depth here, I hope someone can help me resolve this...
I have a Google map which loads data from an array and also populates a sidebar list of the items.
A click on the sidebar item opens the corresponding infowindow as expected o.k.
When I mouseenter a sidebar item it pans to if necessary and highlights the corresponding marker (and closes any infowindow currently open ).
(.locs is the sidebar container, .loc is an item)
$(document).on("mouseenter",".loc",function() {
var thisloc = $(this).data("locid");
for(var i=0; i<markers.length; i++) {
if(markers[i].locid == thisloc) { //get the latlong
if(lastinfowindow instanceof google.maps.InfoWindow) lastinfowindow.close();
map.panTo(markers[i].getPosition());
markers[i].setIcon('../mapIcons/mini-white.png');
}
}
});
This bit works fine as I'm just setting a fixed image.
However, when I mouseleave the marker fails to revert back to its original state.
If I use the setIcon for a specic image it works fine, but I want to refer back to the original icon from the dataset item.
markers[i].setIcon("currmark");
currmark is the var I used to hold the original icon.
$(document).on("mouseleave",".loc",function() {
var thisloc = $(this).data("locid");
var currmark = getIcon("mapData.type");
for(var i=0; i<markers.length; i++) {
if(markers[i].locid == thisloc) { //get the latlong
map.panTo(markers[i].getPosition());
markers[i].setIcon("currmark");
}
}
});
An alert set on 'currmark', the var I used to hold the original icon, shows only the last icon set by the mouseenter setIcon.
This seems to idicate to me that the original icon from the dataset (mapdata.type) has been forgotten / replaced by the last setting applied to markers[i].
I think I need to reaccess the dataset to remind the var of the original state when I set
var currmark = getIcon("mapData.type");
Some added info....
I'm using a utility function that translates a given 'type' in the dataset to an icon, hence the getIcon(type) function.
function getIcon(type) {
switch(type) {
case "bar": return "../mapIcons/mini-blue.png";
case "restaurant": return "../mapIcons/mini-red.png";
case "cafe": return "../mapIcons/mini-yellow.png";
default: return "../mapIcons/mini-white.png";
}
}
An example of a data entry...
var data = [
{address:'Rua Calheta',detail:'Restaurant',title:'Dolphin',type:'restaurant',ico:'red',lat:"37.08570947136275",long:"-8.731633722782135"}
];
I hope I've explained this half sensibly. Can anyone assist me, as I was dead chuffed I'd got this far.
2nd Additional Info for Beetroot showing how my marker and sidebar are initially setup....
data.forEach(function(mapData,idx) {
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(mapData.lat,mapData.long),
title: mapData.title,
icon: getIcon(mapData.type)
});
var link=('<a href="#"' + mapData.title +'">');
var contentHtml = "<div id='iw' class='iw2'><h3>" + link + mapData.title+"</a></h3>" + mapData.detail+"<br>"+mapData.address+"</div>";
var infowindow = new google.maps.InfoWindow({
content: contentHtml
});
google.maps.event.addListener(marker, 'click', function() {
if(lastinfowindow instanceof google.maps.InfoWindow) lastinfowindow.close();
marker.infowindow.open(map, marker);
lastinfowindow = marker.infowindow;
});
marker.locid = idx+1;
marker.infowindow = infowindow;
markers[markers.length] = marker;
var spot=('<img src="' + (getIcon(mapData.type)) + '" />');
var sideHtml = '<p class="loc" data-locid="'+marker.locid+'">'+spot+mapData.title+'</p>';
$("#locs").append(sideHtml);
if(markers.length == data.length) doFilter();
});
EDIT 02/07
The complete source after incorporating Beetroot-Beetroot's slick changes. Here in its entirety as I'm now vary aware that he can only help if he has the whole picture!
Now attempting to debug after learning I'm not such a smartass.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false& style=feature:all|element:labels|visibility:off">
</script>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
var map;
var markers = [];
var lastinfowindow;
var locIndex;
//Credit: MDN
if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
}
}
//my data ~ cutdown and local for testing
var data = [
{address:'Rua Calheta',detail:'Restaurant',title:'Dolphin',type:'restaurant',icotyp:'red',lat:"37.08570947136275",long:"-8.731633722782135"},
{address:'Rua Calheta',detail:'Cafe',title:'Cafe Calheta',type:'cafe',icotyp:'yellow',lat:"37.0858150589029",long:"-8.731550574302673"},
{address:'Rua Calheta',detail:'Bar',title:'Kellys',type:'bar',icotyp:'red',lat:"37.08583217639933",long:"-8.731239438056945"},
{address:'Rua 2nd Abril',detail:'Bar',title:'Godots',type:'bar',icotyp:'blue',lat:"37.08602046860496",long:"-8.731470108032226"}
];
// translate data type: to icon
function getIcon(type) {
switch(type) {
case "bar": return "../mapIcons/mini-blue.png";
case "restaurant": return "../mapIcons/mini-red.png";
case "cafe": return "../mapIcons/mini-yellow.png";
default: return "../mapIcons/mini-white.png";
}
}
function initialize() {
var latlng = new google.maps.LatLng(37.08597981464561, -8.730670809745788);
var myOptions = {
zoom: 18,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
// revised beetroot-beetroot 'loop' function to set markers and sidebar at the same time
var $locs = $("#locs");//Used repeatedly inside the loop.
$.each(data, function(idx, mapData) {
//Note: critical assignment of the new marker as a property of `mapData`.
mapData.marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(mapData.lat,mapData.long),
title: mapData.title,
icon: getIcon(mapData.type)
});
var link = '' + mapData.title + '';
var contentHtml = "<div id='iw' class='iw2'><h3>" + link + "</h3>" + mapData.detail + "<br>" + mapData.address + "</div>";
//What was `marker` must now be referred to as `mapData.marker`
mapData.marker.infowindow = new google.maps.InfoWindow({
content: contentHtml
});
google.maps.event.addListener(mapData.marker, 'click', function() {
if(lastinfowindow && lastinfowindow.close) lastinfowindow.close();
//`this` refers back to the clicked element; the appropriate marker
this.infowindow.open(map, this);
lastinfowindow = this.infowindow;
});
var spot = '<img src="' + (getIcon(mapData.type)) + '" />';
//Here, it's convenient to create what was `sideitem` as a jQuery object, so we can apply several jquery methods (without making an assignment).
$('<p class="loc" />')
.html(spot + mapData.title)
.appendTo($locs)
.data('mapData', mapData);//<<<<<<<< critical
});
doFilter(); //It should be possible to execute this statement when the loop is finished.
$(document).on("mouseenter", ".loc", function() {
if(lastinfowindow && lastinfowindow.close) lastinfowindow.close();
var mapData = $(this).data("mapData");
map.panTo(mapData.marker.getPosition());//<<<< direct reference to the marker avoids the need to loop.
mapData.marker.setIcon(getIcon(''));//get the default icon.
}).on("mouseleave", ".loc", function() {
var mapData = $(this).data("mapData");
mapData.marker.setIcon(getIcon(mapData.type));
}).on("click",".loc",function() {
var mapData = $(this).data("mapData");
mapData.marker.infowindow.open(map, mapData.marker);
lastinfowindow = mapData.marker.infowindow;
});
/*
Run on every change to any of the checkboxes
*/
function doFilter() {
if(lastinfowindow && lastinfowindow.close) lastinfowindow.close(); //Close last info windows if still open and new filter applied
if(!locIndex) {
locIndex = {};
//I reverse index markers to figure out the position of loc to marker index
for(var x=0, len=markers.length; x<len; x++) {
locIndex[markers[x].locid] = x;
}
}
//what's checked?
var checked = $("input[type=checkbox]:checked");
var selTypes = [];
for(var i=0, len=checked.length; i<len; i++) {
selTypes.push($(checked[i]).val());
}
for(var i=0, len=data.length; i<len; i++) {
var sideDom = "p.loc[data-locid="+(i+1)+"]";
//Only hide if length != 0
if(checked.length !=0 && selTypes.indexOf(data[i].type) < 0) {
$(sideDom).hide();
markers[locIndex[i+1]].setVisible(false);
} else {
$(sideDom).show();
markers[locIndex[i+1]].setVisible(true);
}
}
}
$(document).on("click", "input[type=checkbox]", doFilter);
}
</script>
<style type="text/css">
#container {width:920px;height:500px; margin-left:auto;margin-right:auto;}
#map_canvas {width: 700px; height: 500px;float:left;border:1px gray solid;margin-right:10px;}
/* sidebar styling */
#locs {margin-top: 0px;padding-top: 0px;margin-left: 5px;height: 500px;width:200px;overflow-y: auto;overflow-x: hidden;}
#locs img {float:left;padding-right:5px;}
.loc {border: 0;width: 200px;padding: 2px;cursor: pointer;margin:0;text-transform:uppercase;font-family:Arial, Helvetica, sans-serif;font-size:0.90em;}
/* checkbox styling */
#form {margin-top: 0px;padding-top: 0px;height: 29px;}
.label {width: 32.5%;margin: 0;padding: 4px 0 4px 4px;display: inline-block;font-family: "Trebuchet MS", Verdana, Arial, sans-serif;text-transform: uppercase;font-size: 0.75em;font-weight: bold;}
.red {color:white;background-color:red;}
.yellow {color:yellow;background-color:black;}
.blue {color:white;background-color:blue;}
/* Map info styling */
#map_canvas div#iw {width:250px;height:65px;overflow:hidden;}
#map_canvas h3 {font-size:1em; margin:0; padding:3px;}
#map_canvas .iw2 a {text-decoration:none;border-bottom:thin blue dashed;}
#map_canvas .iw2 a:hover {text-decoration:none;border-bottom:thin red solid;}
</style>
</head>
<body onLoad="initialize()">
<div id="container">
<div id="map_canvas"></div> <!-- map //-->
<div id="locs"></div> <!-- sidebar //-->
<div id="form" style="margin:0;padding:0;border:thin gray solid;width:910px">
<span class="label blue"><input type="checkbox" name="bars" value="bar">Bars</span>
<span class="label yellow"><input type="checkbox" name="cafes" value="cafe">Cafes</span>
<span class="label red"><input type="checkbox" name="restaurants" value="restaurant">Restaurants</span>
</div>
</div> <!-- end of container //-->
</body>
</html>
EDIT 3 - 03/07 - Revised initialise marker / sidebar
// BB - revised each loop function to set markers and sidebar at the same time
var $locs = $("#locs");//Used repeatedly inside the loop.
$.each(data, function(idx, mapData) {
//BB - Note: critical assignment of the new marker as a property of `mapData`.
mapData.marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(mapData.lat,mapData.long),
title: mapData.title,
icon: getIcon(mapData.type)
});
var link = '' + mapData.title + '';
var contentHtml = "<div id='iw' class='iw2'><h3>" + link + "</h3>" + mapData.detail + "<br>" + mapData.address + "</div>";
//What was `marker` must now be referred to as `mapData.marker`
mapData.marker.infowindow = new google.maps.InfoWindow({
content: contentHtml
});
google.maps.event.addListener(mapData.marker, 'click', function() {
if(lastinfowindow && lastinfowindow.close) lastinfowindow.close();
//BB - `this` refers back to the clicked element; the appropriate marker
this.infowindow.open(map, this);
lastinfowindow = this.infowindow;
});
//BB - Here, it's convenient to create what was `sideitem` as a jQuery object, so we can apply several jquery methods (without making an assignment).
var spot = '<img src="' + (getIcon(mapData.type)) + '" />';
$('<p class="loc" />')
.html(spot + mapData.title)
.appendTo($locs)
.data('mapData', mapData);//<<<<<<<< critical
//BB - At the bottom of the $.each() loop in initialize(), create and populate one array per category, as properties of markers ://
if(!markers[mapData.type]) markers[mapData.type] = [];
markers[mapData.type].push(mapData.marker);
});
// End of for/each loop
EDIT 4 - 07/07 - Revised full script for comment
<script type="text/javascript">
var map;
//var markers = [];
//object, not array. BB
var markers = {};
var lastinfowindow;
//var locIndex;
//Credit: MDN
if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function(fn, scope) {
for(var i = 0, len = this.length; i < len; ++i) {
fn.call(scope, this[i], i, this);
}
}
}
//my data ~ cutdown and local for testing
var data = [
{address:'Rua Calheta',detail:'South African & Portuguese Restaurant',title:'Dolphin',type:'restaurant',lat:"37.08570947136275",long:"-8.731633722782135"},
{address:'Rua Calheta',detail:'Poruguese Cafe / Bar',title:'Cafe Calheta',type:'cafe',lat:"37.0858150589029",long:"-8.731550574302673"},
{address:'Rua Calheta',detail:'English Bar',title:'Kellys',type:'bar',lat:"37.08583217639933",long:"-8.731239438056945"},
{address:'Rua 2nd Abril',detail:'English Bar',title:'Godots',type:'bar',lat:"37.08602046860496",long:"-8.731470108032226"},
{address:'Rua 2nd Abril',detail:'Chinese Restaurant',title:'Royal Garden',type:'restaurant',lat:"37.086164896968405",long:"-8.731738328933715"},
{address:'Rua 2nd Abril',detail:'English Bar',title:'Clives',type:'bar',lat:"37.086125",long:"-8.731374"},
{address:'Rua 2nd Abril',detail:'English Restaurant',title:'The Lime Tree',type:'restaurant',lat:"37.086125877750365",long:"-8.731588125228881"},
{address:'Praia da Luz',detail:'Portuguese Restaurant',title:'Alloro',type:'restaurant',lat:"37.09158",long:"-8.724850"},
{address:'Rua Calheta',detail:'English Cafe / Bistro',title:'Jakes',type:'cafe',lat:"37.0862601125538",long:"-8.732671737670898"},
{address:'Av dos Pescadores',detail:'English & Portuguese Restaurant',title:'Chaplins',type:'restaurant',lat:"37.08550480361006",long:"-8.730005621910095"},
{address:'Av dos Pescadores',detail:'English & Portuguese Restaurant',title:'Atlantico',type:'restaurant',lat:"37.085425634814705",long:"-8.729941248893737"},
{address:'Av dos Pescadores',detail:'Indian Restaurant',title:'Saffron',type:'restaurant',lat:"37.08534432623613",long:"-8.729884922504425"},
{address:'Av dos Pescadores',detail:'Indian Restaurant',title:'Pashmina',type:'restaurant',lat:"37.08526729697597",long:"-8.729839324951171"},
{address:'Rua Calheta',detail:'English Bar',title:'The Bull',type:'bar',lat:"37.085652442494",long:"-8.73089075088501"},
{address:'Av dos Pescadores',detail:'English & Portuguese Restaurant',title:'Galley',type:'restaurant',lat:"37.08571577732778",long:"-8.729227781295776"},
{address:'Av dos Pescadores',detail:'English & Portuguese Bar',title:'Carlos',type:'bar',lat:"37.0856306176238",long:"-8.729227781295776"}
];
// translate data.type: to icon
function getIcon(type) {
switch(type) {
case "bar": return "../mapIcons/mini-blue.png";
case "restaurant": return "../mapIcons/mini-red.png";
case "cafe": return "../mapIcons/mini-green.png";
default: return "../mapIcons/mini-white.png"; // used as current selection indicator
//default: return "../mapIcons/marker-yellow-dot.png"; // will use instead of white later
}
}
function initialize() {
var latlng = new google.maps.LatLng(37.08597981464561, -8.730670809745788);
var myOptions = {
zoom: 17,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
//-----------------------------------------------------------------------------------------
/*
Start of for/each loop
*/
var $locs = $("#locs");//Used repeatedly inside the loop.
$.each(data, function(idx, mapData) {
//BB - Note: critical assignment of the new marker as a property of `mapData`.
// section 1 - Marker construct
mapData.marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(mapData.lat,mapData.long),
title: mapData.title,
icon: getIcon(mapData.type)
});
// section 1 end
// section 2 - Infowindow construct
var link = '' + mapData.title + ''; // make a link of name
var contentHtml = "<div id='iw' class='iw2'><h3>" + link + "</h3>" + mapData.detail + "</div>"; // style info window and add detail
// What was `marker` must now be referred to as `mapData.marker`
mapData.marker.infowindow = new google.maps.InfoWindow({
content: contentHtml,
});
// section 2 end
// section 3 - Map marker click function
google.maps.event.addListener(mapData.marker, 'click', function() {
if(lastinfowindow && lastinfowindow.close) lastinfowindow.close(); // close any open infowindows
map.setZoom(18); // zoom in
map.setCenter(mapData.marker.getPosition());// centre on selection
//BB - `this` refers back to the clicked element; the appropriate marker
this.infowindow.open(map, this); // open infowindow
lastinfowindow = this.infowindow; // remember for closing this infowindow, if still open when selection changes
});
// section 3 end
// section 4 - Display Map marker and sidebar item
// BB - Here, it's convenient to create what was `sideitem` as a jQuery object, so we can apply several jquery methods (without making an assignment).
var spot = '<img src="' + (getIcon(mapData.type)) + '" />'; // sidebar copy of marker for display
$('<p class="loc" />')
.html(spot + mapData.title) // sidebar icon and name
.appendTo($locs) // add to sidebar container
.data('mapData', mapData); //<<<<<<<< critical
// BB Remove non matching from sidebar
marker.loc = $('<p class="loc" />').addClass(mapData.type).html(spot + mapData.title).data('marker', {m:marker, type:mapData.type}).appendTo($locs).get(0);
// BB - At the bottom of the $.each() loop in initialize(), create and populate one array per category, as properties of markers ://
if(!markers[mapData.type]) markers[mapData.type] = [];
markers[mapData.type].push(marker);
});
// End of for/each loop
//-----------------------------------------------------------------------------------------
} // end of initialise (?)
//-----------------------------------------------------------------------------------------
/*
Sidebar Functions
*/
$(document).on("mouseenter", ".loc", function() {
//if(lastinfowindow && lastinfowindow.close) lastinfowindow.close(); // moved to on click, avoids closing when accidently moving mouse
var mapData = $(this).data("mapData");
map.setZoom(18); // zoom in a bit
map.setCenter(mapData.marker.getPosition());// centre on selection
//map.panTo(mapData.marker.getPosition());// direct reference to the marker avoids the need to loop.
mapData.marker.setIcon(getIcon(''));//get the default icon ie. larger yellow spot.
}).on("mouseleave", ".loc", function() {
var mapData = $(this).data("mapData");
mapData.marker.setIcon(getIcon(mapData.type));//reset marker to correct type
map.setZoom(17); //rest zoom to default
map.setCenter(marker.getPosition()); // centre on map middle
}).on("click", ".loc", function() { // opens corresponding info window on map
if(lastinfowindow && lastinfowindow.close) lastinfowindow.close();
var mapData = $(this).data("mapData");
//map.setZoom(19); // zoom in more maybe
mapData.marker.infowindow.open(map, mapData.marker); // open infowindow
lastinfowindow = mapData.marker.infowindow; // remember for closing this infowindow, if still open when selection changes
})
//-----------------------------------------------------------------------------------------
/*
Run on every change to any of the checkboxes
*/
function doFilter() {
if(lastinfowindow && lastinfowindow.close) lastinfowindow.close(); // close last infowindow if still open
alert ("filter triggered");
$("input[type=checkbox]").each(function(i, checkbox) {
var markersArr = markers[checkbox.value];
if(markersArr) {
$.each(markersArr, function(i, marker) {
marker.loc.style.display = ['none', 'block'][Number(checkbox.checked)]; // don't display non selected types
marker.setVisible(checkbox.checked); // display selected type(s)
});
};
});
}
//-----------------------------------------------------------------------------------------
/*
Run on initial setup
*/
doFilter();
//-----------------------------------------------------------------------------------------
/*
fires on every checkbox change
*/
$("#form").on("click", ".cat", doFilter)
</script>
If, in the loop where the markers are created, you give each sidebar item a reference to its marker instead of the locid, then there's no need to loop to rediscover the marker on mouseenter/mouseleave.
ie, instead of setting :
//My best guess at what the statement must be.
thisloc.data("locid", id);
//Keep this line if thisloc.data("locid") is used elsewhere.
set (within the sidebar item/marker creation loop) :
var marker = ....;
var thisloc = ...;
...
data[i].marker = marker;//add a .marker property to the original dataset.
thisloc.data("itemData", data[i]);//associate the original dataset with the sidebar item
Now the mouseenter/mouseleave handlers should simplify as follows:
$(document).on("mouseenter", ".loc", function() {
if(lastinfowindow && lastinfowindow.close) lastinfowindow.close();
var data = $(this).data("itemData");
map.panTo(data.marker.getPosition());//<<<< direct reference to the marker avoids the need to loop.
data.marker.setIcon(getIcon(''));//get the default icon.
}).on("mouseleave", ".loc", function() {
var data = $(this).data("itemData");
data.marker.setIcon(getIcon(data.type));
});
Note: You shouldn't need to pan to the marker again on mouseleave.
This should answer the question posed plus other advantages.
EDIT:
OK, now I've seen the main loop, it can be revised something like this, with various mods all through :
var $locs = $("#locs");//Used repeatedly inside the loop.
$.each(data, function(idx, mapData) {
//Note: critical assignment of the new marker as a property of `mapData`.
mapData.marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(mapData.lat,mapData.long),
title: mapData.title,
icon: getIcon(mapData.type)
});
var link = '' + mapData.title + '';
var contentHtml = "<div id='iw' class='iw2'><h3>" + link + "</h3>" + mapData.detail + "<br>" + mapData.address + "</div>";
//What was `marker` must now be referred to as `mapData.marker`
mapData.marker.infowindow = new google.maps.InfoWindow({
content: contentHtml
});
google.maps.event.addListener(mapData.marker, 'click', function() {
if(lastinfowindow && lastinfowindow.close) lastinfowindow.close();
//`this` refers back to the clicked element; the appropriate marker
this.infowindow.open(map, this);
lastinfowindow = this.infowindow;
});
var spot = '<img src="' + (getIcon(mapData.type)) + '" />';
//Here, it's convenient to create what was `sideitem` as a jQuery object, so we can apply several jquery methods (without making an assignment).
$('<p class="loc" />')
.html(spot + mapData.title)
.appendTo($locs)
.data('mapData', mapData);//<<<<<<<< critical
});
doFilter();//It should be possible to execute this statement when the loop is finished.
And the corresponding mouseenter/mouseleave handlers would be :
$(document).on("mouseenter", ".loc", function() {
if(lastinfowindow && lastinfowindow.close) lastinfowindow.close();
var mapData = $(this).data("mapData");
map.panTo(mapData.marker.getPosition());//<<<< direct reference to the marker avoids the need to loop.
mapData.marker.setIcon(getIcon(''));//get the default icon.
}).on("mouseleave", ".loc", function() {
var mapData = $(this).data("mapData");
mapData.marker.setIcon(getIcon(mapData.type));
});
All untested, so may well need debugging.
EDIT2 :
The way I left it above, the array markers wasn't being populated. Now I have seen the function doFilter() I can see that markers should be populated, however it is more convenient for it to be an object rather than an array.
markers = {};//in the same scope as before
At the bottom of the $.each() loop in initialize(), create and populate one array per category, as properties of markers :
if(!markers[mapData.type]) markers[mapData.type] = [];
markers[mapData.type].push(mapData.marker);
With the markers populated in this way, you have a very simple means of identifying all markers in each category, and doFilter() will simplify enormously to :
function doFilter() {
if(lastinfowindow && lastinfowindow.close) lastinfowindow.close();
$("input[type=checkbox]").each(function(i, checkbox) {
var markersArr = markers[checkbox.value];
if(markersArr) {
$.each(markersArr, function(i, marker) {
marker.setVisible(checkbox.checked);
});
}
});
}
EDIT3
To get the sidebar entries to show/hide in sympathy with the category controls, initialize() should be as follows :
function initialize() {
var latlng = new google.maps.LatLng(37.08597981464561, -8.730670809745788);
var myOptions = {
zoom: 18,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var $locs = $("#locs");//Used repeatedly inside the loop.
var marker;
$.each(data, function(idx, mapData) {
//Note: critical assignment of the new marker as a property of `mapData`.
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(mapData.lat, mapData.long),
title: mapData.title,
icon: getIcon(mapData.type)
});
var link = '' + mapData.title + '';
var contentHtml = "<div id='iw' class='iw2'><h3>" + link + "</h3>" + mapData.detail + "<br>" + mapData.address + "</div>";
marker.infowindow = new google.maps.InfoWindow({
content: contentHtml
});
google.maps.event.addListener(marker, 'click', function() {
closeLastInfoWindow();
//`this` refers back to the clicked element; the appropriate marker
this.infowindow.open(map, this);
lastinfowindow = this.infowindow;
});
var spot = '<img src="' + (getIcon(mapData.type)) + '" />';
//Here, it's convenient to create what was `sideitem` as a jQuery object, so we can apply several jquery methods.
marker.loc = $('<p class="loc" />')
.addClass(mapData.type)
.html(spot + mapData.title)
.data('marker', {m:marker, type:mapData.type})
.appendTo($locs).get(0);
if(!markers[mapData.type]) markers[mapData.type] = [];
markers[mapData.type].push(marker);
});
$(document).on("mouseenter", ".loc", function() {
closeLastInfoWindow();
var m = $(this).data("marker").m;
map.panTo(m.getPosition());//<<<< direct reference to the marker avoids the need to loop.
m.setIcon(getIcon(''));//get the default icon.
}).on("mouseleave", ".loc", function() {
var data = $(this).data("marker");
data.m.setIcon(getIcon(data.type));
}).on("click",".loc",function() {
var m = $(this).data("marker").m;
m.infowindow.open(map, m);
lastinfowindow = m.infowindow;
});
$("#form").on("click", ".cat", doFilter);
doFilter();
}
markers[i].setIcon("currmark") won't work (sets the icon to the string "currmark"). Use the variable: markers[i].setIcon(currmark).
$(document).on("mouseleave",".loc",function() {
var thisloc = $(this).data("locid");
var currmark = getIcon("mapData.type");
for(var i=0; i<markers.length; i++) {
if(markers[i].locid == thisloc) { //get the latlong
map.panTo(markers[i].getPosition());
markers[i].setIcon(currmark);
}
}
});

close InfoWindow before open another

I have a problem with InfoWindow. I have an ajax function that retrieves data via JSON, but I can not get close InfoWindow automatically when you open another.
My code is this:
var mapOptions = {
center: new google.maps.LatLng(44.49423583832911, 11.346244544982937),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mappa_locali"),mapOptions);
$.ajax({
type:'GET',
url:"locali_json.php"+urlz,
success:function(data){
var json = JSON.parse(data);
for (var i=0; i<json.length; i++) {
point = new google.maps.LatLng(json[i].latitudine,json[i].longitudine);
var infowindow = new google.maps.InfoWindow;
infowindow.setContent(''+json[i].nome_locale+'<br>'+json[i].address);
addMarkerz(point,infowindow);
}
}
})
}
function addMarkerz(point,infowindow) {
position: point,
map: map
});
google.maps.event.addListener(marker,'mouseover',infoCallback(infowindow, marker));
markers.push(marker);
infos.push(infowindow);
}
function infoCallback(infowindow, marker) {
return function() {
infowindow.close();
infowindow.open(map, marker);
};
}
Does anyone know where decreased mistake? Or do you have any advice for me?
The suggestion is only create one infowindow (in the global scope), reuse it and change its contents when a marker is clicked, close it if the user clicks on the map.
code snippet (removes the dependency on the AJAX call):
// global variables
var map;
var markers = [];
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(44.49423583832911, 11.346244544982937),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mappa_locali"), mapOptions);
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
point = new google.maps.LatLng(json[i].latitudine, json[i].longitudine);
var infowindowHtml = '' + json[i].nome_locale + '<br>' + json[i].address;
addMarkerz(point, infowindowHtml);
}
}
function addMarkerz(point, infowindowHtml) {
var marker = new google.maps.Marker({
position: point,
map: map
});
google.maps.event.addListener(marker, 'mouseover', infoCallback(infowindowHtml, marker));
markers.push(marker);
}
function infoCallback(infowindowHtml, marker) {
return function() {
infowindow.close();
// update the content of the infowindow before opening it
infowindow.setContent(infowindowHtml)
infowindow.open(map, marker);
};
}
var data = JSON.stringify([{
latitudine: 44.494887,
longitudine: 11.3426163,
id_locale: "0",
nome_locale: "Bologna",
address: "Bologna, Italy"
}, {
latitudine: 44.4946615,
longitudine: 11.314634999999953,
id_locale: "0",
nome_locale: "Quartiere Saragozza",
address: "Quartiere Saragozza, Bologna, Italy"
}]);
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#mappa_locali {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="mappa_locali"></div>
function infoCallback(infowindow, marker) {
return function() {
infowindow.close();
infowindow.open(map, marker);
};
}
should be changed to
function infoCallback(infowindow, marker) {
return function() {
//Close active window if exists
if (activeWindow != null) {
activeWindow.close();
}
//Open new window
infowindow.open(map,marker);
//Store new window in global variable
activeWindow = infowindow;
};
}
and declare activeWindow as a global variable in your .js file as var activeWindow.
I think I have a simple solution. I just save the last open mark. On the next click first of all I close the last mark.
var markers = [];
var infowindows = [];
function addMarkes(facilityID) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < variants.length; i++) {
var v = variants[i];
var position = new google.maps.LatLng(v.Lat, v.Long);
bounds.extend(position);
markers[i] = new google.maps.Marker({
position: position,
title: v.Title,
map: map,
animation: google.maps.Animation.DROP,
icon: v.Icon,
infoWindowIndex: i //synchronize with infoWindows
});
var localContent = '<div><span class="address">' + v.Address + '</span></div>';
infowindows[i] = new google.maps.InfoWindow({
content: localContent
});
//Just for multiple marks.
if (variants.length > 0) {
var lastOpen = -1; //Save the last open mark
google.maps.event.addListener(markers[i], 'click', function (innerKey) {
return function () {
//Close the last mark.
if (lastOpen > -1) {
infowindows[lastOpen].close();
}
infowindows[innerKey].open(map, markers[innerKey]);
lastOpen = innerKey;
}
}(i));
}
}
map.fitBounds(bounds);
}

Google Map Tooltip

I wonder whether someone may be able to help me please.
I've been working on a tooltip for markers that I place on a google map. I can get this to work showing the information that I would like the user to see, in this case the fields name and address, so the code line is title: name+address.
Could someone please tell me how I could put a space between these so the tooltip would read 'name address' rather than 'nameaddress'.
I've tried all sorts of things using e.g.title: name'_'+ address, title: name' '+address and I can't get it to work.
Any help would be greatly appreciated.
Many thanks
Chris
You can try this
name + ' ' + address
NB: you need a space in the quotes and a + on either side.
I use this function to initialize started values:
//Inicialize map values
function initialize() {
latCenterMap=41.50347;
lonCenterMap=-5.74638;
zommCeneterMap=14;
latPoint=41.50347;
lonPoint=-5.74638;
//Values default initialize
var latlng = new google.maps.LatLng(latCenterMap, lonCenterMap);
var mapOptions = {
zoom: zommCeneterMap,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas_'), mapOptions);
codePoint(map, lat, lon);
}
I used this function to set values point position into map
//Get position by Latitude and Longitude
function codePoint(map, lat, lon) {
var latlng = new google.maps.LatLng(parseFloat(lat), parseFloat(lon));
var title = "Your text";
var iconPoint = new google.maps.MarkerImage('images/pointBlue.png',
//Measure image
new google.maps.Size(25,25),
new google.maps.Point(0,0),
//Half measure image
new google.maps.Point(12.5,12.5)
);
marker = new google.maps.Marker({
position: latlng,
map: map,
icon: iconPoint,
tooltip: title
});
customTooltip(marker);
}
I use this function to create a tooltip to point position
//TOOLTIP
function customTooltip(marker){
// Constructor function
function Tooltip(opts, marker) {
// Initialization
this.setValues(opts);
this.map_ = opts.map;
this.marker_ = marker;
var div = this.div_ = document.createElement("div");
// Class name of div element to style it via CSS
div.className = "tooltip";
this.markerDragging = false;
}
Tooltip.prototype = {
// Define draw method to keep OverlayView happy
draw: function() {},
visible_changed: function() {
var vis = this.get("visible");
this.div_.style.visibility = vis ? "visible" : "hidden";
},
getPos: function(e) {
var projection = this.getProjection();
// Position of mouse cursor
var pixel = projection.fromLatLngToDivPixel(e.latLng);
var div = this.div_;
// Adjust the tooltip's position
var gap = 15;
var posX = pixel.x + gap;
var posY = pixel.y + gap;
var menuwidth = div.offsetWidth;
// Right boundary of the map
var boundsNE = this.map_.getBounds().getNorthEast();
boundsNE.pixel = projection.fromLatLngToDivPixel(boundsNE);
if (menuwidth + posX > boundsNE.pixel.x) {
posX -= menuwidth + gap;
}
div.style.left = posX + "px";
div.style.top = posY + "px";
if (!this.markerDragging) {
this.set("visible", true);
}
},
// This is added to avoid using listener (Listener is not working when Map is quickly loaded with icons)
getPos2: function(latLng) {
var projection = this.getProjection();
// Position of mouse cursor
var pixel = projection.fromLatLngToDivPixel(latLng);
var div = this.div_;
// Adjust the tooltip's position
var gap = 5;
var posX = pixel.x + gap;
var posY = pixel.y + gap;
var menuwidth = div.offsetWidth;
// Right boundary of the map
var boundsNE = this.map_.getBounds().getNorthEast();
boundsNE.pixel = projection.fromLatLngToDivPixel(boundsNE);
if (menuwidth + posX > boundsNE.pixel.x) {
posX -= menuwidth + gap;
}
div.style.left = posX + "px";
div.style.top = posY + "px";
if (!this.markerDragging) {
this.set("visible", true);
}
},
addTip: function() {
var me = this;
var g = google.maps.event;
var div = me.div_;
div.innerHTML = me.get("text").toString();
// Tooltip is initially hidden
me.set("visible", false);
// Append the tooltip's div to the floatPane
me.getPanes().floatPane.appendChild(this.div_);
// In IE this listener gets randomly lost after it's been cleared once.
// So keep it out of the listeners array.
g.addListener(me.marker_, "dragend", function() {
me.markerDragging = false; });
// Register listeners
me.listeners = [
// g.addListener(me.marker_, "dragend", function() {
// me.markerDragging = false; }),
g.addListener(me.marker_, "position_changed", function() {
me.markerDragging = true;
me.set("visible", false); }),
g.addListener(me.map_, "mousemove", function(e) {
me.getPos(e); })
];
},
removeTip: function() {
// Clear the listeners to stop events when not needed.
if (this.listeners) {
for (var i = 0, listener; listener = this.listeners[i]; i++) {
google.maps.event.removeListener(listener);
}
delete this.listeners;
}
// Remove the tooltip from the map pane.
var parent = this.div_.parentNode;
if (parent) parent.removeChild(this.div_);
}
};
function inherit(addTo, getFrom) {
var from = getFrom.prototype; // prototype object to get methods from
var to = addTo.prototype; // prototype object to add methods to
for (var prop in from) {
if (typeof to[prop] == "undefined") to[prop] = from[prop];
}
}
// Inherits from OverlayView from the Google Maps API
inherit(Tooltip, google.maps.OverlayView);
var tooltip = new Tooltip({map: map}, marker);
tooltip.bindTo("text", marker, "tooltip");
google.maps.event.addListener(marker, 'mouseover', function() {
tooltip.addTip();
tooltip.getPos2(marker.getPosition());
});
google.maps.event.addListener(marker, 'mouseout', function() {
tooltip.removeTip();
});
}
I use this style to css file
//CSS
.tooltip {
position:absolute;
top:0;
left:0;
z-index: 300;
width: 11.5em;
padding: 5px;
font-size: 12pt;
font-family: klavika;
color: #fff;
background-color: #04A2CA;
border-radius: 10px;
box-shadow: 2px 2px 5px 0 rgba(50, 50, 50, 0.75);
}

Resources