Google Maps API v3: Gray Box, no map - google-maps

As part of a much bigger project, we're trying to get a Map on a site using Google's Map API v3. I have followed the simplest steps that Google has laid out, I've tried copying code outright from other working maps. But no matter what I do, all we get is a gray box and no map.
Using Firebug, I can see the information trying to populate the map, but it is simply not displaying. I've tried jquery, jquery libraries specifically made for google maps, nothing is working. I have been up and down the internet and all through google's api help files. Plus, the problem is not local as I've uploaded the file to multiple servers and tested it on multiple browsers and computers. Nothing is working.
At this point it's got to be something stupid that I'm overlooking. Here's my code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?&sensor=true">
</script>
<script type="text/javascript">
function load()
{
var mapDiv = document.getElementById("map");
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions =
{
//zoom: 8,
center:latlng,
//backgroundColor: '#ff0000',
mapTypeId: google.maps.MapTypeId.ROADMAP,
imageDefaultUI: true
};
var map = new google.maps.Map(mapDiv, mapOptions);
function createMarker(point, text, title)
{
var marker =
new GMarker(point,{title:title});
return marker;
}
}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 800px; height: 400px;"></div>
</div>
</body>
</html>

This works for me. You simply have to set zoom parameter:
UPDATE (by #user2652379): You need to set BOTH zoom and center options. Just zoom does not work.
<!DOCTYPE html>
<html>
<head>
<title></title>
<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</script>
<script type="text/javascript">
function load()
{
var mapDiv = document.getElementById("map");
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions =
{
zoom: 8,
center:latlng,
//backgroundColor: '#ff0000',
mapTypeId: google.maps.MapTypeId.ROADMAP,
//imageDefaultUI: true
};
var map = new google.maps.Map(mapDiv, mapOptions);
// map.addControl(new GSmallMapControl());
// map.addControl(new GMapTypeControl());
// map.addMapType(ROADMAP);
// map.setCenter(
// new GLatLng(37.4419, -122.1419), 13);
}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 800px; height: 400px;"> </div>
</body>
</html>

Another case is when map container is hidden at the moment you initialize the map. E.g. you are doing it inside bootstrap show.bs.modal event, instead of shown.bs.modal

I had the same issue and came across a lot of topics on stackoverflow but none of them had the working solution for me. I eventually found out it was caused to a line of css I had added.
All the elements in the map inherited a
overflow:hidden;
By adding the following line to my CSS it was fixed
#map * {
overflow:visible;
}

I would like to add a quick comment to this since I had the same problem with the zoom parameter set.
I found out that the problem was my theme's css. In my base theme I had the following CSS:
img, embed, object, video {
max-width: 100%;
max-height: 100%;
width: auto;
height: auto;
}
This messed up the rendering of the map and after I removed it, my map renders just fine.

Also beware of having an invalid latitude or longitude value for the map center or your markers. For example, this fiddle shows the Grey Map Of Death because the map center is at latitude 131.044 which is invalid (not from +90:-90).
function initMap() {
var uluru = {lat: 131.044, lng: -25.363};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}

In my case, I was working on a map with vue and a modal in the iview library; and during the first render it worked, but any other render displayed the grey screen of death. I fixed the issue by setting a timeout function to display the map after 50 ms to give the modal enough time to render and be visible.
//Time out is crucial for the map to load when opened with vue
setTimeout(() => {
this.showMap(id);
}, 50);
The above example was an earlier fix and a quick hack, i have realized all you need to do is wait for the next tick, on vue you can achieve this by
async mounted(){
await this.$nextTick()
this.showMap(id)
}
or if you are not comfortable with async await you can try the callback option
mounted(){
Vue.nextTick(function () {
this.showMap(id)
})
}

I had the same issue. i was using google maps in Jquery Accordion and when i expand the div the map only consisted a grayed area. I was able to solve this issue by triggering a click event on the specified accordion heading and setting the map container to visible.
Script:
<script type="text/javascript">
var map;
function initMap(lat, lng) {
var myCenter = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: myCenter
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
}
function ViewMap() {
var latlng = document.getElementById('<%=txt.ClientID%>').value.split(','); // This is where my latlng are placed: 25.12312,55.3212333
$("#showmap").show();
// Sorry for mixing up Jquery and javascript.
initMap(latlng[0], latlng[1]);
}
</script>
ASPX File/Html Markup:
<h3 id="lMap" onclick="ViewMap();"><i class="fa fa-map-o" onclick="ViewMap();"></i>Location Map</h3>
<div style="height:auto" id="showmap">
<div id="map" style="width: 850px; height: 550px; overflow: visible"></div>
</div>

I realise this is an old thread, but this may help someone in the future.
Struggled with this for hours, but after discovering that the Google Map is rendered with a grey box overlay if the map is rendered while not being visible, I used a bit of jQuery to make my application only instantiate and render the map if the map is visible, like such:
if ($("#myHomeMapHolder").is(":visible")) {
if (homemap == null) {
homemap = new google.maps.Map(document.getElementById("myHomeMapHolder"), myOptions);
google.maps.event.addListener(homemap, 'click', function (event) {
placeHomeMarker(event.latLng);
});
} else {
homemap.setCenter(myLatlng);
}
if (homemarker == null) {
homemarker = new google.maps.Marker({
position: myLatlng,
map: homemap,
title: "Home"
});
} else {
homemarker.setPosition(myLatlng);
}
}
And voila, my map is only rendered if the map holder is visible, so it never renders with a grey box.
For anyone wondering, myHomeMapHolder is a div which the map sits inside.

In my case, someone had dropped this little prize in some responsive.css file:
img {
max-width: 100% !important;
}
Removed that and all is fine now.

I had this issue with a site I'm working on too. We're doing some things to all <img> tags for responsiveness. This fix is working for us for the map:
img {max-width: initial !important;}

For those who might be stuck regardless of the nice solutions provided here, try setting the height and width of your container directly in the html markup instead of a stylesheet ie.
<div id="map-container" style="width: 100%; height: 300px;"></div>
happy mapping!

This may not be the case for everyone, but maybe it can help someone.
I was creating markers in my map from data attributes placed on the map element like this: data-1-lat="2" data-1-lon="3" data-text="foo". I was putting them in an array based on the order they were placed in the data attributes.
The problem is that IE and Edge (for some mad reason) invert the order of the data attributes in the HTML tag, therefore I wasn't able to correctly extract them from the data attributes.

None of the existing answers helped me because my problem was that Apollo was adding extra properties ("__typename" fields) to my MapOptions object.
In other words, the JSON looked like this:
mapOptions {"__typename":"MapOptions","center":{"__typename":"GeoCoordinates","lat":33.953056,"lng":-83.9925},"zoom":10}
Once I realized that those extra properties were problematic, this is how I solved it (using TypeScript):
function getCleanedMapOptions(mapOptionsGql: google.maps.MapOptions): google.maps.MapOptions {
const mapOptions = { ...mapOptionsGql };
const lat: number = mapOptions.center.lat as number;
const lng: number = mapOptions.center.lng as number;
const mapOptionsCleaned = {
center: new google.maps.LatLng({ lat, lng }),
zoom: mapOptions.zoom,
};
return mapOptionsCleaned;
}
export function createMap(mapOptions: google.maps.MapOptions): google.maps.Map {
const mapOptionsCleaned = getCleanedMapOptions(mapOptions);
const map = new google.maps.Map(document.getElementById('map') as HTMLElement, mapOptionsCleaned);
return map;
}

In my case (version is 3.30 when submitting this), it was because the div id MUST be "map"
<div id="map"></div>
...
document.getElementById("map")

Related

Grey area in Google Maps (Joomla 3+)

Good afternoon,
I'm trying to implement a Google Maps inside my SobiPro entries (SobiPro is a directory component for Joomla) but it's not working properly. My map is showing some parts with a grey color and after searching and finding a lot of solutions, I need you to ask for help because any of the other solutions worked.
I have tried everything and it's still not working.
Here is the URL, in the third label you will find my map "Direccion" is called: http://bdebeauty.es/component/sobipro/268
What can I do to solve this problem?
Edit with more code:
<style>
#map-canvas {
margin: 0px;
padding: 0px;
}
</style>
<script>
function initialize2() {
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Hello World!'
});
}
google.maps.event.addDomListener(window, 'load', initialize2);
</script>
<div id="map-canvas" style="width:450px;height:300px;"></div>
Thanks in advance.
I think what you will need is something like google.maps.event.trigger(map, 'resize');
as it is said in the documentation,
Developers should trigger this event on the map when the div changes size: google.maps.event.trigger(map, 'resize') .

Google Map embedded in website loading Google page rather than the map

I have this website - http://www.gyroontario.ca/contact/ which has a Google Map embedded within it. This has worked fine for many years but all of a sudden the embedded map is trying to load the Google Maps page instead of just embedding the map.
If you load the link, it initially loads the map correctly but then all of a sudden it loads the maps page with all the Google main menu and sidebar.
Is there something that has been changed by Google because we haven't touched the site for a long time. How can I fix this?
This is an image of what it's embedding:
This is the code I've embedded:
<iframe width="525" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=50+Skyway+Drive,+Guelph,+ON+N1H+6H8&aq=&sll=51.502241,-3.19941&sspn=0.260515,0.380058&ie=UTF8&hq=&hnear=Skyway+Dr,+Guelph,+Wellington+County,+Ontario+N1H+6H8,+Canada&t=m&ll=43.565031,-80.19762&spn=0.021767,0.045061&z=14&iwloc=A&output=embed"></iframe>
This is how I'm getting the code, just a simple google embed code:
The iframe contains the URL
https://maps.google.co.uk/maps?f=q&source=s_q&hl=en&geocode=&q=50+Skyway+Drive,Guelph,+ON+N1H+6H8&aq=&sll=43.361335,-79.923517&sspn=1.217084,1.520233&gl=uk&ie=UTF8&hq=&hnear=Skyway+Dr,+Guelph,+Wellington+County,+Ontario+N1H+6H8,+Canada&t=m&ll=43.565031,-80.19762&spn=0.012438,0.023861&z=14&iwloc=A&output=embed?wmode=transparent
which directly refers the UK's Google maps. I'm not sure how it worked initially and later changed.
But you can fix by using the [Google maps v3] (used now a days)(https://developers.google.com/maps/documentation/javascript/examples/map-simple).
Remove iframe and try doing the below and use Google Maps JavaScript API v3.
HTML:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<div id="map-canvas"></div>
CSS:
#map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
Javascript:
function initialize() {
var myLatlng = new google.maps.LatLng(43.565529, -80.197645);
var mapOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//=====Initialise Default Marker
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'marker'
//=====You can even customize the icons here
});
//=====Initialise InfoWindow
var infowindow = new google.maps.InfoWindow({
content: "<B>Skyway Dr</B>"
});
//=====Eventlistener for InfoWindow
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I have created a simple fiddle for your reference.
Hope you got some idea.
Updates:
I think the problem is with wmode=transparent in the iframe URL. When I remove it is working. Check fiddle1 and fiddle2
See difference between 1 and 2.
Clean up your page (line ~85):
window.onload = function() {
var frames = document.getElementsByTagName("iframe");
for (var i = 0; i < frames.length; i++) {
frames[i].src += "?wmode=transparent";
}
}
is responsible the loading of the complete google maps page.
You can easily check this by creating an empty page with the google maps-iframe element only (will work)
and than adding the window.onload from your page.
BTW: contact/tooltip.css is missing.

JQuery Mobile and Google Maps Not Rendering Correctly

I am simply trying to display a google map within a jquery mobile page. If I load the page directly it works. However, if I navigate to the page from another page it only renders a single map tile. At first glance it would appear that my issue was similar to https://forum.jquery.com/topic/google-maps-inside-jquery-mobile
However, I was already performing my initialization within the 'pageinit' event and my map div has a set width and height.
I have seen http://code.google.com/p/jquery-ui-map/ but I would rather not use a (another) third party plugin if at all possible.
Here's what my page looks like:
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="cordova-1.6.1.js"></script>
<link rel="stylesheet" href="jquery.mobile-1.1.0.min.css" />
<script src="jquery-1.7.1.min.js"></script>
<script src="global.js"></script>
<script src="jquery.mobile-1.1.0.min.js"></script>
</head>
<body>
<div id="mapPage" data-role="page">
<style type="text/css">
html
{
height: 100%;
}
body
{
height: 100%;
margin: 0;
padding: 0;
}
#map_canvas
{
height: 100%;
}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=***API_KEY_REMOVED***&sensor=true">
</script>
<script type="text/javascript">
function initialize() {
var height = $(window).height() - 50;
var width = $(window).width();
$("#map_canvas").height(height);
$("#map_canvas").width(width);
var myLatlng = new google.maps.LatLng(39.962799, -82.999802);
var myOptions = {
center: myLatlng,
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
//alert($(map.getDiv()).width());
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: ""
});
google.maps.event.trigger(map, 'resize')
}
$("#mapPage").live('pageinit', function () {
initialize();
});
</script>
<div data-role="header" id="menuHeader">
<a href="MenuDialog.htm" class="menuLink" data-role="none" data-rel="dialog">
<img class="headerIcon" style="height: 40px; border-right: 1px solid #333333; padding-right: 5px;"
id="MenuIcon" src="images/menuIcon.png" /></a>
<p>
Loc
</p>
</div>
<div data-role="content">
<div id="map_canvas" style="margin-top: 50px;">
</div>
</div>
</body>
<html>
Thanks in advance for you help.
Update:
After some experimenting I added the following delay to my resize event:
setTimeout(function() {
google.maps.event.trigger(map,'resize');
}, 500);
This seemed to fix the issue. Hopefully this helps someone else.
I read on a website that if you have this problem it's beacuse the dom isn't totally loaded when you initialize your google map.
You must add this in your code:
$( document ).bind( "pageshow", function( event, data ){
google.maps.event.trigger(map, 'resize');
});
It works for me. It's maybe brutal to resize at every page you show but ... it works.
You have <html> and <body> at 100% size, but not the <div>s in the hierarchy between <body> and <div id="map_canvas">.
Try adding those to your CSS as well (the content one will need an id).
You may also need to ensure that the API knows the size of the map <div> by triggering a resize event when everything is ready. Showing only a single tile is a classic symptom of the API getting it wrong (and generally assuming it has zero size).
Instead of firing a resize, I solved this by wrapping my js in a 'pagecreate' event... like this:
$(document).on('pagecreate', '#map', function() {
var mapOptions = {
center: new google.maps.LatLng(40.773782,-73.974236),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
});
I think the right approach would be to trigger the event when partial tile is loaded once. Below code snippet will help you in achieving that.
google.maps.event.addListenerOnce(map, 'tilesloaded', function(){
google.maps.event.trigger(map,'resize');
});
I found the issue for me was that JQuery mobile uses Ajax to load the pages. I am not sure if it is the best practice but I simply forced it to load my map page normally by putting the following code in the anchor tag:
data-ajax="false"

Google Map API v3 off center if reloaded (not the usual 'resize' thing)

I read all the similar questions but mine is slightly different. The first time a JQuery Mobile dialog is displayed, the map loads fine inside the usual map_canvas div, but if the dialog is reloaded (i.e. go back and click on the button to open the dialog again), it is displayed only partially, zoomed out to a 3 or 4 and centered around the div's top-left corner.
There is no change in the div size (which is explicitly set) and for good measure a google.maps.event.trigger(map, 'resize'); is called.
I also tried to initialize the map after the dialog is shown but the result is the same.
Button code:
$("#dest-map-button").click(function() {
initializeMap(job_id,"map_canvas");
}
);
Function:
function initializeMap(job_id, map_div){
var pos = arrJobs[job_id].lat_lng.split(',');
var job_pos = new google.maps.LatLng(pos[0],pos[1]);
var driverLatLng = lat_lng.split(',');
var driver_pos = new google.maps.LatLng(driverLatLng[0],driverLatLng[1]);
var myOptions = {
zoom: 18,
center: driver_pos,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
}
map = new google.maps.Map(document.getElementById(map_div), myOptions);
var marker = new google.maps.Marker({
position: job_pos,
map: map,
title: "Job"
});
var marker2 = new google.maps.Marker({
position: driver_pos,
map: map,
title: "X",
});
google.maps.event.trigger(map, 'resize');
}
HTML:
<div data-role="page" id="dialog-destination-map" data-theme="e">
<div data-role="content">
<div id="map_canvas" style="height:300px; width:300px; position: relative; margin: 0px auto;">
map_canvas
</div>
</div>
</div>
Any ideas?
EDIT: this question seems describing exactly the same problem: JQuery Mobile & Google Maps Glitch
But the solution provided (caching) can't be used here as the map might need to change
After trying everything else, I finally stumbled upon the pageshow event. Calling initializeMap after all the page transitions are done rather than when clicking the button solved the problem:
$('#dialog-destination-map').live('pageshow',function(event){
initializeMap(job_id,"map_canvas");
}
);
I still wonder how come it was working at the first load then...
I Agree with #peter .. You do not need to create map on each pageshow event.. Instead, try this:
$(document).on("pagebeforechange", function()
{
if(mapObj){
center = mapObj.getCenter();
}
});
$("#mapPage").bind("pageshow", function()
{
google.maps.event.trigger(mapObj, "resize");
if(center)mapObj.setCenter(center);
});
var driverLatLng is being initialized with lat_lng.split(','); which hasn't been declared before.
You don't need to create a new map each time you visit the page. Create the map beforehand, e.g. on pageinit. On pageshow: google.maps.event.trigger(mapObj, "resize");

Google Maps marker not showing

It's exactly the example code of the maps API documentation found here:
Google maps API documentation
I have set up an map and it is showing.
Next step was showing the marker with geocoding..
But it's not working? Can anyone help me out?
Thanks!!
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAS1COH5SeJCKhZ6i6nTi0Fx2qsdvWbAfA&sensor=false"></script>
<script type="text/javascript">
var loMap;
var loGeocoder;
$(document).ready(function()
{
var loOptions =
{
center: new google.maps.LatLng(51.9645, 5.1965),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
loMap = new google.maps.Map(document.getElementById('map'), loOptions);
loGeocoder = new google.maps.Geocoder();
showMarkers();
});
function showMarkers()
{
console.log('World');
loGeocoder.geocode( { 'address': 'Den Bosch'}, function (results, status)
{
if(status == google.maps.GeocoderStatus.OK)
{
console.log('Hello?');
loMap.setCenter(results[0].geometry.location);
console.log(results[0].geometry.location);
var marker = new google.maps.Marker(
{
map: loMap,
position: results[0].geometry.location
});
}
else
{
console.log('Error');
}
});
}
</script>
<div id="map" class="search_map" style="width: 220px; height: 240px"></div>
An old question but as I recently hit the problem I thought I would share my solution. I found that something in the Javascript on the rest of my site was interfering with Google Maps. I was not getting any errors in Firebug or Chrome Console so I could not track down exactly what the conflict was.
I found that if I put the Google Map onto a blank ASPX page (i.e. no MasterPage with all of the Javascript and CSS from the rest of my site) that it worked fine.
The solution? I put the Google Map into an Iframe and now it works just fine. If you inspect the source of the Google Map example code, they use an Iframe too so there must be something to that.
you need to change the line new google.maps.LatLng(51.9645, 5.1965) to
var place = new google.maps.LatLng(51.9645, 5.1965);
and then use place as center in loOptions .
same as in marker also it really works :)
And import jquery as well
at the start of page.