3

So I am trying to create a website that will show a location on Google maps. I want to set the map size as a % of the users screen size. This works fine for the width of the map, but when I try and set the height as a % the map vanishes. I tried setting the body to 100% width and 100% height, I tried using a container div, but I'm new to html and CSS, so I'm not sure what else I could try.

CSS for that is here;

#map {
    position: relative;
    width: 35%;
    height: 350px;
    background-color: #CCC;
    margin: 1% 0 0 15%;
    }

#map-container {
    height: 100%;
    width: 100%;
    }

The code I used for the map was taken straight from https://developers.google.com/maps/tutorials/fundamentals/adding-a-google-map, but if needed I can upload the full .html doc.

CDickson
  • 195
  • 2
  • 5
  • 15

4 Answers4

3

set the height and width for all the containing elements to:

width: 100%;
height: 100%;

Discussion in Mike Williams' Google Maps API v2 tutorial: Using a percentage height for the map div

proof of concept fiddle

code snippet:

function initialize() {
  var mapCanvas = document.getElementById('map');
  var mapOptions = {
    center: new google.maps.LatLng(44.5403, -78.5463),
    zoom: 8,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(mapCanvas, mapOptions)
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
  width: 100%;
  height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
geocodezip
  • 158,664
  • 13
  • 220
  • 245
2

Your map container needs a px height defined before you can use a % height on the child element.

Try:

#map-container{
    height: 350px;
}

#map{
    height: 100%;
}
luke
  • 21
  • 1
1

It´s not possible to set a percentage height of an HTML element, unless you have a parent element with a fixed height.

Though do modern browsers support height in percent relative to viewport by the keyword 'vh' instead of '%'.

Otherwise you have to calculate the height of the viewport and set the elements height it by Javascript / jQuery.

See more info here

Community
  • 1
  • 1
thbaan
  • 59
  • 4
0

if and only if you have the issue where map gets smaller in details and mobile device you must check the meta tag width device width initial scale one i post this because i copied developers all html and it did not include the meta tag and got much time to figure it out. otherwise all % and pixel sizing on the work perfectly.