Google Maps Api v3 - getBounds is undefined - javascript

I'm switching from v2 to v3 google maps api and got a problem with gMap.getBounds() function.
I need to get the bounds of my map after its initialization.
Here is my javascript code:
var gMap;
$(document).ready(
function() {
var latlng = new google.maps.LatLng(55.755327, 37.622166);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
gMap = new google.maps.Map(document.getElementById("GoogleMapControl"), myOptions);
alert(gMap.getBounds());
}
);
So now it alerts me that gMap.getBounds() is undefined.
I've tried to get getBounds values in click event and it works fine for me, but I cannot get the same results in load map event.
Also getBounds works fine while document is loading in Google Maps API v2, but it fails in V3.
Could you please help me to solve this problem?

In the early days of the v3 API, the getBounds() method required the map tiles to have finished loading for it to return correct results. However now it seems that you can listen to bounds_changed event, which is fired even before the tilesloaded event:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps v3 - getBounds is undefined</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 350px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: new google.maps.LatLng(55.755327, 37.622166),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'bounds_changed', function() {
alert(map.getBounds());
});
</script>
</body>
</html>

It should be working, atleast according to the documentation for getBounds(). Nevertheless:
var gMap;
$(document).ready(function() {
var latlng = new google.maps.LatLng(55.755327, 37.622166);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
gMap = new google.maps.Map(document.getElementById("GoogleMapControl"), myOptions);
google.maps.event.addListenerOnce(gMap, 'idle', function(){
alert(this.getBounds());
});
});
See it working here.

I was saying Salman's solution is better because the idle event is called earlier than the tilesloaded one, since it waits for all the tiles to be loaded. But on a closer look, it seems bounds_changed is called even earlier and it also makes more sense, since you're looking for the bounds, right? :)
So my solution would be:
google.maps.event.addListenerOnce(gMap, 'bounds_changed', function(){
alert(this.getBounds());
});

In other comments here, it's adviced to use the "bounds_changed" event over "idle", which I agree with. Certainly under IE8 which triggers "idle" before "bounds_changed" on my dev machine at least, leaving me with a reference to null on getBounds.
The "bounds_changed" event however, will be triggered continuously when you'll drag the map. Therefor, if you want to use this event to start loading markers, it will be heavy on your webserver.
My multi browser solution to this problem:
google.maps.event.addListenerOnce(gmap, "bounds_changed", function(){
loadMyMarkers();
google.maps.event.addListener(gmap, "idle", loadMyMarkers);
});

Well, i'm not sure if i'm too late, but here's my solution using gmaps.js plugin:
map = new GMaps({...});
// bounds loaded? if not try again after 0.5 sec
var check_bounds = function(){
var ok = true;
if (map.getBounds() === undefined)
ok = false;
if (! ok)
setTimeout(check_bounds, 500);
else {
//ok to query bounds here
var bounds = map.getBounds();
}
}
//call it
check_bounds();

Adding an answer for 2021.
Map.getBounds() may return undefined initially. The preferred workaround to this is to use the bounds_changed event. Typically, an undefined value will only happen in the initialization of the map and never again.
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: new google.maps.LatLng(55.755327, 37.622166),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.addEventListener('bounds_changed', () => {
console.log(map.getBounds());
});
https://developers.google.com/maps/documentation/javascript/reference/map#Map.bounds_changed

Related

How to set the marker position constant on window resize on google maps?

I recently started exploring google maps api. I stumbled upon panby function of google maps api. What I am trying to do is, when my map is loaded initially, the marker should be on the right as shown in the attached image.
Attached screenshot of initial load
However, I want to add a listener for the marker to stay on the right on window resize but do not know what to write in the listener function .Please help me this. Thanks in advance. Here is my code so far.
onAfterRendering: function() {
var myLatlng = new google.maps.LatLng(12.979172,77.715402);
var mapOptions = {
center: myLatlng ,
zoom: 12,
disableDefaultUI: true,
zoomControl: true
};
var x = this.byId("mapCanvas").getDomRef();
map = new google.maps.Map(x, mapOptions);
map.panBy(-300,0);
google.maps.event.addDomListener(window, "resize", function() {
var location= marker.getPosition();
google.maps.event.trigger(map, "resize");
});}
You can recenter the map to the known marker position and then pan left. Something like (untested):
...
map.panBy(-300,0);
var markerLocation= marker.getPosition(); //if you don't have it elsewhere
google.maps.event.addDomListener(window, "resize", function() {
map.setCenter(markerLocation)
map.panBy(-300,0);
google.maps.event.trigger(map, "resize");
});}

Google maps zoom scrollbar does not appear on new version

I have a web-page here. It uses google maps and it worked well. Recently a new version of google maps was released where some changes were made. For instance, instead of e.latLng.F, e.latLng.lng and instead of e.latLng.A, e.latLng.lat should be used. So far, so good. However, for some reason, the zoom scrollbar cannot be seen. I know one can still zoom with mouse scrolling, however, what about devices where mouse scroll is not defined, like a laptop with a touchpad?
This is a part of initialization:
var mapOptions = {
center: { lat: lat, lng: lon},
zoom: 14
};
if (!administrator) {
mapOptions.mapTypeId = google.maps.MapTypeId.HYBRID;
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
I believe I should define an attribute for mapOptions, but I do not know what should be defined there. When I searched for this on google, I have not found the answer. It is possible that I will find out the answer soon, but anyway, I ask the question here to make sure that others will have an answer to this question in the future. Thanks.
EDIT:
At this page I can see a zoom control. This is the code there:
<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js">
</script>
<script>
function initialize()
{
var mapProp = {
center: new google.maps.LatLng(51.508742,-0.120850),
zoom:7,
zoomControl:true,
zoomControlOptions: {
style:google.maps.ZoomControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
if I modify it to this:
<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js">
</script>
<script>
function initialize()
{
var mapProp = {
center: { lat: 51.508742, lng: -0.120850},
zoom:7,
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
the zoom control is still displayed. I wonder why is the zoom control displayed at w3c and not at my end, since:
both the example and my code uses a div
the properties are initialized in a similar manner
the map is initialized in a similar manner
the dom listener is initialized in a similar manner
They've removed the scroll bar from the newest API, but they left the + and - zoom controls. Strangely, I see that your map doesn't have those either.
This article about the changes made to the map controls might be useful
The zoom control was always displayed, but the footer overflown it. It seems that the zoom control is positioned to the right bottom by default, while earlier it was positioned to the left top by default. The solution is either to make sure that the div where the map is displayed is displayed fully, or to initialize the position of the zoom control, like this:
var mapOptions = {
center: { lat: lat, lng: lon},
zoom: 14,
zoomControlOptions: {
position: google.maps.ControlPosition.LEFT_TOP
}
};

Google Maps refreshing everytime mouse is clicked

http://task4adamholt.appspot.com/?guestbook_name=Cars
For some reason every time the mouse is clicked, whether it be on the table or the actual map itself it refreshes all the maps for some reason.
Does anyone have any idea why, it's really strange. The .js file includes the following function
function getLoc(lon,lat,id) {
function initialize() {
var mapProp = {
center: new google.maps.LatLng(lat, lon),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(id), mapProp);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: 'Sent Here!'
});
}
google.maps.event.addDomListener(window, 'click', initialize);
document.getElementById(id).style.display = 'block';
}
This is the line that's causing the problem.
google.maps.event.addDomListener(window, 'click', initialize);
It listens for a click on the window, and runs the functions whenever a click happens, refreshing the map. I would definitely change the 'click' event to something else, like DOM ready.

jquery link toggle with google maps

Im having problems working out how to get this toggle working, by default it hides the map and when you click show map i want the map to slide down and change the link test to hide map which then of course will slide back up but does not seem to be working..... anyone got any ideas?
Also if anyone knows of a solution for the google maps issue im also having please let me know, because the made is hidden when you show / slides down it does not show most of the map (something about resizing i think i remember reading up on)
i have made a jsfiddle here: http://jsfiddle.net/DfVBb/ although does not work there at all for some reason. thanks in advance!
HTML
<div class="slideToggleBox">
<div id="map_div"> </div>
</div>
show map
JS
<script type="text/javascript">
$('#map_div').hide();
$('#slideToggle').click(function() {
$('#map_div').slideToggle('slow', function() {
$('#slideToggle').text('hide map');
}, function(){
$('#slideToggle').text('show map');
});
return false
});
</script>
Maps JS
$(document).ready(function() {
var latlng = new google.maps.LatLng(53.334583, -0.961674);
var options = {
zoom: 15, // This number can be set to define the initial zoom level of the map
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_div'), options);
var image = new google.maps.MarkerImage('/images/map-icon.png',
new google.maps.Size(680, 178),
new google.maps.Point(0,0),
new google.maps.Point(18, 50)
);
var marker1 = new google.maps.Marker({
position: new google.maps.LatLng(53.334583,-0.961674),
map: map,
icon: image
});
});
</script>
I managed to work out a solution for this and also fixing the resize issue
$(function () {
// create a center
var c = new google.maps.LatLng(53.334583, -0.961674);
//create map options object
var mapOptions = {
zoom: 14,
center: c,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
$("#slideToggle").click(function () {
$('#map_canvas').slideToggle(300, function(){
if ($('#slideToggle').text() !== "hide map") $('#slideToggle').text('hide map');
else $('#slideToggle').text('show map');
google.maps.event.trigger(map, "resize"); // resize map
map.setCenter(c); // set the center
}); // slide it down
});
});
I looked at your fiddle, it has to be cleaned. Based on my understanding, you're trying to toggle Google maps on button click.
Mistakes in your Fiddle:
(1) The Google maps is not initialized. The below is used to initialize Google maps.
google.maps.event.addDomListener(window, 'load', initialize);
(2) Your .slideToggle() has to be cleaned up. It has be somehow like
$('#slideToggle').on('click', function () {
$('#map_canvas').slideToggle('slow', function () {
if ($('#slideToggle').text() !== "hide map")
$('#slideToggle').text('hide map');
else
$('#slideToggle').text('show map');
});
return false;
});
I've created a JSFiddle, please go through it and share your thoughts.

google map api,chrome and firefox is right,but ie can't run

google map api,chrome and firefox is right,but ie can't run
I use jquery load initialize();
ie6 outpute error message is
error 'google' undefine
function initialize() {
var latlng = new google.maps.LatLng(39.979639,116.30209);
var myOptions = {
zoom: 12,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
$(document).ready(function(){
initialize();
});
You’re not actually calling the map initialisation function. You’d need to do something like:
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
But of course without that it wouldn’t work anything else either… Is the version of IE you’re testing in IE6? It’s not officially supported by Google Maps anymore.

Categories