Google Maps JS API: fitBounds and maintain center [duplicate] - javascript

I've been looking around for a solution to this problem, but i can't seem to find somthing that solves this. The closest i get is this thread. But this doesn't work.
What i'm trying to do is to run fitbounds based on a set of markers which works fine. But i would also like to center the map based on the users location (the bouncing marker in the plunk) and still keep all markers within the map view.
If i try to setCenter after fitBounds, some markers are outside of the map view.
Is there some nifty way of combining these two functions?
Here's the plunk illustrating the issue.
function initialize() {
var userCenter = new google.maps.LatLng(51.508742, -0.120850);
var userCenterMarker = new google.maps.Marker({
position: userCenter
});
userCenterMarker.setAnimation(google.maps.Animation.BOUNCE);
var mapProp = {
center: userCenter,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var bounds = new google.maps.LatLngBounds();
var markers = getMarkers();
$(markers).each(function() {
bounds.extend(this.position);
this.setMap(map);
});
userCenterMarker.setMap(map);
map.fitBounds(bounds);
setTimeout(function() {
map.setCenter(userCenter);
}, 1500);
}
Thanks!

Simple solution: Add your "user marker" to the bounds, do fitBounds, then decrement the resulting zoom by 1 and center on that marker.
bounds.extend(userCenterMarker.getPosition());
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map,'bounds_changed', function() {
map.setZoom(map.getZoom()-1);
});
working fiddle
More complex solution: Center on the "user marker", check to see if the marker bounds is completely included in the map's current bounds (map.getBounds().contains(markerBounds)), if not, decrement the zoom level by 1.

The above answer didn't work for me. Here's what did:
contained = true;
map.fitBounds(bounds);
map.setCenter(center);
newbounds = map.getBounds();
for (i = 0; i < l; i ++) {
if (!newbounds.contains(markers[i].getPosition())) {
contained = false;
}
}
if (!contained) map.setZoom(map.getZoom() - 1);

Related

Wrong position of infowindow on small zoom levels. Google maps api v3

On small zoom levels one place will be displayed twice or more (world map is repeated horizontally). When I place marker on map with coordinates (e.g. -32.05604, 115.74718) I will see it on map more than once. It's normal.
But if I try to show infowindow on mouse hover I will get wrong behaviour. Infowindow will be always showed near one of my markers and never near other, without relation what marker was under mouse cursor.
See example here: (try to move mouse to left marker on map).
https://jsfiddle.net/m3wpk1gr/1/
How to show infowindow for marker which under mouse?
My code:
function initialize() {
var myLatLng = new google.maps.LatLng(-32.05604, 115.74718),
myOptions = {
zoom: 1,
center: new google.maps.LatLng(-32.05604, 0)
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
marker.setMap(map);
var iw = new google.maps.InfoWindow();
marker.addListener('mouseover', function() {
iw.setContent('InfoWindow');
iw.open(map, this);
});
marker.addListener('mouseout', function() {
iw.close();
});
}
initialize();
I'm afraid there is nothing you can do to get the desired result(the position is correct, so when the position exists multiple times on a map, the API has to make a decision).
What you can do: set the optimized-option of the marker to false, then they will not be repeated at lower zoom-levels

Preserving Google map zoom to kml layer on checkbox click

I'm attempting to add multiple kml layers to a map that can be turned on and off with check boxes. I got that part working (yay!). When I click on a layer to turn it on, it zooms in (this is fine), but when I unclick to turn the layer off, it zooms back out to my map extent. How do I get it to preserve the zoom of the last loaded layer? Code below.
<script>
var map;
var watershedLayer = new google.maps.KmlLayer ({
url: 'http://mvihes.bc.ca/mapping/watersheds.kmz'
});
var ere1949Layer = new google.maps.KmlLayer ({
url: 'http://mvihes.bc.ca/mapping/ere1949.kmz'
});
function initialize() {
var parksville= new google.maps.LatLng(49.316786, -124.308768);
var mapOptions = {
zoom: 9,
center: parksville
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
check();
}
function check()
{
if(document.getElementById('watersheds').checked)
{watershedLayer.setMap(map);}
else
{watershedLayer.setMap(null);}
if(document.getElementById('ere1949').checked)
{ere1949Layer.setMap(map);}
else
{ere1949Layer.setMap(null);}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I tried using the preserveViewport function but it just stopped the layer from zooming in, which is not what I wanted. I'm new to javaScript so possibly I'm missing something obvious...any help would be appreciated!
jsfiddle
Set the map-property of a selected layer only when it's not set yet:
function check()
{
if(document.getElementById('watersheds').checked)
{if(!watershedLayer.getMap())watershedLayer.setMap(map);}
else
{watershedLayer.setMap(null);}
if(document.getElementById('ere1949').checked)
{if(!ere1949Layer.getMap())ere1949Layer.setMap(map);}
else
{ere1949Layer.setMap(null);}
}
http://jsfiddle.net/jhagmq7L/16/
You can also attach max and min zoom levels to the map, something to consider the over all map zoom when loading kml layers.
// sets the min and max zoom levels of the map
var opt = { minZoom: 6, maxZoom: 18 };
map.setOptions(opt);

Getting data stored in additional field of googlemap's marker

I'm working with google maps api and javascript which I am not much familiar with. Here's the code I use to draw markers on my map. I get Latitudes and Longitudes from my database:
var geocoder;
var map;
var jsonStr = '<?php echo json_encode($arajka) ?>';
var LatLong = JSON.parse(jsonStr);
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: new google.maps.LatLng(50.000001, 20.000001),
zoom: 12
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = [];
for(var i=0;i<LatLong.length;i++){
var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
marker.push(new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login}));
}
// trying to set some listener but it fails.
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
alert("ASDASDASD" + marker.ajdi);
});
}
So, this listener doesn't work, I don't know why. Well, I expect that it doesn't exactly know what marker is it about. When I tried to do it with a single one, like in tutorial, it worked properly. I don't know what to do when I have this array. Any suggestions please?
You have several mistakes in your code:
As #Hollister mentions, marker is an array, so you need to put the addListener call inside the loop;
You have to store the additional marker data into the marker, not into the marker array;
you have to use this in the listener, not marker.
for(var i=0;i<LatLong.length;i++){
var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
var this_marker = new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login});
this_marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
marker.push(this_marker);
// trying to set some listener but it fails.
google.maps.event.addListener(this_marker, 'click', function() {
map.setZoom(8);
map.setCenter(this.getPosition());
alert("ASDASDASD" + this.ajdi);
});
}

Google Maps API v3 not loading without fitbounds, zooming causing infinite loop/stackoverflow

Previous question here:
stack overflow with Google maps API (IE7 IE8)
I found the following question in the mean time: Google Maps API v3: Can I setZoom after fitBounds?
The solution there works just fine, when I have more than one marker on the map. However when I visit a subpage of groupbke.young.netaffinity.net eg. https://groupbke.young.netaffinity.net/hotels/ireland/dublin/dublin/young-testing-hotel-liege/specials/bed-and-breakfast
the map will only load if map.fitBounds() is called. On the other hand, even if the map is not loaded, it will throw a stack overflow error when I scroll above the map canvas.
Will throw a stack overflow anyway, if I try to use setZoom.
Any ideas?
var hoteldata = [
['Young Testing Hotel - Liège', 53.33932, -6.261427, '<div class="nearby-hotel"> <h1>Young Testing Hotel - Liège</h1> <div class="star-rating-1"></div><div class="clear"></div> <div class="nearby-hotel-image l"> <img src="http://groupbke.young.netaffinity.net/bookings/images/imagecache/3/0C9DBC143E18ED64059C1696A52D2941-60x60.jpg" border="1" class="imagetype1"/> </a> </div> <div class="nearby-hotel-description l"> <a class="nearby-hotel-desc" href="/hotels/ireland/dublin/dublin/young-testing-hotel-liege">Dublin\'s most luxurious design hotel is located in the heart of the city. Experience the best of both worlds when staying at this chic haven, to one side the tranquility and calm of St Stephen\'s Green and to the other, Grafton Street, Dublin\'s finest shopping avenue. From its central location, in amongst this buzzing vibrant city it is an easy stroll to explore the leading cultural, historical and leisure attractions. Or just step out to the chic shopping, high energy bars, fine dining restaurants and chattering Cafes.</a> Book Now </div> <div class="clear"></div> </div>', 4]
];
function initialize(mapid) {
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var bounds = new google.maps.LatLngBounds();
var map = new google.maps.Map(document.getElementById(mapid), myOptions);
var infowindow = new google.maps.InfoWindow();
var markers = [];
for (i = 0; i < hoteldata.length; i++) {
var latLng = new google.maps.LatLng(hoteldata[i][1], hoteldata[i][2]);
bounds.extend(latLng);
var img = '/images/hotel-marker.png';
if (hoteldata[i][4] == 2) {
img = '/images/country-marker.png';
}
if (hoteldata[i][4] == 3) {
img = '/images/guesthouse-marker.png';
}
if (hoteldata[i][4] == 4) {
img = '/images/hotel-self-marker.png';
}
var marker = new google.maps.Marker({
position: latLng,
icon: img,
shadow: '/images/marker-shadow.png'
});
markers.push(marker);
bindInfoWindow(marker, map, infowindow, hoteldata[i][3]);
}
var clusterStyles = [
{
opt_textColor: 'white',
url: '/images/m3-blue.png',
height: 65,
width: 64
},
{
opt_textColor: 'white',
url: '/images/m3-green.png',
height: 65,
width: 64
},
{
opt_textColor: 'white',
url: '/images/m3-orange.png',
height: 65,
width: 64
}
];
var mcOptions = {
styles: clusterStyles,
maxZoom:14
};
if (markers.length>1){
var markerCluster = new MarkerClusterer(map, markers, mcOptions);
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map, 'zoom_changed', function() {
var oldZoom = map.getZoom();
map.setZoom(oldZoom + (-7)); //Or whatever
});
} else if (markers.length == 1){
markers[0].setMap(map);
//google.maps.event.clearListeners(map, 'zoom_changed');
//google.maps.event.addListenerOnce(map, 'zoom_changed', function() {
// var oldZoom = map.getZoom();
// map.setZoom(oldZoom + (-7)); //Or whatever
// setTimeout('roomSetter(globalmap,globalzoom)',300);
//});
//google.maps.event.trigger(map,'zoom_changed');
//google.maps.event.clearListeners(map, 'zoom_changed');
//map.fitBounds(bounds);
//var oldZoom = map.getZoom();
//map.setCenter(bounds.getCenter());
//map.setZoom(oldZoom+(-7));
//map.setZoom(3);
//globalmap=map;
//globalzoom=map.getZoom()+(-7);
//setTimeout('zoomSetter(globalmap,globalzoom)',300);
}
}
var globalmap;
var globalzoom;
function zoomSetter(map, zoom){
//map.setZoom(zoom);
}
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
});
}
function initmaps() {
initialize('map_canvas');
initialize('map_thumb');
}
google.maps.event.addDomListener(window, 'load', initmaps);
I've set up 3 testpages to demonstrate the problem:
http://groupbke.young.netaffinity.net/maptest1.html
this has the setZoom() function and throws a stackoverflow error, even though this should be correct
http://groupbke.young.netaffinity.net/maptest2.html
this does nothing beyond adding the marker to the map. scroll zooming on the map still throws a stack error.
http://groupbke.young.netaffinity.net/maptest3.html
this has fitBound(), which in theory is not good, but works. can NOT adjust the zoom level after that, or it will throw a stackoverflow error. scroll zooming works.
What I was missing from the answer from my previous question was that an initial zoom level and center has to be set.
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
zoom:22,
center: new google.maps.LatLng(50.820645,-0.137376)
};
Also had to change the event to 'idle' on the multi marker zooming adjustment.
if (markers.length>1){
var markerCluster = new MarkerClusterer(map, markers, mcOptions);
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map, 'idle', function() {
var oldZoom = map.getZoom();
map.setZoom(oldZoom + (-7)); //Or whatever
});
}
Works like a charm after that.
When you have only one hotel, you create a LatLngBounds object containing only one point:
for (i = 0; i < hoteldata.length; i++) {
var latLng = new google.maps.LatLng(hoteldata[i][1], hoteldata[i][2]);
bounds.extend(latLng);
...}
but you then do a map.fitBounds(bounds) — this attempts an infinite zoom. While it's arguable that the API should be able to cope with that, it's equally arguable that it will attempt to do exactly what you tell it. It's possible that IE will behave differently to Firefox and other browsers.
Where you have commented out the fitBounds() in your quoted code in the question, that is present in your online page. Since that line only applies to instances where one marker is involved and the bounds object is a single point, I would replace it with a simple setZoom() instead.
map.setZoom(16);

Automatically opening marker info pane on google map

I've created a custom map with most things I want on it (custom icon and custom info bubble), however I can't find a solution to automatically open the markers info window on load, I've done alot of searching but can't seem to find anything the code I have so far is as follows, any help would be much appreciated:
function initialize() {
var myLatlng = new google.maps.LatLng(54.325109,-2.742226);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var countries = [
{
title:'Remedy',
lat:54.3210,
lon:-2.7438,
content:"<h2>Remedy</h2><p>address, <br />location, <br />postcode</p> <p><b>T:</b> 07595 153 835 <br /><b>E:</b> <a href='mailto:email'>email</a></p>"
}
];
for (var i = 0; i < countries.length; i++) {
var c = countries[i];
c.marker = new google.maps.Marker({
position: new google.maps.LatLng(c.lat, c.lon),
map: map,
icon: '/wp-content/themes/remedy/display_images/google_map_icon.png',
title: c.title});
c.infowindow = new google.maps.InfoWindow({content: c.content});
google.maps.event.addListener(c.marker, 'click', makeCallback(c));
}
function makeCallback(country) {
return function () {
country.infowindow.open(map, country.marker);
};
}
infowindow.open(map, marker);
}
Maybe it's not working because you just created the instance of the Map and didn't wait for the complete load of the map to open the InfoWindow.
Try something like this:
google.maps.event.addListenerOnce(map, 'tilesloaded', function(event) {
infowindow.open(map, marker);
});
According to the reference:
http://code.google.com/intl/en/apis/maps/documentation/javascript/reference.html#Map
tilesloaded - This event is fired when the visible tiles have finished loading.
Hmm, inforwindow does not refer to anything in your code, which is why it is not working.
Since you have one country in the list as of now you can do a quick test and intialize the infowindow variable with an actual info window, or better yet also since you have 1 item in the list, just define c to be outside the loop so you can access it and then open the popup passing it the map and the marker, something like this (assuming c has been defined outside the loop)
c.infowindow.open(map, c.marker);
var infowindow = new google.maps.InfoWindow({
content: "Test Route",
position: new google.maps.LatLng(38.8709866, -77.208055),
});
infowindow.open(map);

Categories