I am having problems with a Google Map that I have inside a div, which upon button click, pops up on screen. The Google Map is only partially showing. I know that I need to that I need to create a resize event, but do not know how, or where to put it. Any help would be much appreciated! Please keep in mind that I have little knowledge of JS!
Link to test site: CLICK ON GOOGLE MAP BUTTON TO SEE THE PROBLEM AT HAND:
http://simplicitdesignanddevelopment.com/Fannie%20E%20Zurb/foundation/contact_us.html#
My Google API script:
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(39.739318, -89.266507),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
</script>
The div which contains the map:
<div id="myModal" class="reveal-modal large">
<h2>How to get here</h2>
<div id="map_canvas" style="width:600px; height:300px;"></div>
<a class="close-reveal-modal">×</a>
</div>
The script which calls the map upon button click:
<script type="text/javascript">
$(document).ready(function() {
$('#myModal1').click(function() {
$('#myModal').reveal();
});
});
</script>
Following Two solutions worked for me
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(39.739318, -89.266507),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
return map;
}
<div id="myModal" class="reveal-modal" data-reveal>
<div id="map_canvas" style="height: 300px"></div>
<a class="close-reveal-modal">×</a>
</div>
$(document).ready(function() {
var myMap;
$('#myModal').bind('open', function() {
if(!myMap) {
var myMap = initialize();
setTimeout(function() {
google.maps.event.trigger(myMap, 'resize');
}, 300);
}
});
}
OR
$(document).ready(function() {
var myMap;
$('#myModal').bind('opened', function() {
if(!myMap) {
var myMap = initialize();
google.maps.event.addDomListener(window, 'load', initialize);
}
});
});
First, based on the source linked to, the script which calls the map upon button click is doing nothing but throwing an error because you have it in the page before jQuery is loaded. You can see it in the error console. You need to move that to the bottom of the page after the rest of the scripts.
Your reveal is "working" because you are using the data-reveal-id attribute on the menu item and the reveal script wires it up automatically.
You are creating the map onload which is bad practice. Don't create it until/unless it is needed.
So to fix your issue, this is what I did. Remove the data-reveal-id from the menu item and replace it with an ID, or you can just use some other selector to access it. I changed it to id="myModal1" since that is what you had in your event code already.
Move your script which calls the map upon button click to the bottom, and change it to look like this:
$(document).ready(function() {
var map;
$('#myModal1').click(function() {
if(!map){
var mapOptions = {
center: new google.maps.LatLng(39.739318, -89.266507),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
$('#myModal').reveal();
});
});
This will create the map only when the user clicks the link to show it and only creates it once. That should fix it for you. If you have to, you can pass an opened callback to the reveal() call and trigger resize there but in my limited testing it was not necessary.
You can also get rid of the entire initialize function.
Now go get a band-aid and put some ice on that head.
Removing width: 600px; on the <div id="map_canvas"> and triggering resize on your map after opening the modal should do the trick:
$(".reveal-modal").on("reveal:opened", function(e) {
google.maps.event.trigger(map, 'resize')
});
Try this
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(39.739318, -89.266507),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
}
$( document ).bind( "pageshow", function( event, data ){
google.maps.event.trigger(map, 'resize');
});
</script>
$("#myModal").on('shown.bs.modal', function(){
google.maps.event.trigger(map, 'resize')
});
Related
I've just started trying to develop a website and I'd like to keep the html and javascript separate if I can. I'm trying to put a marker on a map, have the co-ordinates placed in a text box as part of a form, and have them sent to the database when the user submits the form. The code works when it's all inside the html doc, but when I try to separate it it doesnt work. Well, the map still shows up and I can set a marker on it, but it doesn't capture the co-ordinates.
In the head of the html
<script type="text/javascript" src="mapSubmitSighting.js"></script>
<body onload="initMap()">
Inside the div where I want the js to execute
<div id="map">
<div class="map" onclick="initMap();">
<script defer
src="https://maps.googleapis.com/maps/api/js?key==initMap"></script>
</div>
The js file
!function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 54.621277, lng: -6.692649 }
});
google.maps.event.trigger(map, "resize");
map.addListener('click', function(e) {
placeMarkerAndPanTo(e.latLng, map);
});
}
!function placeMarkerAndPanTo(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
map.panTo(latLng);
document.getElementById("lat").value = latLng.lat();
document.getElementById("lng").value = latLng.lng();
}
I know there's lots wrong with this but if I could just work out how to get the javascript to work it'd be a start. Thank you!
Most part of your code actually works.
Did a few modification though.
Added initial marker position as I noticed that you intended to do this on your sample code.
Also, refactored your code so needed routines will be re-usable.
Please check below.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 50%;
}
</style>
<script src="mapSubmitSighting.js"></script>
</head>
<body>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD72DV80rL8PBw2BTTWOwHV3NPSQdx24D8&callback=initMap"></script>
<br/>
<div>
Latitude: <input type="text" id="lat"/><br/><br/>
Longitude: <input type="text" id="lng"/>
</div>
</body>
</html>
JS
function initMap() {
var initialLocation = {lat: 54.621277, lng: -6.692649 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: initialLocation
});
var marker = setMarker(initialLocation, map);
setTextCoordinates(initialLocation.lat, initialLocation.lng);
google.maps.event.trigger(map, "resize");
map.addListener('click', function(e) {
placeMarkerAndPanTo(e.latLng, map);
});
}
function placeMarkerAndPanTo(latLng, map) {
var marker = setMarker(latLng, map);
map.panTo(latLng);
setTextCoordinates(latLng.lat(), latLng.lng());
}
function setMarker(latLng, map){
var marker = new google.maps.Marker({
position: latLng,
map: map
});
return marker;
}
function setTextCoordinates(lat, lng){
document.getElementById("lat").value = lat;
document.getElementById("lng").value = lng;
}
Output
Hope this helps!
You are probably not linking the file correctly.
You can open the developer tools (F12 in Chrome, or just right-click on some part of the page and select Inspect Element) and look at the errors in the console.
Most likely there's a 404 error. Look at the URL of the file, does it match the place where it is supposed to be? Are you missing a folder? Did you forget to upload it? Let us know so we can further assist!
You also do not need the ! in the beginning of your js function. This is preventing your html from reading the js file.
should look like -->
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,`enter code here`
I'm doing some experimentation with Google maps, and my aim is to place markers on a map which will depend on when it is dragged or resized, so I'm planning to use the "idle" event listener. The problem is that I can't get it to work.
I've put an alert box inside the idle listener to test it, but it doesn't get fired.
This is what I have so far:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script>
var map;
var geocoder;
var markers = [];
function initialize()
{
var myOptions = {
center: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
panControl: true,
zoomControl: true,
scaleControl: true
};
map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);
//regenerateMarkers(); // 29/7/15
}
// Initializes the Google Map
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addListener(map, 'idle', function() {
//regenerateMarkers(); // 29/7/15
alert("inside idle");
});
</script>
The html to display the map is as follows:
<div id="map_canvas" style="height: 450px; width: 900px;"></div>
I cannot for the life of me see why the idle listener is not firing to bring up the alert box. Can anyone please help? Many thanks!
You should bind idle event inside initialize function otherwise map couldn't be already loaded and event can't be bound.
I am trying to make tabs using js to have more data on the site.
Please view: http://dev.ateo.dk/officelab-konferencecenter/
The two tabs at the top ("Billeder" and "kort") are made using js.
If i go into the tap called "kort", the google maps will not load completely - however if i right-click and choose "Inspect Element (Q)" using firefox, the map suddenly loads.
Also, the map is not centered. on the specific location - the location is in the top left corner.
You may notice a blank square below the tab div. This is the exact same code as used within the js tab. If i comment out the in js tab, the square which is blank, will work perfectly. So it somehow seems that the js tab combined with the js google maps are not working. Can this be the case, and if so, how is it fixed?
Below i am showing the code which will init the google maps and the taps on the page:
if($('body.single-konferencested').length > 0)
{
tabs();
}
if($('body.single-konferencested').length > 0)
{
$(document).ready(function() {
function initialize() {
var myLatlng = new google.maps.LatLng(place_lat,place_lng);
var mapOptions = {
zoom: 9,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
clickable : true
});
var pinIcon = new google.maps.MarkerImage(
"http://dev.ateo.dk/wp-content/themes/ateo/img/pin_marker.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(24, 40)
);
marker.setIcon(pinIcon);
var content_string = '<div id="gmap_info">'+
'<div id="siteNotice">'+
'</div>'+
'<h3 id="firstHeading" class="firstHeading">'+place_title+'</h3>'+
'<div id="bodyContent">'+
'<p>'+place_address+'<br />'+place_city_zip+'</div>'+
'</div>';
var infowindow = new google.maps.InfoWindow({
content: content_string
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
});
}
This following is the html showing the DOM for the "Kort" tab:
<div class="tabContent" id="kort" style="padding: 5px 10px;">
<h2>Kort</h2>
<div id="gmap" style="width: 600px; height: 400px;"></div>
<h2>test</h2>
</div>
Best regards
Patrick
If the div in which the map is going to live is not visible on page load the map will not load correctly. You should fire a resize once the div has come into view.
google.maps.event.trigger(map, 'resize');
You should bind this to the first click of the map tab.
It looks like the map is commented out of the second tab currently. If you could uncomment it it would be easier to help you more specifically!
EDIT:
to bind the function once, try this:
var tab = jQuery('ul#tabs li')[1]
jQuery(tab).one('click', function(){
google.maps.event.trigger(map, 'resize');
});
In order for the resize to work you will need access to the map variable from your init function.
It would also be easier to select the correct tab if you drop a class on it. That would be more reliable then getting the 2nd li in the tabs ul.
EDIT 2:
try adding the click function in your initialize code. Something similar to the following
var mapOptions = {
zoom: 9,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('gmap'), mapOptions);
//add the code here, after the map variable has been instantiated
var tab = jQuery('ul#tabs li')[1]
jQuery(tab).one('click', function(){
google.maps.event.trigger(map, 'resize');
//fire a center event after the resize, this is also useful
// if bound to a window resize
map.setCenter(myLatlng)
});
//end of new code
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
clickable : true
});
It can be solved easily by re-initialize the Google Map on Tab click.
$('#kort').click(function(e) {
initialize();
resetMap(map);
});
This simple solution has found from here - How to Display Google Map Inside of a Hidden Div
I put Google Map inside a div, and made a slideToggle onto the div.
the Google Map doesn't display correctly.
Once the div expanded, it doesn't look right like the map below
Please check the code on jsFiddle Sample
<div class="click">
<div class="hide">
<div id="map" style="width:300px;height:140px;"></div>
</div>
</div>
You could wait until the map is loaded by adding an event listener for idle. This event will fire once the map is fully loaded and ready.
google.maps.event.addListenerOnce(map, 'idle', function() {
$('.hide').hide();
});
Here's the JSFiddle.
EDIT:
For anyone with a similar problem, here is the updated JSFiddle with the map positioned offscreen so it remains hidden without using display:none.
you need to wait until map finished render then you set hide a map
because map div was toggle when div on hiding and that make map looking wrong location
init function should look like this
function initialize() {
var latlng = new google.maps.LatLng(48.89376,2.33742);
var settings = {
zoom: 15,
center: latlng,
disableDefaultUI: true,
zoomControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), settings);
var marker=new google.maps.Marker({
position:latlng,
});
marker.setMap(map);
// on map idle set div hide
google.maps.event.addListenerOnce(map, 'idle', function() {
$('.hide').hide();
});
}
I'm using Twitter's Bootstrap for defining my CSS. I have made a page with three tabs. The second tab contains a map built with Google Maps. However when opening the page and switching to the second page with the map, the map is not rendered completely. Once I reload the page with the google maps tab as the selected tab the map loads entirely.
I read some posts that advised people with the same problem to add the following code to the javascript:
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
However this doesn't seem to be the solution. Please find the complete code below:
Javascript:
<script type="text/javascript">
function initialize() {
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("data.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({position: latlng, map: map});
}
});
}
</script>
HTML:
<div class="tab-pane" id="orange" style="background-color:#E3F2FF;">
<div id="map_canvas" style="width:780px; height:400px; overflow:;"></div>
</div>
How can I resolve this? Maybe I can add some javascript that reloads the google maps part once the tab is selected but I don't know how to do this....
Updated code still shows the error:
<div class="tab-pane" id="orange" style="background-color:#E3F2FF;">
<div id="map_canvas" style="width:780px; height:400px; overflow:;"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="util.js"></script>
<script type="text/javascript">
function initialize() {
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("data.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({position: latlng, map: map});
}
});
map.checkResize();
}
</script>
</div>
I was battling with this issue as well. I was using a modal form and it rendered the map when it was hidden. When the tab is shown, you need to trigger this code:
google.maps.event.trigger(map, 'resize');
map.setZoom( map.getZoom() );
Hopefully it will work for you. If that doesn't work, here is the link where I found the solution. Maybe there will be another helpful comment.
http://code.google.com/p/gmaps-api-issues/issues/detail?id=1448
There's a lot of solutions here and frankly they're all wrong. If you have to hi-jack the default functionality of Bootstrap tabs, you might as well not use Bootstrap tabs. If you're only calling resize after the tab is shown, you may still have issues with the GMaps interface (zoom level and such). You simply have to initialize the map after the tab is visible.
var myCenter=new google.maps.LatLng(53, -1.33);
var marker=new google.maps.Marker({
position:myCenter
});
function initialize() {
var mapProp = {
center:myCenter,
zoom: 14,
draggable: false,
scrollwheel: false,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
};
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
initialize();
});
You can see a working example in this bootply: http://www.bootply.com/102241
Note: if your interface is still glitchy, it could be this issue:
Google Maps API V3 : weird UI display glitches (with screenshot)
Using the most recent gmaps api, you just need to add this to your styling:
.gm-style img { max-width: none; }
.gm-style label { width: auto; display: inline; }
Works for me after testing different delays :
$(window).resize(function() {
setTimeout(function() {
google.maps.event.trigger(map, 'resize');
}, 300)
});
Hope it helps.
I have solved the problem by using
google.maps.event.trigger(map, 'resize');
inside show function in bootstrap-tab.js means at the time of showing the box you should trigger resize event and will work..
Edit: I have seen another link with the same answer
Google Maps API v3, jQuery UI Tabs, map not resizing
I have seen this link after solving the problem to find out the reason which is still unanswered that why resize event does not works on the click event of the tabs but works in the tab js
this works fine for me, I use jquery tabs
setTimeout(function() {
google.maps.event.trigger(map, "resize");
map.setCenter(new google.maps.LatLng(default_lat, default_lng));
map.setZoom(default_map_zoom);
}, 2000);
from this link https://code.google.com/p/gmaps-api-issues/issues/detail?id=1448
To show a google maps in a hidden div, the div must show before the map is created and loaded. Below is an example:
<div id="map_canvas" style="width:500px; height:500px"></div>
<script>
$(document).ready(function(){
$('#button').click(function() {
$('#map_canvas').delay('700').fadeIn();
setTimeout(loadScript,1000);
});
});
function initialize() {
var title= "Title";
var lat = 50;
var lng = 50;
var myLatlng = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:artTitle
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
</script>
For me, what it worked was to call the function that renders the map after the, in my case, the modal had shown.
All I had to do was:
$(document).on("shown", "#eventModal", function(){
bindMap(coordinates);
});
You can do the same with the tabs, because they also have a "shown" event.