Google Maps API zoom on resize - google-maps-api-3

I have searched, researched and searched some more.
I am desperately trying to make it so my map changes its zoom automatically with different browser sizes as it keeps the markers on the map viewable. Right now the best thing that works for me is:
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
And even that is flawed. When the map becomes smaller, say on a mobile device, the markers eventually leave visibility since the zoom does not change. I need the zoom to change. Seemingly, this is the solution(I've done a lot of research, mostly from Stack Overflow):
map.fitBounds(firstB,secondB);
firstB, and secondB are the latitude and longitude that my markers use for their position.
I've even tried:
bounds = new google.maps.LatLngBounds();
bounds.extend(marker);
bounds.extend(smarker);
map.fitBounds(bounds);
Currently this is what I have:
<script>
var geocoder;
var map;
function initialize() {
firstB = new google.maps.LatLng(38.9395799,-104.7168500999999);
secondB = new google.maps.LatLng(38.9382571,-104.71727069999997);
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(38.938987, -104.717286);
var mapOptions = {
zoom:18,
center:latlng,
disableDefaultUI:true
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
map.fitBounds(firstB,secondB);
var styles=[
{
featureType:"road",
elementType:"labels",
stylers:[
{visibility:"off"}
]
}
];
map.setOptions({styles: styles});
var pinIcon = new google.maps.MarkerImage(
'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(52, 52)
);
var marker = new google.maps.Marker({
position: firstB,
map: map,
title: 'AVS',
icon:pinIcon,
});
var firstB_contentString = '<div><p>Medical Office Building</p><p class="infoContent">6007 E Woodmen Rd.</p><p class="infoContent">Colorado Springs, CO 80923</p></p></div>';
var firstB_infowindow = new google.maps.InfoWindow({
content: firstB_contentString
});
google.maps.event.addListener(marker, 'click', function() {
firstB_infowindow.open(map,marker);
});
var smarker = new google.maps.Marker({
position: secondB,
map: map,
title: 'AVS',
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
var secondB_contentString = '<div><p>General Hospital</p><p class="infoContent">6001 E. Woodmen Rd.</p><p class="infoContent">Colorado Springs, CO 80923</p></div>';
var secondB_infowindow = new google.maps.InfoWindow({
content: secondB_contentString
});
google.maps.event.addListener(smarker, 'click', function() {
secondB_infowindow.open(map,smarker);
});
google.maps.event.addListener(map, 'mousedown', function() {
firstB_infowindow.close(map,marker);
secondB_infowindow.close(map,smarker);
});
google.maps.event.addListener(marker, 'mousedown', function() {
firstB_infowindow.close();
secondB_infowindow.close();
});
google.maps.event.addListener(smarker, 'mousedown', function() {
firstB_infowindow.close();
secondB_infowindow.close();
});
/*bounds = new google.maps.LatLngBounds();
bounds.extend(marker);
bounds.extend(smarker);
map.fitBounds(bounds);*/
}
google.maps.event.addDomListener(window, 'load', initialize);
/*google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});*/
</script>
Nothing works.

Fix your bounds, make that global and call map.fitBounds in the resize handler code:
var bounds = new google.maps.LatLngBounds();
function initialize() {
var firstB = new google.maps.LatLng(38.9395799,-104.7168500999999);
var secondB = new google.maps.LatLng(38.9382571,-104.71727069999997);
bounds.extend(firstB);
bounds.extend(secondB);
Then:
google.maps.event.addDomListener(window, "resize", function() {
google.maps.event.trigger(map, "resize");
map.fitBounds(bounds);
});
working fiddle
code snippet:
var geocoder;
var map;
var bounds = new google.maps.LatLngBounds();
function initialize() {
var firstB = new google.maps.LatLng(38.9395799,-104.7168500999999);
var secondB = new google.maps.LatLng(38.9382571,-104.71727069999997);
bounds.extend(firstB);
bounds.extend(secondB);
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(38.938987, -104.717286);
var mapOptions = {
zoom:18,
center:latlng,
disableDefaultUI:true
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
map.fitBounds(bounds);
var styles=[
{
featureType:"road",
elementType:"labels",
stylers:[
{visibility:"off"}
]
}
];
map.setOptions({styles: styles});
var pinIcon = new google.maps.MarkerImage(
'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
null, /* size is determined at runtime */
null, /* origin is 0,0 */
null, /* anchor is bottom center of the scaled image */
new google.maps.Size(52, 52)
);
var marker = new google.maps.Marker({
position: firstB,
map: map,
title: 'AVS',
icon:pinIcon,
});
var firstB_contentString = '<div><p>Medical Office Building</p><p class="infoContent">6007 E Woodmen Rd.</p><p class="infoContent">Colorado Springs, CO 80923</p></p></div>';
var firstB_infowindow = new google.maps.InfoWindow({
content: firstB_contentString
});
google.maps.event.addListener(marker, 'click', function() {
firstB_infowindow.open(map,marker);
});
var smarker = new google.maps.Marker({
position: secondB,
map: map,
title: 'AVS',
icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png'
});
var secondB_contentString = '<div><p>General Hospital</p><p class="infoContent">6001 E. Woodmen Rd.</p><p class="infoContent">Colorado Springs, CO 80923</p></div>';
var secondB_infowindow = new google.maps.InfoWindow({
content: secondB_contentString
});
google.maps.event.addListener(smarker, 'click', function() {
secondB_infowindow.open(map,smarker);
});
google.maps.event.addListener(map, 'mousedown', function() {
firstB_infowindow.close(map,marker);
secondB_infowindow.close(map,smarker);
});
google.maps.event.addListener(marker, 'mousedown', function() {
firstB_infowindow.close();
secondB_infowindow.close();
});
google.maps.event.addListener(smarker, 'mousedown', function() {
firstB_infowindow.close();
secondB_infowindow.close();
});
/*bounds = new google.maps.LatLngBounds();
bounds.extend(marker);
bounds.extend(smarker);
map.fitBounds(bounds);*/
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
google.maps.event.trigger(map, "resize");
map.fitBounds(bounds);
});
html, body, #map-canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas" style="border: 2px solid #3872ac;"></div>

Related

Google Maps display none document ready

I have a problem with the wrapper for the Google map. The class is set by document ready to display:none. If I click on the link the map must be set on show(). It works, but the map doesn't display right.
Here's a screenshot:
And here is my JSFiddle example.
Here my HTML code:
show map
<div class="advertise-mapper">
<div class="responsiveContaineradv">
<div id="map-canvas" class="map-adver"></div>
</div>
</div>
Here my JS Code:
jQuery(document).ready(function() {
jQuery(document).on("click", ".advertise-map", function(e) {
e.preventDefault();
jQuery('.advertise-mapper').show();
});
});
var map;
function initialize() {
var locations = [
['<h4>BMX Golden MILE 20 Fahrrad</h4>250.00 €<br>zur Kleinanzeige', 51.4627921, 6.9787572],
['<h4>Apple Macbook Air 13 A1466 Juni 2013</h4>800.00 €<br>zur Kleinanzeige', 51.665041, 7.631431],
['<h4>Apple iPod nano 16 GB Grün 6. Generation</h4>60.00 € VB<br>zur Kleinanzeige', 51.5096015, 7.377755],
];
var myLatlng = new google.maps.LatLng(51.513587, 7.465298);
var mapOptions = {
zoom: 11,
center: myLatlng
}
var infowindow = new google.maps.InfoWindow({
maxWidth: 360
});
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var markers = new Array();
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
animation: google.maps.Animation.DROP
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
function autoCenter() {
// Create a new viewpoint bound
var bounds = new google.maps.LatLngBounds();
// Go through each...
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i].position);
}
// Fit these bounds to the map
map.fitBounds(bounds);
}
autoCenter();
}
google.maps.event.addDomListener(window, 'load', initialize);
How can I make the map display correctly when shown?
I would make a few small corrections, the most important of which goecodezip mentioned in the comments.
In your onclick of .advertise-map, add the map resize (important) and autoCenter (optional).
jQuery(document).on("click",".advertise-map",function(e){
e.preventDefault();
jQuery('.advertise-mapper').show();
google.maps.event.trigger(map, "resize");
autoCenter();
});
Next, I'd make 'markers' a global variable:
var map;
var markers = new Array();
Finally, I'd move the autoCenter() function out from the initialize function.
With all those changes, I believe this is what you're looking for: http://jsfiddle.net/2xn7wywo/22/

Trying to find error why map isn't centered when resize window

I'm using a dom listener to set the center of the map when a user is resizing the window, but i'm confused because nothing happens!? What have I missed? Every thing else works fine with the map in responsive design. Help is preciated.
If someone is wondering why I have this code {$mapPoints} this is a PHP string of all markers.
EDIT 2:
At start I have the markers in the center of the map. Then I pan the map and the markers isn't in the center any more. When I resize the window I want the markers at the center of the map as it was from the beginning (55.678939, 12.568359). Have I miss understodd something or isn't this possible? I have also tried to set the center of the map to the these coordinates when resizing the window.
EDIT 1:
CSS for the map:
#map_canvas
{
width: 100%;
height: 350px;
margin: 20px 0 20px 0px;
}
var map = null;
var infowindow = new google.maps.InfoWindow();
var iconBase = 'images/mapNumbers/number';
function initialize() {
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(55.678939, 12.568359),
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(55.678939, 12.568359);
var center = map.getCenter();
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
// Add markers to the map
var point;
{$mapPoints}
}
// 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());
});
}
google.maps.event.addDomListener(window, 'load', initialize);
It seems that at the beginning you almost got it right. I did the following changes:
function initialize() {
var markerPos = new google.maps.LatLng(55.678939, 12.568359);
var myOptions = {
center: markerPos,
...
}
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var marker = new google.maps.Marker({
position: markerPos,
...
});
google.maps.event.addDomListener(window, 'resize', function() {
console.log('window resize');
map.setCenter(markerPos);
var center = map.getCenter();
console.log(center);
// google.maps.event.trigger(map, 'resize');
});
Test should be like you wrote: load the map, pan to the left/right, resize the window. Marker and the map should be centered.
Take a look at the bounds_changed event:
google.maps.event.addListener(map, 'bounds_changed', function() {
//do really cool stuff and change the world or at least a map of it
}

Show One WindowInfo Per Marker(Google Map)

I try this but I can only last windowInfo.
Help me please
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(33.414837,54.68141),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById('map'),mapOptions);
/*var weatherLayer = new google.maps.weather.WeatherLayer({
temperatureUnits: google.maps.weather.TemperatureUnit.Degree
});
weatherLayer.setMap(map);*/
/*var cloudLayer = new google.maps.weather.CloudLayer();
cloudLayer.setMap(map)*/
for (i = 0; i < StationListArray.length; i++) {
var image = StationListArray[i].split("|")[4];
var StationLocation = new google.maps.LatLng(StationListArray[i].split("|")[2], StationListArray[i].split("|")[1]);
var marker = new google.maps.Marker({
position: StationLocation,
map: map,
title: StationListArray[i].split("|")[0],
icon: image
});
google.maps.event.addListener(marker,'click',function() {
var infowindow = new google.maps.InfoWindow({
content:"Hello World!"});
infowindow.open(map,marker);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Change the 2nd argument of open() to this
infowindow.open(map,this);
marker refers to the variable marker, which will be overwritten on each iteration. When the loop has been finished, it points to the last marker that has been created. this inside the click-callback refers to the marker that has been clicked.

Adding Google maps InfoWindow Dynamically Wordpress

I am trying to add a Google maps InfoWindow Dynamically to Wordpress, this is the code that is currently working with a custom marker I have tried several functions for infowindows but it seems to be breaking and not loading the map. not sure what I might be doing wrong.
this works I just need to add a infoWindow
<script type="text/javascript">
//<![CDATA[
function load() {
var styles =
[
{
"stylers": [
{ "lightness": 1 },
{ "saturation": -76 },
{ "hue": "#3bff00" }
]
}
];
var lat = <?php echo $lat; ?>;
var lng = <?php echo $lng; ?>;
// coordinates to latLng
var latlng = new google.maps.LatLng(lat, lng);
// map Options
var myOptions = {
zoom: 14,
scrollwheel: false,
center: latlng,
mapTypeId: 'Styled'
};
//draw a map
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var styledMapType = new google.maps.StyledMapType(styles, { name: 'Styled' });
map.mapTypes.set('Styled', styledMapType);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
icon: '/wp-content/themes/bills_theme/images/pin_bills.png',
});
}
// call the function
load();
//]]>
</script>
A simple infowindow would be (not tested):
//draw a map
var map = new google.maps.Map(document.getElementById("map"), myOptions);
var styledMapType = new google.maps.StyledMapType(styles, { name: 'Styled' });
map.mapTypes.set('Styled', styledMapType);
var marker = new google.maps.Marker({
position: map.getCenter(),
map: map,
icon: '/wp-content/themes/bills_theme/images/pin_bills.png',
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, "click", function(e) {
infowindow.setContent("Hello world");
infowindow.open(map,marker);
});
google.maps.event.trigger(marker, "click");
}
// call the function
Just add this code:
var contentString = 'put your content here.';
google.maps.event.addListener(marker, 'click', function() {
var infowindow = new google.maps.InfoWindow({
content: contentString,
position: latlng,
maxWidth: 200
});
infowindow.open(map);
});
More info about Info Window you can read HERE.

close InfoWindow before open another

I have a problem with InfoWindow. I have an ajax function that retrieves data via JSON, but I can not get close InfoWindow automatically when you open another.
My code is this:
var mapOptions = {
center: new google.maps.LatLng(44.49423583832911, 11.346244544982937),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mappa_locali"),mapOptions);
$.ajax({
type:'GET',
url:"locali_json.php"+urlz,
success:function(data){
var json = JSON.parse(data);
for (var i=0; i<json.length; i++) {
point = new google.maps.LatLng(json[i].latitudine,json[i].longitudine);
var infowindow = new google.maps.InfoWindow;
infowindow.setContent(''+json[i].nome_locale+'<br>'+json[i].address);
addMarkerz(point,infowindow);
}
}
})
}
function addMarkerz(point,infowindow) {
position: point,
map: map
});
google.maps.event.addListener(marker,'mouseover',infoCallback(infowindow, marker));
markers.push(marker);
infos.push(infowindow);
}
function infoCallback(infowindow, marker) {
return function() {
infowindow.close();
infowindow.open(map, marker);
};
}
Does anyone know where decreased mistake? Or do you have any advice for me?
The suggestion is only create one infowindow (in the global scope), reuse it and change its contents when a marker is clicked, close it if the user clicks on the map.
code snippet (removes the dependency on the AJAX call):
// global variables
var map;
var markers = [];
var infowindow = new google.maps.InfoWindow();
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(44.49423583832911, 11.346244544982937),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mappa_locali"), mapOptions);
var json = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
point = new google.maps.LatLng(json[i].latitudine, json[i].longitudine);
var infowindowHtml = '' + json[i].nome_locale + '<br>' + json[i].address;
addMarkerz(point, infowindowHtml);
}
}
function addMarkerz(point, infowindowHtml) {
var marker = new google.maps.Marker({
position: point,
map: map
});
google.maps.event.addListener(marker, 'mouseover', infoCallback(infowindowHtml, marker));
markers.push(marker);
}
function infoCallback(infowindowHtml, marker) {
return function() {
infowindow.close();
// update the content of the infowindow before opening it
infowindow.setContent(infowindowHtml)
infowindow.open(map, marker);
};
}
var data = JSON.stringify([{
latitudine: 44.494887,
longitudine: 11.3426163,
id_locale: "0",
nome_locale: "Bologna",
address: "Bologna, Italy"
}, {
latitudine: 44.4946615,
longitudine: 11.314634999999953,
id_locale: "0",
nome_locale: "Quartiere Saragozza",
address: "Quartiere Saragozza, Bologna, Italy"
}]);
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#mappa_locali {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="mappa_locali"></div>
function infoCallback(infowindow, marker) {
return function() {
infowindow.close();
infowindow.open(map, marker);
};
}
should be changed to
function infoCallback(infowindow, marker) {
return function() {
//Close active window if exists
if (activeWindow != null) {
activeWindow.close();
}
//Open new window
infowindow.open(map,marker);
//Store new window in global variable
activeWindow = infowindow;
};
}
and declare activeWindow as a global variable in your .js file as var activeWindow.
I think I have a simple solution. I just save the last open mark. On the next click first of all I close the last mark.
var markers = [];
var infowindows = [];
function addMarkes(facilityID) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < variants.length; i++) {
var v = variants[i];
var position = new google.maps.LatLng(v.Lat, v.Long);
bounds.extend(position);
markers[i] = new google.maps.Marker({
position: position,
title: v.Title,
map: map,
animation: google.maps.Animation.DROP,
icon: v.Icon,
infoWindowIndex: i //synchronize with infoWindows
});
var localContent = '<div><span class="address">' + v.Address + '</span></div>';
infowindows[i] = new google.maps.InfoWindow({
content: localContent
});
//Just for multiple marks.
if (variants.length > 0) {
var lastOpen = -1; //Save the last open mark
google.maps.event.addListener(markers[i], 'click', function (innerKey) {
return function () {
//Close the last mark.
if (lastOpen > -1) {
infowindows[lastOpen].close();
}
infowindows[innerKey].open(map, markers[innerKey]);
lastOpen = innerKey;
}
}(i));
}
}
map.fitBounds(bounds);
}

Resources