I am building a google map and I would like to have some information show when the mouse is over a marker and then more detailed information when the user clicks on the map. I have found a solution for it by adding two infowindows.
html
<div id="map-canvas"></div>
css
#map-canvas {
height: 400px;
width: 100%;
}
js
"use strict";
// variable to hold a map
var map;
// variable to hold current active InfoWindow
var activeInfoWindow ;
// ------------------------------------------------------------------------------- //
// initialize function
// ------------------------------------------------------------------------------- //
function initialize() {
// map options - lots of options available here
var mapOptions = {
zoom : 6,
draggable: true,
center : new google.maps.LatLng(43.637599, 1.319152),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// create map in div called map-canvas using map options defined above
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// define three Google Map LatLng objects representing geographic points
var barca = new google.maps.LatLng(41.387042, 2.181382);
var toulouse = new google.maps.LatLng(43.637599, 1.319152);
var madrid = new google.maps.LatLng(40.424803, -3.698083);
// place markers
fnPlaceMarkers(barca,"Barcelona");
fnPlaceMarkers(toulouse,"Toulouse");
fnPlaceMarkers(madrid,"Madrid");
}
// ------------------------------------------------------------------------------- //
// create markers on the map
// ------------------------------------------------------------------------------- //
function fnPlaceMarkers(myLocation,myCityName){
var marker = new google.maps.Marker({
position : myLocation
});
//var lat_lng = {lat: 17.08672, lng: 78.42444};
// Renders the marker on the specified map
marker.setMap(map);
// create an InfoWindow - for mouseover
var infoWnd = new google.maps.InfoWindow();
// create an InfoWindow - for mouseclick
var infoWnd2 = new google.maps.InfoWindow(
{
//pixelOffset: new google.maps.Size(200,0)
//position: {40.424803, -3.698083}
//content: contentString
}
);
// -----------------------
// ON MOUSEOVER
// -----------------------
// add content to your InfoWindow
infoWnd.setContent('<div class="scrollFix">' + 'Welcome to ' + myCityName + ' This appears when you put your mouse over a marker</div>');
// add listener on InfoWindow for mouseover event
google.maps.event.addListener(marker, 'mouseover', function() {
// Close active window if exists - [one might expect this to be default behaviour no?]
if(activeInfoWindow != null) activeInfoWindow.close();
// Close info Window on mouseclick if already opened
infoWnd2.close();
// Open new InfoWindow for mouseover event
infoWnd.open(map, marker);
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd;
});
// on mouseout (moved mouse off marker) make infoWindow disappear
google.maps.event.addListener(marker, 'mouseout', function() {
infoWnd.close();
});
// --------------------------------
// ON MARKER CLICK - (Mouse click)
// --------------------------------
// add content to InfoWindow for click event
infoWnd2.setContent('<div class="scrollFix">' + 'Welcome to ' + myCityName + '. <br/> This appears when you click on marker</div>');
// add listener on InfoWindow for click event
google.maps.event.addListener(marker, 'click', function() {
//Close active window if exists - [one might expect this to be default behaviour no?]
if(activeInfoWindow != null) activeInfoWindow.close();
// Open InfoWindow - on click
infoWnd2.open(map, marker);
// Close "mouseover" infoWindow
infoWnd.close();
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd2;
});
}
// ------------------------------------------------------------------------------- //
// initial load
// ------------------------------------------------------------------------------- //
google.maps.event.addDomListener(window, 'load', initialize);
It works well and you can see it here:
https://codepen.io/anon/pen/JJLVNB
but I would like to improve this. I saw something that I really like. How can I add an html infowindow in the top left of the google maps like they do on booking.com (img below) on clicking the marker. When you are inside a location you can click on "Show on map" and it will show this feature that I like.
How can I create this feature of showing an infowindow on hover and then on click another one always placed at the top left?
Look at CSS cards here. You can also set the position of this div to fixed. I'd suggest you use the meta attribute viewport to help it be optimizable for mobile screens.
You can use javascript ot change the visibilty of the card when user clicks on a marker to be visible and to become hidden whenever he clicks elsewhere. Also, the content to the card can be sent from the same js function.
Since you said that your requirement is to place it on top:0 and left:0, there is a method to do that.
You display the content on a div with class=scrollFix. The entire div is it's 4th parent.
add the below code inside the eventlistener of marker -> click where you generate the info box.
1. jQuery
$(".scrollFix")[0].parentNode.parentNode.parentNode.parentNode.style.top="0px";
$(".scrollFix")[0].parentNode.parentNode.parentNode.parentNode.style.left="0";
Snippet
"use strict";
// variable to hold a map
var map;
// variable to hold current active InfoWindow
var activeInfoWindow ;
// ------------------------------------------------------------------------------- //
// initialize function
// ------------------------------------------------------------------------------- //
function initialize() {
// map options - lots of options available here
var mapOptions = {
zoom : 6,
draggable: true,
center : new google.maps.LatLng(43.637599, 1.319152),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// create map in div called map-canvas using map options defined above
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// define three Google Map LatLng objects representing geographic points
var barca = new google.maps.LatLng(41.387042, 2.181382);
var toulouse = new google.maps.LatLng(43.637599, 1.319152);
var madrid = new google.maps.LatLng(40.424803, -3.698083);
// place markers
fnPlaceMarkers(barca,"Barcelona");
fnPlaceMarkers(toulouse,"Toulouse");
fnPlaceMarkers(madrid,"Madrid");
}
// ------------------------------------------------------------------------------- //
// create markers on the map
// ------------------------------------------------------------------------------- //
function fnPlaceMarkers(myLocation,myCityName){
var marker = new google.maps.Marker({
position : myLocation
});
//var lat_lng = {lat: 17.08672, lng: 78.42444};
// Renders the marker on the specified map
marker.setMap(map);
// create an InfoWindow - for mouseover
var infoWnd = new google.maps.InfoWindow();
// create an InfoWindow - for mouseclick
var infoWnd2 = new google.maps.InfoWindow(
{
//pixelOffset: new google.maps.Size(200,0)
//position: {40.424803, -3.698083}
//content: contentString
}
);
// -----------------------
// ON MOUSEOVER
// -----------------------
// add content to your InfoWindow
infoWnd.setContent('<div class="scrollFix">' + 'Welcome to ' + myCityName + ' This appears when you put your mouse over a marker</div>');
// add listener on InfoWindow for mouseover event
google.maps.event.addListener(marker, 'mouseover', function() {
// Close active window if exists - [one might expect this to be default behaviour no?]
if(activeInfoWindow != null) activeInfoWindow.close();
// Close info Window on mouseclick if already opened
infoWnd2.close();
// Open new InfoWindow for mouseover event
infoWnd.open(map, marker);
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd;
});
// on mouseout (moved mouse off marker) make infoWindow disappear
google.maps.event.addListener(marker, 'mouseout', function() {
infoWnd.close();
});
// --------------------------------
// ON MARKER CLICK - (Mouse click)
// --------------------------------
// add content to InfoWindow for click event
infoWnd2.setContent('<div class="scrollFix">' + 'Welcome to ' + myCityName + '. <br/> This appears when you click on marker</div>');
// add listener on InfoWindow for click event
google.maps.event.addListener(marker, 'click', function() {
//Close active window if exists - [one might expect this to be default behaviour no?]
if(activeInfoWindow != null) activeInfoWindow.close();
// Open InfoWindow - on click
infoWnd2.open(map, marker);
$(".scrollFix")[0].parentNode.parentNode.parentNode.parentNode.style.top="0";
$(".scrollFix")[0].parentNode.parentNode.parentNode.parentNode.style.left="0";
// Close "mouseover" infoWindow
infoWnd.close();
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd2;
});
}
// ------------------------------------------------------------------------------- //
// initial load
// ------------------------------------------------------------------------------- //
google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas, #side-bar {
height: 400px;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
2. JavaScript
document.getElementsByClassName("scrollFix")[0].parentNode.parentNode.parentNode.parentNode.style.top="0";
document.getElementsByClassName("scrollFix")[0].parentNode.parentNode.parentNode.parentNode.style.left="0";
Snippet
"use strict";
// variable to hold a map
var map;
// variable to hold current active InfoWindow
var activeInfoWindow ;
// ------------------------------------------------------------------------------- //
// initialize function
// ------------------------------------------------------------------------------- //
function initialize() {
// map options - lots of options available here
var mapOptions = {
zoom : 6,
draggable: true,
center : new google.maps.LatLng(43.637599, 1.319152),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// create map in div called map-canvas using map options defined above
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// define three Google Map LatLng objects representing geographic points
var barca = new google.maps.LatLng(41.387042, 2.181382);
var toulouse = new google.maps.LatLng(43.637599, 1.319152);
var madrid = new google.maps.LatLng(40.424803, -3.698083);
// place markers
fnPlaceMarkers(barca,"Barcelona");
fnPlaceMarkers(toulouse,"Toulouse");
fnPlaceMarkers(madrid,"Madrid");
}
// ------------------------------------------------------------------------------- //
// create markers on the map
// ------------------------------------------------------------------------------- //
function fnPlaceMarkers(myLocation,myCityName){
var marker = new google.maps.Marker({
position : myLocation
});
//var lat_lng = {lat: 17.08672, lng: 78.42444};
// Renders the marker on the specified map
marker.setMap(map);
// create an InfoWindow - for mouseover
var infoWnd = new google.maps.InfoWindow();
// create an InfoWindow - for mouseclick
var infoWnd2 = new google.maps.InfoWindow(
{
//pixelOffset: new google.maps.Size(200,0)
//position: {40.424803, -3.698083}
//content: contentString
}
);
// -----------------------
// ON MOUSEOVER
// -----------------------
// add content to your InfoWindow
infoWnd.setContent('<div class="scrollFix">' + 'Welcome to ' + myCityName + ' This appears when you put your mouse over a marker</div>');
// add listener on InfoWindow for mouseover event
google.maps.event.addListener(marker, 'mouseover', function() {
// Close active window if exists - [one might expect this to be default behaviour no?]
if(activeInfoWindow != null) activeInfoWindow.close();
// Close info Window on mouseclick if already opened
infoWnd2.close();
// Open new InfoWindow for mouseover event
infoWnd.open(map, marker);
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd;
});
// on mouseout (moved mouse off marker) make infoWindow disappear
google.maps.event.addListener(marker, 'mouseout', function() {
infoWnd.close();
});
// --------------------------------
// ON MARKER CLICK - (Mouse click)
// --------------------------------
// add content to InfoWindow for click event
infoWnd2.setContent('<div class="scrollFix">' + 'Welcome to ' + myCityName + '. <br/> This appears when you click on marker</div>');
// add listener on InfoWindow for click event
google.maps.event.addListener(marker, 'click', function() {
//Close active window if exists - [one might expect this to be default behaviour no?]
if(activeInfoWindow != null) activeInfoWindow.close();
// Open InfoWindow - on click
infoWnd2.open(map, marker);
document.getElementsByClassName("scrollFix")[0].parentNode.parentNode.parentNode.parentNode.style.top="0";
document.getElementsByClassName("scrollFix")[0].parentNode.parentNode.parentNode.parentNode.style.left="0";
// Close "mouseover" infoWindow
infoWnd.close();
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd2;
});
}
// ------------------------------------------------------------------------------- //
// initial load
// ------------------------------------------------------------------------------- //
google.maps.event.addDomListener(window, 'load', initialize);
#map-canvas, #side-bar {
height: 400px;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
Related
I have a page where I show an image within some defined dimensions. I now want to invoke Google maps on a button click and show it within that dimensions itself. How can I do it in JavaScript and Angular JS?
P.S. I suppose it can be done by creating new JSP and link it to the button. But I want to update only the image portion not the whole page since it will take more time to load.
"use strict";
angular.module('app', [])
.controller('ctrl', ['$scope', function($scope){
// variable to hold a map
var map;
// variable to hold current active InfoWindow
var activeInfoWindow ;
// ------------------------------------------------------------------------------- //
// initialize function
// ------------------------------------------------------------------------------- //
// map options - lots of options available here
var mapOptions = {
zoom : 8,
draggable: true,
center : new google.maps.LatLng(37.5622, 22.6141),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
// create map in div called map-canvas using map options defined above
map = new google.maps.Map(document.getElementById("googleMap"), mapOptions);
// define two Google Map LatLng objects representing geographic points
var kalamata = new google.maps.LatLng(37.0422, 22.1141);
var athens = new google.maps.LatLng(37.9833, 23.7333);
// place two markers
fnPlaceMarkers(kalamata,"Kalamata");
fnPlaceMarkers(athens,"Athens");
window.setTimeout(function(){
google.maps.event.trigger(map, 'resize');
},10);
$scope.container = true;
$scope.toggle = function(){
$scope.container = !$scope.container;
};
// ------------------------------------------------------------------------------- //
// create markers on the map
// ------------------------------------------------------------------------------- //
function fnPlaceMarkers(myLocation,myCityName){
var marker = new google.maps.Marker({
position : myLocation
});
// Renders the marker on the specified map
marker.setMap(map);
// create an InfoWindow
var infoWnd = new google.maps.InfoWindow();
// add content to your InfoWindow
infoWnd.setContent('<div class="scrollFix">' + 'Welcome to ' + myCityName + '</div>');
// add listener on InfoWindow - close last infoWindow before opening new one
google.maps.event.addListener(marker, 'mouseover', function() {
//Close active window if exists - [one might expect this to be default behaviour no?]
if(activeInfoWindow != null) activeInfoWindow.close();
// Open InfoWindow
infoWnd.open(map, marker);
// Store new open InfoWindow in global variable
activeInfoWindow = infoWnd;
});
}
}]);
<img src=<%=request.getContextPath()%>/resources/images/io6.jpg style="width: 1245px; height: 290px;" ng-show="container">
<div id="googleMap" style="width:1245px;height:290px; display: inline-block;" ng-show="!container"></div>
you can just hide the image on button click and show google map
<img src="dummy.jpg" ng-show="!container">
<div id="googleMap" ng-show="container"></div>
<button ng-click="toggle()">Toggle</button>
$scope.toggle = function() {
$scope.container = !$scope.container;
if($scope.container){
setTimeout(function( {google.maps.event.trigger(map, 'resize')});
}
};
example here
I added code for tool tip display when hovering the pointers in the google map.It is showing the tool tip but the content is "undefined". How can put the corresponding content related to the pointer into the tool tip box.The code is :
function initialize() {
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(29.7,-95.4),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("salon_map"), myOptions);
var locations = [
__newmapdetls__
];
for (var i = 0; i < locations.length; i++) {
var location = locations[i];
var image = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="+location[3]+"|FF0000|000000",
new google.maps.Size(20, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34));
var myLatLng = new google.maps.LatLng(location[1], location[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: location[0],
zIndex: location[3],
tooltip:"testinggg"+i
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow1.open(map, this);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow1.close(map, this);
});
var infowindow1 = new google.maps.InfoWindow({
content: "'"+this.tooltip+"'"
});
}
}
Also url is : http://myshopsalon.com/find-a-shop-salon
A couple of things I noticed when looking at your page source:
Your page is loading both jQuery 1.10.1 and 1.7.2. But it isn't using noConflict(). So these two jQuery versions are stepping on each other.
You're also loading three copies of the Maps API: two copies of version 3 and a copy of the deprecated version 2 API.
Now to your question:
Use a closure to save your variables for each iteration of the marker loop. You can do this by simply calling a function in each iteration.
Instead of using this when you call infowindow.open(), use marker. (this and marker may be the same in this context, but use marker for consistency.)
The .close() method of an infowindow does not take any parameters.
Don't set the tooltip property when you create the marker. That may work, but it isn't documented that you can add your own properties in this fashion. Instead, simply use a local variable or parameter for tooltip.
I would create the infowindow before adding the event listeners. This will actually work fine in either order (since the event listeners are asynchronous), but it looks better to see the infowindow created first.
So, change your for loop to:
for (var i = 0; i < locations.length; i++) {
addMarker( locations[i], "testinggg" + i );
}
function addMarker( location, tooltip ) {
var image = new google.maps.MarkerImage(
"http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="+location[3]+"|FF0000|000000",
new google.maps.Size(20, 34),
new google.maps.Point(0, 0),
new google.maps.Point(10, 34)
);
var myLatLng = new google.maps.LatLng(location[1], location[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: location[0],
zIndex: location[3]
});
var infowindow = new google.maps.InfoWindow({
content: "'" + tooltip + "'"
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow.close();
});
}
That said, you may not like the result you get when you open an infowindow in response to moving the mouse over a marker. What if the marker is near the top of the window? The page will immediately move to make the infowindow fit on the screen, and now the marker won't be under the mouse any more.
You're already setting the title property when you create the marker. This should cause a normal browser tooltip to appear when the mouse is hovered over the marker, and it won't cause the map to move as the infowindow may do. Any reason not to just use that tooltip instead of the infowindow? You could just remove all of the infowindow code, or let the infowindow open on a click as it normally would.
Set the content of the infowindow onmouseover(you may access there the tooltip-property of the specific marker)
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow1.setContent(this.tooltip);
infowindow1.open(map, this);
});
the initializing of infowindow1 move to outside the loop and leave the arguments empty.
Use the below code:
var infowindow1 = new google.maps.InfoWindow({
content: "'"+marker.tooltip+"'"
});
EDIETD:
var contentString = "testinggg"+i;
var infowindow1[i] = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image,
title: location[0],
zIndex: location[3],
tooltip:"testinggg"+i
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow1[i].open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
infowindow1[i].close(map, marker);
});
You can not get the property of marker in the info window. So you need to define the content in other variable.
I have an application using Google maps, currently I have a number of markers added to the page and clicking on them opens up a info window.
I also have a pagniated list of results which I would like to open the corresponding info window when clicked. Currently clicking on one of these anchors opens all of the info windows, but this is as far as I can get currently.
I have a position marker function:
positionMarkers: function(lat, lng, user) {
var marker = new google.maps.Marker({
animation: google.maps.Animation.DROP,
position: new google.maps.LatLng(lat, lng),
map: map
});
if (caption == null) {
var caption = 'No caption available';
} else {
var caption = caption.text;
}
var contentString = '<div class="infoWindow"><h2>' + user + '</h2></div>';
var infowindow = new google.maps.InfoWindow({
content: contentString,
maxWidth: 284
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
$('.instaframe').bind('click', function(){
infowindow.open(map, marker);
});
}
The trouble I am having is with the bind function towards the end of the snippet. I am not sure where to go to bind the click event with just the marker being added each time the positionMarkers function runs.
Marker one
Marker two
Marker three
Help would be greatly apprecaited.
I'm playing around with Google maps for the first time, so I looked at a nice tutorial over at CSS Tricks: http://css-tricks.com/google-maps-slider/ I like working with jQuery better than pure JS, and this tutorial makes a nice way to click on a place in a list to display the marker in the map.
I liked it that way, but I need to add infowindows to the marker. Which I did, but when I click on a place on the list and the map pans away, the infowindow stays open! I think it's because I need to attach the infowindow.close() to the event of clicking on a "#locations li".
Here's my code, which runs on document.ready:
$(function() {
var chicago = new google.maps.LatLng(41.924832, -87.697456),
pointToMoveTo,
first = true,
curMarker = new google.maps.Marker({}),
$el;
var myOptions = {
zoom: 10,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map($("#map_canvas")[0], myOptions);
$("#locations li").click(function() {
$el = $(this);
if (!$el.hasClass("hover")) {
$("#locations li").removeClass("hover");
$el.addClass("hover");
if (!first) {
// Clear current marker
curMarker.setMap();
// Set zoom back to Chicago level
// map.setZoom(10);
}
// Move (pan) map to new location
function move(){
pointToMoveTo = new google.maps.LatLng($el.attr("data-geo-lat"), $el.attr("data-geo-long"));
map.panTo(pointToMoveTo);
}
move();
// Add new marker
curMarker = new google.maps.Marker({
position: pointToMoveTo,
map: map
});
// Infowindow: contenido
var contentString = '<p>'+$el.find("h3").html()+'</p>';
contentString += 'hola' ;
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50),
content: contentString
});
// On click, zoom map
google.maps.event.addListener(curMarker, 'click', function() {
//map.setZoom(14);
infowindow.open(map,curMarker);
});
It looks like you're creating a new InfoWindow for each marker. Quoting from the Google Maps API Docs:
If you only want one info window to display at a time (as is the behavior on Google Maps), you need only create one info window, which you can reassign to different locations or markers upon map events (such as user clicks).
Therefore, you may simply want to create one InfoWindow object just after you initialize your map, and then handle the click event handler as follows:
google.maps.event.addListener(curMarker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, curMarker);
});
Then the InfoWindow should automatically close when you click on a new marker without having to call the close() method.
I need to have only one InfoWindow open on my Google Map. I need to close all other InfoWindows before I open a new one.
Can someone show me how to do this?
You need to create just one InfoWindow object, keep a reference to it, and reuse if for all the markers. Quoting from the Google Maps API Docs:
If you only want one info window to display at a time (as is the behavior on Google Maps), you need only create one info window, which you can reassign to different locations or markers upon map events (such as user clicks).
Therefore, you may simply want to create the InfoWindow object just after you initialize your map, and then handle the click event handlers of your markers as follows. Let's say you have a marker called someMarker:
google.maps.event.addListener(someMarker, 'click', function() {
infowindow.setContent('Hello World');
infowindow.open(map, this);
});
Then the InfoWindow should automatically close when you click on a new marker without having to call the close() method.
Create your infowindow out of the scope so that you can share it.
Here is a simple example:
var markers = [AnArrayOfMarkers];
var infowindow = new google.maps.InfoWindow();
for (var i = 0, marker; marker = markers[i]; i++) {
google.maps.event.addListener(marker, 'click', function(e) {
infowindow.setContent('Marker position: ' + this.getPosition());
infowindow.open(map, this);
});
}
I had the same problem but the best answer didn't solve it completely, what I had to do in my for statement was using the this relating to my current marker. Maybe this helps someone.
for(var i = 0; i < markers.length; i++){
name = markers[i].getAttribute("name");
address = markers[i].getAttribute("address");
point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
contentString = '<div style="font-family: Lucida Grande, Arial, sans-serif;>'+'<div><b>'+ name +'</b></div>'+'<div>'+ address +'</div>';
marker = new google.maps.Marker({
map: map,
position: point,
title: name+" "+address,
buborek: contentString
});
google.maps.event.addListener(marker, 'click', function(){
infowindow.setContent(this.buborek);
infowindow.open(map,this);
});
marker.setMap(map);
}
a tad late, but I managed to have only one infowindow open by maken infowindow a global variable.
var infowindow = new google.maps.InfoWindow({});
then inside the listner
infowindow.close();
infowindow = new google.maps.InfoWindow({
content: '<h1>'+arrondissement+'</h1>'+ gemeentesFiltered
});
infowindow.open(map, this);
Declare a globar var selectedInfoWindow; and use it to hold the opened info window:
var infoWindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
//Check if there some info window selected and if is opened then close it
if (selectedInfoWindow != null && selectedInfoWindow.getMap() != null) {
selectedInfoWindow.close();
//If the clicked window is the selected window, deselect it and return
if (selectedInfoWindow == infoWindow) {
selectedInfoWindow = null;
return;
}
}
//If arrive here, that mean you should open the new info window
//because is different from the selected
selectedInfoWindow = infoWindow;
selectedInfoWindow.open(map, marker);
});
You need to keep track of your previous InfoWindow object and call the close method on it when you handle the click event on a new marker.
N.B It is not necessary to call close on the shared info window object, calling open with a different marker will automatically close the original. See Daniel's answer for details.
Basically you want one function that keeps reference to one new InfoBox() => delegate the onclick event.
While creating your markers (in a loop) use bindInfoBox(xhr, map, marker);
// #param(project): xhr : data for infoBox template
// #param(map): object : google.maps.map
// #param(marker): object : google.maps.marker
bindInfoBox: (function () {
var options = $.extend({}, cfg.infoBoxOptions, { pixelOffset: new google.maps.Size(-450, -30) }),
infoBox = new window.InfoBox(options);
return function (project, map, marker) {
var tpl = renderTemplate(project, cfg.infoBoxTpl); // similar to Mustache, Handlebars
google.maps.event.addListener(marker, 'click', function () {
infoBox.setContent(tpl);
infoBox.open(map, marker);
});
};
}())
var infoBox is assigned asynchronously and kept in memory. Every time you call bindInfoBox() the return function will be called instead. Also handy to pass the infoBoxOptions only once!
In my example I've had to add an extra param to the map as my initialization is delayed by tab events.
InfoBoxOptions
Here is a solution that doesn't need to create only one infoWindow to reuse it. You can continue creating many infoWindows, the only thing you need is to build a closeAllInfoWindows function, and call it before open a new infowindow.
So, keeping your code, you just need to:
Create a global array to store all the infoWindows
var infoWindows = [];
Store each new infoWindow in the array, just after the infoWindow = new...
infoWindows.push(infoWindow);
Create the closeAllInfoWindows function
function closeAllInfoWindows() {
for (var i=0;i<infoWindows.length;i++) {
infoWindows[i].close();
}
}
In your code, call to closeAllInfoWindows() just before open the infoWindow.
Regards,
One smart easy way to do this with jQuery is the following :
google.maps.event.addListener(marker, 'click', function (e) {
jQuery(".gm-ui-hover-effect").click();
marker.info.open(map, this);
});
It will click on all the closing buttons amongst your tooltips.
My approach allows you to toggle the infoWindow as well.
Global space
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(contentString);
var lastInfoWindow;
Local space
marker.addListener("click", (e) => {
if (lastInfoWindow === e.domEvent.srcElement) {
infoWindow.close();
lastInfoWindow = null;
} else {
infoWindow.open({
anchor: marker,
map,
shouldFocus: false,
});
lastInfoWindow = e.domEvent.srcElement;
}
});
Solved it this way:
function window(content){
google.maps.event.addListener(marker,'click', (function(){
infowindow.close();
infowindow = new google.maps.InfoWindow({
content: content
});
infowindow.open(map, this);
}))
}
window(contentHtml);
Google Maps allows you to only have one info window open. So if you open a new window, then the other one closes automatically.