How to close an open google maps infowindow by clicking marker again - google-maps-api-3

I'm trying to close a open google maps infowindow by clicking a marker again. Currently there are only questions about how to close all other infowindows when clicking the map or other markers.
How to close an open google maps infowindow by clicking the same marker again? Currently I can only close an infowindow by clicking the cross on the top right corner of the infowindow.
This is what I tried but it doesn't even open the infowindow:
EncoreMarker.addListener('click', function () {
if (EncoreInfoCard.open) {
EncoreInfoCard.close(map, EncoreMarker);
}
else {
EncoreInfoCard.open(map, EncoreMarker);
}
});

Your code won't work because open is a function that opens the InfoWindow, not a boolean that tells whether it is open or not.
This works for me:
EncoreMarker.addListener('click', function () {
// create a custom property of the InfoWindow, defaults to a value that evaluates as false
if (EncoreInfoCard.isOpen) {
EncoreInfoCard.close(map, EncoreMarker);
EncoreInfoCard.isOpen = false;
}
else {
EncoreInfoCard.open(map, EncoreMarker);
EncoreInfoCard.isOpen = true;
}
});
proof of concept fiddle
code snippet:
// This example displays a marker at the center of Australia.
// When the user clicks the marker, an info window opens.
// When the user clicks the makrer again, the info window closes.
function initMap() {
var uluru = {
lat: -25.363,
lng: 131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var EncoreInfoCard = new google.maps.InfoWindow({
content: "<b>This is a Test</b>"
});
google.maps.event.addListener(EncoreInfoCard, 'closeclick', function() {
EncoreInfoCard.isOpen = false;
});
var EncoreMarker = new google.maps.Marker({
position: uluru,
map: map,
title: 'Uluru (Ayers Rock)'
});
EncoreMarker.addListener('click', function() {
if (EncoreInfoCard.isOpen) {
EncoreInfoCard.close(map, EncoreMarker);
EncoreInfoCard.isOpen = false;
} else {
EncoreInfoCard.open(map, EncoreMarker);
EncoreInfoCard.isOpen = true;
}
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap">
</script>

Related

Google Maps API 3 - Disable if Mobile

Looking to disable the Google Map when browsed on a mobile device. Currently running CSS to hide the div if the browser window is 600px or below.
#media only screen and (max-width: 600px) {
.mapCanvas {
display: none;
}
}
How can you disable the JS from querying the Google Maps API if the browser is 600px or smaller?
So that it won't query the API server when the map isn't even displayed.
<div id="mapCanvas"></div>
<script>
function initMap() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the web page
map = new google.maps.Map(document.getElementById("mapCanvas"), mapOptions);
map.setTilt(50);
// Multiple markers location, latitude, and longitude
var markers = [ <?php echo $js_markers; ?>
];
// Info window content
var infoWindowContent = [ <?php echo $js_content; ?>
];
// Add multiple markers to map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Place each marker on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Add info window to marker
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
// Center the map to fit all markers on the screen
map.fitBounds(bounds);
}
// Set zoom level
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(7);
google.maps.event.removeListener(boundsListener);
});
}
// Load initialize function
google.maps.event.addDomListener(window, 'load', initMap);
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=???&callback=initMap"></script>
Don't include the google maps API JS file if its mobile
Something like
if (typeof window.orientation !== 'undefined') { ... }

How to close POI's InfoWindow?

I'm trying to make POI's InfoWindow close when click a link.
I overrided the setContent of InfoWindow like this:
//override the built-in setContent-method
google.maps.InfoWindow.prototype.setContent = function (content) {
content = content.innerHTML + '<br/> Save place';
//run the original setContent-method
fx.apply(this, arguments);
};
Note: I didn't create any InfoWindow object to reference to use close() method.
In your override function capture a global reference to the infowindow so you can reference it to close it.
Your override of the infowindow doesn't work. I took a working version from this question: How to get a click event when a user clicks a (business) place on the map
proof of concept fiddle
code snippet:
var geocoder;
var map;
var infowindow;
//keep a reference to the original setPosition-function
var fx = google.maps.InfoWindow.prototype.setPosition;
// from https://stackoverflow.com/questions/24234106/how-to-get-a-click-event-when-a-user-clicks-a-business-place-on-the-map/24234818#24234818
//override the built-in setPosition-method
google.maps.InfoWindow.prototype.setPosition = function() {
//logAsInternal isn't documented, but as it seems
//it's only defined for InfoWindows opened on POI's
if (this.logAsInternal) {
// save reference in global infowindow variable.
infowindow = this;
google.maps.event.addListenerOnce(this, 'map_changed', function() {
var map = this.getMap();
//the infoWindow will be opened, usually after a click on a POI
if (map) {
//trigger the click
google.maps.event.trigger(map, 'click', {
latLng: this.getPosition()
});
}
});
}
//call the original setPosition-method
fx.apply(this, arguments);
};
function initialize() {
var map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addDomListener(document.getElementById('btn'), 'click', function(e) {
// close the last opened POI infowindow
infowindow.close();
});
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="btn" type="button" value="close IW" />
<div id="map_canvas"></div>

Google map resize not solving partial display issue within a modal dialogue

I known this question has been raised and answered many times but I can't seem to make the suggested solutions work for me...
I'm displaying a google map within a simplemodal dialogue.
Outside the modal dialogue the map displays correctly.
However, once inside a modal wrapper only part of the map is shown on the first iteration (see below).
The solution would appear to involve binding a 'resize' event to the map but it isn't working for me...
First iteration:
On opening the modal for the first iteration, my map displays with the partial section displaced over to the top RHS and overlaid on the full map.
On closing the first dialogue the screen returns to it's initial state.
Second and subsequent iterations:
On subsequent iterations the map displays correctly but on closing the background color of the map canvas is visible.
HTML:
<body>
<button class="modalMap">With Modal </button>
<button class="nonModalMap">Without Modal </button>
<div id="mapCanvas"></div>
</body>
CSS:
#simplemodal-overlay {background-color:#000;}
#simplemodal-container {color:#999; background-color:#fff;}
#simplemodal-container a{color:#ddd;}
.modalMap:hover,.nonModalMap:hover {
cursor:pointer;
}
#mapCanvas {
position:relative;
width:480px;height:300px;
}
JS:
$(document).ready(function(){
var myMap;
$('.modalMap').click(function(){
buildMap();
$('#mapCanvas').modal(
{onOpen:function(dialog){
dialog.overlay.fadeIn('fast',function(){
dialog.data.hide();dialog.container.fadeIn('fast',function(){
dialog.data.slideDown('fast');
});
});
}
,onClose:function(dialog){
dialog.data.fadeOut('fast',function(){
dialog.container.hide('fast',function(){
dialog.overlay.slideUp('fast',function(){
$.modal.close();
});
});
});
}
});
});
/* But without the modal the map displays correctly... */
$('.nonModalMap').click(function(){
buildMap();
});
});
function buildMap() {
var kpl = {
Place: function (data, map) {
var self = this;
this.data = data;
var coords = data.geo_coords.split(',');
this.position = new google.maps.LatLng(coords[0], coords[1]);
this.marker = new google.maps.Marker({
position: this.position,
map: map
});
google.maps.event.addListener(this.marker, 'click', function() {
if (self.data.url) {
window.location.href = self.data.url
}
});
},
MapManager: function (div, data) {
this.map = new google.maps.Map(div, {
zoom: 15,
center: new google.maps.LatLng(53.818298, -1.573263),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
backgroundColor: '#cccccc',
streetViewControl: false,
navigationControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
saveCenter = this.map.center;
this.places = [];
for (var i in data) {
if (data.hasOwnProperty(i)) {
this.places.push(new kpl.Place(data[i], this.map));
}
}
}
};
myMap = new kpl.MapManager($('#mapCanvas').get(0), [{
url: "mailto:info#????.com",
geo_coords: "53.818298, -1.573263",
name: "Kensington Property LS6"
}]);
}
/* plus the simplemodal library... */
I've recreated the code in jsfiddle - http://jsfiddle.net/redApples/j23ue0n1/32/
Can anybody rescue my sanity...?

Capture Coordinates in Google Map on User Click

I'm using this code to capture the co-ordinates when user clicks on the map by using below event listener:
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
However this function doesn't get called when user click on already marked location in Map.
Meaning this function is not called for points where mouse pointer changes to hand icon on Google Map.
Need help on capturing these kind of locations.
You should add the click listener on marker will give you the position of marker.
//Add listener
google.maps.event.addListener(marker, "click", function (event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log( latitude + ', ' + longitude );
}); //end addListener
Edit:
You need something like this
//Add listener
google.maps.event.addListener(marker, "click", function (event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
console.log( latitude + ', ' + longitude );
radius = new google.maps.Circle({map: map,
radius: 100,
center: event.latLng,
fillColor: '#777',
fillOpacity: 0.1,
strokeColor: '#AA0000',
strokeOpacity: 0.8,
strokeWeight: 2,
draggable: true, // Dragable
editable: true // Resizable
});
// Center of map
map.panTo(new google.maps.LatLng(latitude,longitude));
}); //end addListener
Another solution is to place a polygon over the map, same size as the map rectangle, and collect this rectangles clicks.
function initialize() {
var mapDiv = document.getElementById('map-canvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'bounds_changed', function() {
var lat1 = 37.41463623043073;
var lat2 = 37.46915383933881;
var lng1 = -122.1848153442383;
var lng2 = -122.09898465576174;
var rectangle = new google.maps.Polygon({
paths : [
new google.maps.LatLng(lat1, lng1),
new google.maps.LatLng(lat2, lng1),
new google.maps.LatLng(lat2, lng2),
new google.maps.LatLng(lat1, lng2)
],
strokeOpacity: 0,
fillOpacity : 0,
map : map
});
google.maps.event.addListener(rectangle, 'click', function(args) {
console.log('latlng', args.latLng);
});
});
}
Now you get LatLng's for places of interest (and their likes) also.
demo -> http://jsfiddle.net/qmhku4dh/
You're talking about the Point of Interest icons that Google puts on the map.
Would it work for you to remove these icons entirely? You can do that with a Styled Map. To see what this would look like, open the Styled Map Wizard and navigate the map to the area you're interested in.
Click Point of interest under Feature type, and then click Labels under Element type. Finally, click Visibility under Stylers and click the Off radio button under that.
This should remove all of the point of interest icons without affecting the rest of the map styling. With those gone, clicks there will respond to your normal map click event listener.
The Map Style box on the right should show:
Feature type: poi
Element type: labels
Visibility: off
If the result looks like what you want, then click Show JSON at the bottom of the Map Style box. The resulting JSON should like this this:
[
{
"featureType": "poi",
"elementType": "labels",
"stylers": [
{ "visibility": "off" }
]
}
]
You can use that JSON (really a JavaScript object literal) using code similar to the examples in the Styled Maps developer's guide. Also see the MapTypeStyle reference for a complete list of map styles.
This example demonstrates the use of click event listeners on POIs (points of interest). It listens for the click event on a POI icon and then uses the placeId from the event data with a directionsService.route request to calculate and display a route to the clicked place. It also uses the placeId to get more details of the place.
Read the google documentation.
<!DOCTYPE html>
<html>
<head>
<title>POI Click Events</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
.title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
</style>
</head>
<body>
<div id="map"></div>
<div id="infowindow-content">
<img id="place-icon" src="" height="16" width="16">
<span id="place-name" class="title"></span><br>
Place ID <span id="place-id"></span><br>
<span id="place-address"></span>
</div>
<script>
function initMap() {
var origin = {lat: -33.871, lng: 151.197};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 18,
center: origin
});
var clickHandler = new ClickEventHandler(map, origin);
}
/**
* #constructor
*/
var ClickEventHandler = function(map, origin) {
this.origin = origin;
this.map = map;
this.directionsService = new google.maps.DirectionsService;
this.directionsDisplay = new google.maps.DirectionsRenderer;
this.directionsDisplay.setMap(map);
this.placesService = new google.maps.places.PlacesService(map);
this.infowindow = new google.maps.InfoWindow;
this.infowindowContent = document.getElementById('infowindow-content');
this.infowindow.setContent(this.infowindowContent);
// Listen for clicks on the map.
this.map.addListener('click', this.handleClick.bind(this));
};
ClickEventHandler.prototype.handleClick = function(event) {
console.log('You clicked on: ' + event.latLng);
// If the event has a placeId, use it.
if (event.placeId) {
console.log('You clicked on place:' + event.placeId);
// Calling e.stop() on the event prevents the default info window from
// showing.
// If you call stop here when there is no placeId you will prevent some
// other map click event handlers from receiving the event.
event.stop();
this.calculateAndDisplayRoute(event.placeId);
this.getPlaceInformation(event.placeId);
}
};
ClickEventHandler.prototype.calculateAndDisplayRoute = function(placeId) {
var me = this;
this.directionsService.route({
origin: this.origin,
destination: {placeId: placeId},
travelMode: 'WALKING'
}, function(response, status) {
if (status === 'OK') {
me.directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
};
ClickEventHandler.prototype.getPlaceInformation = function(placeId) {
var me = this;
this.placesService.getDetails({placeId: placeId}, function(place, status) {
if (status === 'OK') {
me.infowindow.close();
me.infowindow.setPosition(place.geometry.location);
me.infowindowContent.children['place-icon'].src = place.icon;
me.infowindowContent.children['place-name'].textContent = place.name;
me.infowindowContent.children['place-id'].textContent = place.place_id;
me.infowindowContent.children['place-address'].textContent =
place.formatted_address;
me.infowindow.open(me.map);
}
});
};
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
async defer></script>
</body>
</html>
If you are using npm load-google-maps-api with webpack this worked for me:
const loadGoogleMapApi = require("load-google-maps-api");
loadGoogleMapApi({ key: process.env.GOOGLE_MAP_API_KEY }).then(map => {
let mapCreated = new map.Map(mapElem, {
center: { lat: lat, lng: long },
zoom: 7
});
mapCreated.addListener('click', function(e) {
console.log(e.latLng.lat()); // this gives you access to the latitude value of the click
console.log(e.latLng.lng()); // gives you access to the latitude value of the click
var marker = new map.Marker({
position: e.latLng,
map: mapCreated
});
mapCreated.panTo(e.latLng); // finally this adds red marker to the map on click.
});
});
Next if you are integrating openweatherMap in your app you can use the value of e.latLng.lat() and e.latLng.lng() which I console logged above in your api request. This way:
http://api.openweathermap.org/data/2.5/weather?lat=${e.latLng.lat()}&lon=${e.latLng.lng()}&APPID=${YOUR_API_KEY}
I hope this helps someone as it helped me.
Cheers!

Get Google Maps v3 to resize height of InfoWindow

When I click a marker and the InfoWindow appears, the height does not adjust if the length of the content is longer that the InfoWindow default height (90px).
I am using text-only, no images.
I have tried maxWidth.
I have checked for inherited CSS.
I have wrapped my content in a div
and applied my CSS to that, including
a height.
I have even tried forcing the
InfoWindow to resize with jQuery
using the domready event on the
InfoWindow.
I only have a few hairs left. Here is my JS:
var geocoder;
var map;
var marker;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(41.8801,-87.6272);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function codeAddress(infotext,address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var image = '/path-to/mapMarker.png';
var infowindow = new google.maps.InfoWindow({ content: infotext, maxWidth: 200 });
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon: image
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
});
}
function checkZipcode(reqZip) {
if ( /[0-9]{5}/.test(reqZip) ) {
$.ajax({
url: 'data.aspx?zip=' + reqZip,
dataType: 'json',
success: function(results) {
$.each(results.products.product, function() {
var display = "<span id='bubble-marker'><strong>"+this.name+"</strong><br>"+
this.address+"<br>"+
this.city+", "+this.state+" "+this.zip+"<br>"+
this.phone+"</span>";
var address = this.address+","+
this.city+","+
this.state+","+
this.zip;
codeAddress(display,address);
});
},
error: function() { $('#information-bar').text('fail'); }
});
} else { $('#information-bar').text('Zip codes are five digit numbers.'); }
}
$('#check-zip').click(function() { $('#information-bar').text(''); checkZipcode($('#requested-zipcode').val()); });
initialize();
InfoText and Address come from an AJAX query of an XML file. Data is not the issue, as it always comes through correctly. codeAddress() is called after the data has been retrieved and formatted.
HTML in the file:
<div id="google_map"> <div id="map_canvas" style="width:279px; height:178px"></div> </div>
CSS for my InfoWindow content (no other CSS applies to the map):
#bubble-marker{ font-size:11px; line-height:15px; }
I finally found a working solution for the problem. Is not as flexible as I wished, but it's pretty good. Fundamentally the key point is: don't use a string as window content but instead a DOM node.
This is my code:
// this dom node will act as wrapper for our content
var wrapper = document.createElement("div");
// inject markup into the wrapper
wrapper.innerHTML = myMethodToGetMarkup();
// style containing overflow declarations
wrapper.className = "map-popup";
// fixed height only :P
wrapper.style.height = "60px";
// initialize the window using wrapper node
var popup = new google.maps.InfoWindow({content: wrapper});
// open the window
popup.open(map, instance);
the following is the CSS declaration:
div.map-popup {
overflow: auto;
overflow-x: hidden;
overflow-y: auto;
}
ps: "instance" refers to the current custom subclass of google.maps.OverlayView (which I'm extending)
Just wrap your content with a div and specify it's height: <div style="height:60px">...</div>, e.g.
myMarker.setContent('<div style="height:60px">' + txt + '</div>');
- In my case it was fairly enough.
Your map canvas is too small. Increase the width/height of your <div id="map_canvas"> element and you should see larger InfoWindows automatically.
That said, I had the same problem on a site I was building. I solved it by creating a cloned div containing the InfoWindow content, measuring that div's width and height, and then setting the InfoWindow content div to have that measured width and height. Here's my code ported into the middle of your codeAddress function (also note that I removed the maxWidth: 200 from your InfoWindow declaration):
function codeAddress(infotext,address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
// Create temporary div off to the side, containing infotext:
var $cloneInfotext = $('<div>' + infotext + '</div>')
.css({marginLeft: '-9999px', position: 'absolute'})
.appendTo($('body'));
// Wrap infotext with a div that has an explicit width and height,
// found by measuring the temporary div:
infotext = '<div style="width: ' + $cloneInfotext.width() + 'px; ' +
'height: ' + $cloneInfotext.height() + 'px">' + infotext +
'</div>';
// Delete the temporary div:
$cloneInfotext.remove();
// Note no maxWidth defined here:
var infowindow = new google.maps.InfoWindow({ content: infotext });
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
}
});
}
Just wrap you InfoBox content with DIV with padding-bottom: 30px;
JS:
map_info_window = new google.maps.InfoWindow();
var $content = $('<div class="infobox">').html(content);
map_info_window.setContent($content.get(0));
map_info_window.open(map, marker);
CSS:
.infobox{
padding-bottom: 30px;
}
It is not really an answer (daveoncode's solution to create a DOM node and use it as content is right), but if you need to dynamically change the content once set (e.g. with jQuery) then you can force gmail to resize the infoWindow with:
infoWindowLinea.setContent(infoWindowLinea.getContent());

Resources