Replace image content with Google Maps - javascript

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

Related

Google Maps markerClusterer.MarkerClusterer not working with geoJSON

Any ideas why my markers aren't clustering? I've tried many different ways and nothing will make them cluster. I realize there might be something wrong with the arguments I'm passing the markerClusterer but I can't find a way to make it work with anything. There's also little to no documentation on markerClusterer.MarkerClusterer (which is required when using unpkg).
function initMap() {
//set map options
var myMapOptions = {
center: {lat: 40.7498024, lng: -73.9774375},
zoom: 12,
}
//fill the html div with a map and pass in map options
var myNewMap = new google.maps.Map(document.getElementById('mymap'), myMapOptions);
//pass in data
myNewMap.data.loadGeoJson('missedConnections.geojson');
//define popup windows
var infowindow = new google.maps.InfoWindow({maxWidth: 750, autopanMargin: 10,});
//create new popup windows on marker click
myNewMap.data.addListener('click', function(event) {
console.log(event);
// set variables
let videourl = event.feature.getProperty('videoURL');
//padding/margin is wonky on mobile vs desktop
let html = '<video style="padding-bottom: 5px; padding-right: 3px;" preload="none" autoplay width=" 90%"><source src="' + videourl + '"></video>';
// show the html variable in the infowindow
infowindow.setContent(html);
infowindow.setPosition(event.latLng);
infowindow.setOptions({pixelOffset: new google.maps.Size(0, -30)});
// move the infowindow up 42 pixels to the top of the default marker icon
infowindow.open(myNewMap);
});
new markerClusterer.MarkerClusterer({myNewMap.data, myNewMap});
}
First, you are using object shorthand incorrectly.
Second, that isn't the interface for the library.
const markerCluster = new MarkerClusterer({ map, markers });
where markers is an array of google.maps.Markers. See MarkerClustererOptions.
Into your html:
<script src="https://unpkg.com/#googlemaps/markerclusterer/dist/index.min.js"></script>
Into your js, code both of these works
var mc = new markerClusterer.MarkerClusterer({ markers, map });
or
new markerClusterer.MarkerClusterer({ markers, map });

Show Google Maps top left infowindow on click?

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>

Google Maps API V3 requires page reload to show marker icons

I am reading points from a DB as JSON to create map markers and an unstructured list on a page. After adding some code to customize the list elements the map stopped showing the marker icons on first request - until a page reload is issued. Is this due to timing out from the API? Could the list object be built from the array after the map is loaded or is there some other way to speed up the code that might eliminate the problem? The map loaded markers fine with double this number of markers (300+) so I know problem is as a result of adding the formatting to the list object. No clustering required. A demo version of the page is available here
Signed a JS n00b. Thanks.
......
JSON POWERED GOOGLEMAP
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
var map;
var infoWindow = new google.maps.InfoWindow();
function initialize() {
var myLatlng = new google.maps.LatLng(49.57154029531499,-125.74951171875);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.TERRAIN,
streetViewControl: false
}
this.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
} /* end initialize function */
<!-- load points from database into Locations JSON -->
$(document).ready(function () {
initialize();
$.getJSON("map-service.php?action=listpoints", function(json) {
if (json.Locations.length > 0) {
for (i=0; i<json.Locations.length; i++) {
var location = json.Locations[i];
addMarker(location);
}
}
});
//define grn icon as closed
var greenicon = 'http://maps.google.com/mapfiles/ms/icons/green-dot.png';
function addMarker(location) {
if(location.datesummit == "0000-00-00") {
var markerOptions = {map: map, title: location.name, position: new google.maps.LatLng(location.lat, location.lng),icon: greenicon};
//create marker info window content
var html='<B>'+location.name+'</B><BR> Register a summit here ';
//create list element text and onclick
$("<li class=\"notclimbed\">")
.html(location.name+"</li>")
.click(function(){
infoWindow.close();
infoWindow.setContent(html);
infoWindow.open(map, marker)
})
.appendTo("#list");
}
else{
var markerOptions = {map: map, title: location.name, position: new google.maps.LatLng(location.lat, location.lng)};
//create marker info window content
var html='<B>'+location.name+'</B><BR> Summitted: '+location.datesummit+'<BR> By:'+location.summitlog;
//create list element text and onclick
$("<li class=\"climbed\">")
.html(location.name+"</li>")
.click(function(){
infoWindow.close();
infoWindow.setContent(html);
infoWindow.open(map, marker)
})
.appendTo("#list");
}
var marker = new google.maps.Marker(markerOptions);
// add a listener to open an info window when a user clicks on one of the markers
google.maps.event.addListener(marker, 'click', function() {
infoWindow.close();
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}; // end of addmarker function
});
</script>
</head>
<body>
<div id="banner" {vertical-align:text-top;} >
<img src="test.jpg" alt="Logo" style="width:150px;height:150px;vertical-align:middle">
<img src="test.png" alt="Logo" style="vertical-align:middle">
</div>
<div id="map_canvas" >
Map Here!
</div>
<div id="mindthegap"></div>
<div id="list" > </div>
</body>
You need to make sure the map variable is initialized before you pass it to markerOptions.
A bit of overzealous debugging showed me that on the times that the page fails, the map is still undefined.
The $(document).ready() will usually occur before body.onload, so either put a call to initialize() at the very top of your $(document).ready(function() { ... }); or put the code for initialize in there.
Also, though not strictly necessary, you should consider encapsulating your map variable instead of using a global. What if you ever want to have 2 maps on one page?

Google Maps API v3: Close infowindow when DOM element is clicked

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.

Have just one InfoWindow open in Google Maps API v3

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.

Categories