Google Map not working with XHTML Doctype (Document Type)

半城伤御伤魂 提交于 2019-12-03 03:53:44

I had the same problem with Google Maps API v3 a while ago and I must say it wasn't easy to debug.

The thing here is that if you don't use DOCTYPE on your page, the page is rendered in quirks mode. Basically this allows to use styles without any additional CSS or JavaScript. In this case you could use this bit to load the map:

<body onload="initialize()">
  <div id="map_canvas" style="width:100%; height:100%"></div>
</body> 

However, with DOCTYPE the page is rendered like the DOCTYPE says so. Setting a style such as above wouldn't work without any additional CSS as it's using percentages. The element doesn't have a size, so you end up taking 100% of nothing. So if you are using XHTML 1.0 Strict, ie.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml/DTD/xhtml1-strict.dtd">

The page renders as it should if you use pixels instead of percentages:

<body onload="initialize()">
  <div id="map_canvas" style="width:500px; height:400px"></div>
</body> 

You could do that also in CSS.

So your options are here:

  1. Leave the DOCTYPE and use pixels instead of percentages OR specify the width and the height via CSS.

  2. Remove the DOCTYPE and use percentages. This is not recommended as the document should always say what DTD it should be rendered with.

You can find more info about Quirks mode from here. There's also a table which shows how different browsers react to the lack of DTD.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

I am using this doctype, and it seems to be working fine. It might just be your bootstrap. How are you loading Google? What errors are you getting? Display what kind of result you are getting?

Your question says "if we use 'Doctype' ". Does this mean you didn't before? If you didn't before, then, essentially, you are changing the 'rules' of how a web page will be laid out. Without a proper doctype, you are in quirks mode.

A quick solution could be to use it as follows:

document.getElementById("google-map").style.height = $(window).height()+'px';

before

var map = new google.maps.Map(document.getElementById("google-map"), myMapOptions);

It works pretty well with doctype. Tried and tested! :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!