Emre Emre - 7 months ago 27
Javascript Question

Google maps returns same coordinates when hidden

I have a google map on the right part of the screen and house listings on the left similar like airbnb. When user moves the google map the listings are refreshed with AJAX request.

I would like to hide the google map on small screen devices. But when I hide google map, weirdly, it still returns bounds (should return 0 as there is no map) but

map.getBounds().getSouthWest().lat()
and
map.getBounds().getNorthEast().lat()
same, and
map.getBounds().getSouthWest().lng()
and
map.getBounds().getNorthEast().lng()
.

I do not get why lat and lng values are equals.

Here is my bounds call;

...
new google.maps.event.addListener(map, 'idle', function(){

params = get_bounds();

request_listings( extra_params );

console.log(params);



});



/*
*Utility function: To get the bounds of the map
*/
function get_bounds(){

return {

sw_lat : map.getBounds().getSouthWest().lat(),

sw_lng : map.getBounds().getSouthWest().lng(),

ne_lat : map.getBounds().getNorthEast().lat(),

ne_lng : map.getBounds().getNorthEast().lng()



};
...


it logs to console;
map is not visible

Object {sw_lat: 40.983198400000006, sw_lng: 28.853608399999985, ne_lat: 40.983198400000006, ne_lng: 28.853608399999985}


And this is when map is visible;

Object {sw_lat: 40.802046203851475, sw_lng: 28.853608399999985, ne_lat: 40.983198400000006, ne_lng: 29.196244508398422}


To compare,

sw_lng the same for both case, and ne_lat the same with/without map. So I am getting these values but why not other or why I am getting value when map is not visible.

Thank you

Answer

It sounds like you're just hiding the map div setting display: none; or an equivalent. In this case the map still exists in the DOM, it's just not visible, which is why you're still able to get the bounds for it.

I'm not actually sure if a map can exist with no bounds, I would suggest changing whatever code you're using these bounds in to also check the visibility instead of the map instead of a 0 bounds.

If you truly want the map to have no bounds (or as small bounds as possible), you could try shrinking the div to width: 0px; height: 0px; (or maybe 1px) and then firing a google.maps.event.trigger(map, 'resize'); event to resize the map to fit a super tiny box.