reopen infowindow after it's closed in Google map - javascript

I have a map with streetview panorama, an infowindow and a draggable marker. After the marker is dragged, a function requests the getPanoramaByLocation to see whether the view service is available. If it's not, it closes the infowindow. That is great but when I click again on the marker the infowindow does not open anymore. Do you know what is wrong please?
tx
var sv = new google.maps.StreetViewService();
function initialize() {
var optionMap = {
zoom: 13,
center: new google.maps.LatLng(47.390251,0.68882),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var myMap = new google.maps.Map(document.getElementById("mapDiv"), optionMap);
var optionsMarker = {
position: new google.maps.LatLng(47.390251,0.68882),
map: myMap,
draggable: true,
title: "my marker"
}
var marker = new google.maps.Marker(optionsMarker);
var infowindowDiv = '<div id="streetview" style="width:300px;height:200px;"' +'</div>';
var infoWindow = new google.maps.InfoWindow({
content: infowindowDiv,
position: myMap.getCenter() });
google.maps.event.addListener(marker, 'click', function() {
infoWindow.open(myMap, marker);
});
google.maps.event.addListener(infoWindow, 'domready', function() {
var panorama = new
google.maps.StreetViewPanorama(document.getElementById("streetview"));
panorama.setPosition(infoWindow.getPosition());
google.maps.event.addListener(marker, 'dragend', function(event) {
sv.getPanoramaByLocation(event.latLng, 50, processSVData);});
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var markerPanoID = data.location.pano;
// Set the Pano to use the passed panoID
panorama.setPano(markerPanoID);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
}
else {
infoWindow.close();
infoWindow = null;
};
}
});
}

From the GMaps API docs:
close() None Closes this InfoWindow by removing it from the DOM structure.
https://developers.google.com/maps/documentation/javascript/reference#InfoWindow
So... If you close the infowindow, it's gone. For ever. All the more so if you REALLY make sure it's gone by saying "infoWindow = null;" You have to make a new one. My advice would be to refactor your code to have a separate function that creates the infowindow on demand and returns it. In your click event definition, check whether infowindow is null, and if so, grab a new one.
HTH

As the other answer explain, the infobox html is removed from DOM when the user clicks the close button, but the JS object still there.
When you create an infowindow you must call the open method to see it on the map
myInfoWindow.open(mymap);
So, if you listen to the 'closeclick' event and keep the infowindow state
var infoWindowClosed = false;
google.maps.event.addListener(myInfoBox, "closeclick", function () {
infoWindowClosed = true;
});
you can reopen myInfoWindow on demand
if(infoWindowClosed){
myInfoWindow.open(mymap);
}

Related

Google Map looped markers wont close previous infowindow [duplicate]

This question already has answers here:
Google Maps JS API v3 - Simple Multiple Marker Example
(15 answers)
Closed 9 years ago.
Using a loop to show markers on Google Maps, I am finding that previous windows wont close even though I have a listener
Here is my code (set to limit number to 50 deliberately) that displays a marker if a user has location info set
function loadGmodule() {
var map = new google.maps.Map(
document.getElementById('gmashup'), {
center: new google.maps.LatLng(20, 0),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i=0;i<50;i++) {
u = users[i];
if (u.lat) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(u.lat, u.lang),
map: map
});
infoContent[i] = '<table ><tr><td><img src=\"'+u.avatar+'\" width=\"60\" height=\"75\"></td>';
infoContent[i] = infoContent[i] + '<td><b>'+u.firstname+' '+u.middlename+' '+u.lastname+'</b><br />'+u.designation + '<br />'+u.company+'<br />'+u.city+'</td>';
infoContent[i] = infoContent[i] + '</tr></table>';
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(infoContent[i]);
addInfoWindowOnEvent(marker, infoWindow, map, 'click');
}
}
}
and the function / listener
function addInfoWindowOnEvent(marker, infoWindow, map, event) {
google.maps.event.addListener(marker, event, function () {
infoWindow.close();
infoWindow.open(map, marker);
});
}
Can anyone advise the best location to put the infoWindow.close() so that previous windows will shut when another pin is clicked.
Thanks in advance for any assistance
Even though the edited indicated a duplicate, it was not to be found in the supplied link.. HOWEVER (even though I think this is a hack, but it will do) there was an answer here which worked
Google Maps API v3 (one infowindow open at a time)
I changed my function to
function addInfoWindowOnEvent(marker, infoWindow, map, event) {
google.maps.event.addListener(marker, event, function () {
if($('.gm-style-iw').length) {
$('.gm-style-iw').parent().remove();
}
infoWindow.open(map,marker);
});
}
and now only one window stays open
For each marker you are creating new infowindow. If you want to close previous infowindow and have only one opened then it is enough to create only one infowindow. It should be global:
var infoContent = [];
var infoWindow;
function loadGmodule() {
var map = new google.maps.Map(
...
infoWindow = new google.maps.InfoWindow();
//for (var i = 0; i < 50; i++) {
for (var i = 0; i < users.length; i++) {
...
and then provide specific content to event listener:
...
infoContent[i] = infoContent[i] + '</tr></table>';
//infoWindow = new google.maps.InfoWindow();
//infoWindow.setContent(infoContent[i]);
addInfoWindowOnEvent(marker, infoContent[i], map, 'click');
}
}
}
function addInfoWindowOnEvent(marker, infoContent, map, event) {
google.maps.event.addListener(marker, event, function () {
infoWindow.close();
infoWindow.setContent(infoContent)
infoWindow.open(map, marker);
});
}

Open info window on load Google Map

I'm wondering if it's possible to open one of the infoWindow objects that are attached to each marker in the code below on page load and not just by clicking on them? As it is now, the user has to click on one of the markers to open an info window.
I tested to create a "stand alone" info window object and that opened fine onload, but it didn't close when I clicked on some of the other markers, because the onClick function was attached to the markers that only could close the info windows attached to that object. Correct med if I'm wrong?
Would this be possible and can I "call" an object by the number or what options do I have? Tips are preciated!
Or if there is possible, that I have tried to open an separate info window onload and be able to close that if I open one of the other info windows!?
var map = null;
var infowindow = new google.maps.InfoWindow();
var iconBase = 'images/mapNumbers/number';
//var zoomLevel = 11;
//var mapPositionLat = 55.678939;
//var mapPositionLng = 12.568359;
function initialize() {
var markerPos = new google.maps.LatLng(55.674196574861895, 12.583808898925781);
var myOptions = {
zoom: 11,
//center: new google.maps.LatLng(55.678939, 12.568359),
center: markerPos,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function () {
infowindow.close();
});
google.maps.event.addListener(map, 'zoom_changed', function () {
infowindow.close();
});
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(markerPos);
map.setZoom(zoomLevel);
//var center = map.getCenter();
});
// Add markers to the map
var point;
point = new google.maps.LatLng(55.667093,12.581255); createMarker(point, "<div class='infoWindow'>1</div>");
point = new google.maps.LatLng(55.660794,12.58972); createMarker(point, "<div class='infoWindow'>2</div>");
point = new google.maps.LatLng(55.660491,12.587087); createMarker(point, "<div class='infoWindow'>3</div>");
}
// Create markers
function createMarker(latlng, html, name, number) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: name,
icon: iconBase + number + '.png'
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(html);
infowindow.open(map, marker);
//map.setCenter(marker.getPosition());
map.setCenter(55.678939, 12.568359);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
In order to display InfoWindow when the map loads, make the call to
infowindow.open(map, marker);
outside of the marker listener.
Below is demonstrated createMarker function, where parameter displayInfoWindow defines whether to display InfoWindow when the map loads:
// Create marker
function createMarker(map,markerPos, markerTitle,infoWindowContent,displayInfoWindow) {
var marker = new google.maps.Marker({
position: markerPos,
map: map,
title: markerTitle,
});
var infowindow = new google.maps.InfoWindow({
content: infoWindowContent
});
if(displayInfoWindow) {
infowindow.open(map, marker);
}
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
Example: http://jsbin.com/lusuquwu/1/
It is possible. One possible solution is to save markers to an array and then trigger click event on of one of them using google.maps.event.trigger(). For example:
...
var zoomLevel = 11; // uncommented due to error message
var markers = [];
function initialize() {
...
point = new google.maps.LatLng(55.660491,12.587087); createMarker(point, "<div class='infoWindow'>3</div>");
google.maps.event.trigger(markers[1], 'click');
}
function createMarker(latlng, html, name, number) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: name,
//icon: iconBase + number + '.png'
icon: iconBase
});
// added to collect markers
markers.push(marker);
google.maps.event.addListener(marker, 'click', function () {
console.log('click event listener');
infowindow.setContent(html);
infowindow.open(map, marker);
//map.setCenter(marker.getPosition());
// corrected due to error
map.setCenter(new google.maps.LatLng(55.678939, 12.568359));
});
}
I combined info from this and another site to come up with the below solution as most solutions are for multi-marker maps.
Just a few lines is all you actually need.
// Start with your map
var map = new google.maps.Map(...);
// Now define the info window using HTML. You can insert images etc.
var info = new google.maps.InfoWindow({content: 'YOUR HTML HERE'});
// Now define the marker position on the map
var marker = new google.maps.Marker({map: map, position:{lat: 'YOUR LATITUDE',lng: 'YOUR LONGITUDE'}});
Now we have the variables, just hide the marker, show the info window and set the map zoom and center.
// Set the map zoom
map.setZoom('YOUR ZOOM LEVEL [1 - 20]');
// Set the map center
map.setCenter({lat: 'YOUR LATITUDE',lng: 'YOUR LONGITUDE'});
// Hide the marker that we created
marker.setVisible(false);
// Open the info window with the HTML on the marker position
info.open(map, marker);
For the content, you can create layers and insert images and text as you need. Just make sure you include the full URL to images in your html.
I also recommend adding this to your CSS to hide the close button, which effectively makes this a permanent, info window.
.gm-style-iw + div {display: none;}

Adding multiple addListener events to a Google Map form with geocoding

I have created a Google Map form that lets users enter an address into a text field and geocode the entry. This then puts a marker on a map. This works fine, but I want to add an additional addListener so when the user clicks the map it will add another pin where they click. For some reason my 'click' addListener is not working. How would I have multiple add Listeners like that?
I attached my current code:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(40.7,-74.0),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.bindTo('bounds', map);
var marker = new google.maps.Marker({
map: map,
draggable: true
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(16);
}
var image = "http://www.google.com/mapfiles/marker_green.png";
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [(place.address_components[0] &&
place.address_components[0].short_name || ''),
(place.address_components[1] &&
place.address_components[1].short_name || ''),
(place.address_components[2] &&
place.address_components[2].short_name || '')
].join(' ');
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(map, 'click', function() {
//alert("Hello! I am an alert box!!");
var marker1 = new google.maps.Marker({
map: map,
draggable: true
});
var image = "http://www.google.com/mapfiles/marker_green.png";
marker1.setIcon(image);
marker1.setPosition(new google.maps.LatLng(40.7,-74.0));
map.addOverlay(marker1);
});
</script>
The map click event will return the position of the mouse click.
Update: To erase the old marker when a new one is added you need to store an instance of the marker outside of the listener scope then you can erase it at the beginning of the listener event.
var singleMarker;
google.maps.event.addListener(map, 'click', function(event) {
//if marker exists, erase marker
if(singleMarker){
singleMarker.setMap(null);
}
singleMarker = new google.maps.Marker({
position: event.latLng, //mouse click position
map: map,
draggable: true,
icon: "http://www.google.com/mapfiles/marker_green.png"
});
});
Updated fiddle example.
You could use a
google.maps.event.addListener(map,'click', function()...
to add an onclick event to the map object. Here's a reference:
http://code.google.com/apis/maps/documentation/javascript/reference.html#Map
You could also use the Google Maps Drawing Tools library:
http://code.google.com/apis/maps/documentation/javascript/overlays.html#drawing_tools

trigger google maps marker click

I have a google map set up to find the user's current location, and center the map at that closest marker to their location. The markers, when clicked, open up an infobox (note this is a little different than an infoWindow - http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/docs/examples.html). What I want to do, however, is automatically open up the nearest marker without the user actually clicking. Here's the code to trigger a marker opening:
//loop through all locations to add a marker:
addMarker = function(loc) {
var markerLoc = new google.maps.LatLng(loc.Lat, loc.Long);
var marker = new google.maps.Marker({
map: map,
position: markerLoc
});
google.maps.event.addListener(marker, "mousedown", function() {
var infoOpts = {
content: loc.markerText,
boxStyle: { background: "none transparent", width: "180px"},
pixelOffset: new google.maps.Size(-90, 0),
closeBoxMargin: "5px"
};
var ib = new InfoBox(infoOpts);
ib.open(map, marker);
});
markers.push(marker);
};
So somehow I have to trigger the mouseDown function of the appropriate marker, but it has to be done in a function outside of this one. I will have a reference to the appropriate marker in the array (markers[closestmarker]).
I see that this question has been sitting for quite awhile, but, just in case, this answer may be helpful:
trigger google maps marker click
The code would look like this:
var marker = new google.maps.Marker({});
new google.maps.event.trigger( marker, 'click' );
I found I needed to attach a click event to the marker like so
var marker = new google.maps.Marker({});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
new google.maps.event.trigger( marker, 'click' );

infowindows on pushpins not closing on google maps

Im using google maps api v3. im adding markers by caling this function:
function createMarker(posn, title, html) {
var marker = new google.maps.Marker ({position:posn, title: title, draggable: false});
var infowindow = new google.maps.InfoWindow({content: html});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map,marker);
});
return marker;
}
it works okay, the only problem is when i click a pushpin the window opens, but when i click another pushpin the first pushpins infowindow window does not close both infowindows are visible.
Don't know if you solved this, but the way I did it was:
function createMarker(posn, title, html) {
var marker = new google.maps.Marker ({position:posn, title: title, draggable: false});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map,marker);
});
infowindow = new google.maps.InfoWindow({content: html});
return marker;
}
This works, and the windows close when another pin is clicked, but the "X" close button doesn't work...
You need to keep track of your info windows in an array and close them programmaticaly when a click event fires so using your example
//define a global array
infoWindows = new Array();
//..do your stuff
function createMarker(posn, title, html) {
var marker = new google.maps.Marker ({position:posn, title: title, draggable: false});
var infowindow = new google.maps.InfoWindow({content: html});
//add this infowindow to an array
infoWindows.push(infowindow);
google.maps.event.addListener(marker, "click", function() {
//go through the array and close all open info windows
for (i=0;i<infoWindows.length;i++) {
infoWindows[i].setMap(null);
}
//open current info window
infowindow.open(map,marker);
});
return marker;
}

Categories

Resources