Reputation: 319
I'm starting to learn the OpenStreetMap / OpenLayers API to put maps in my web app. While I've got to grips with the mapping itself, I've found that the div which contains the map won't stay where I put it. Here's my code so far:
<html>
<head>
<title>OpenStreetMap Test</title>
<script language="JavaScript" src="/resources/OpenLayers-2.13.1/OpenLayers.js"></script>
<script language="JavaScript" src="/resources/proj4js/lib/proj4js-combined.js"></script>
<script language="JavaScript" src="maptest.js"></script>
</head>
<body onload="init()">
<h2>OpenStreetMap Test</h2>
<div id="map" style="border: 1px solid black; margin-left: auto; margin-right: auto; margin-top: 10%; height: 300px; width:300px;"></div>
</body>
</html>
function init() {
Proj4js.defs["EPSG:27700"] = "+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs ";
var EPSG27700 = new OpenLayers.Projection("EPSG:27700");
var EPSG900913 = new OpenLayers.Projection("EPSG:900913");
var map = new OpenLayers.Map("map",{
controls: [
new OpenLayers.Control.Navigation(),
new OpenLayers.Control.PanZoomBar(),
new OpenLayers.Control.LayerSwitcher({'ascending':false}),
new OpenLayers.Control.ScaleLine(),
new OpenLayers.Control.KeyboardDefaults()
]});
var OSM = new OpenLayers.Layer.OSM("OpenStreetMap");
var OSMcycle = new OpenLayers.Layer.OSM("OSM Cycle", ['http://a.tile.thunderforest.com/cycle/${z}/${x}/${y}.png',
'http://b.tile.thunderforest.com/cycle/${z}/${x}/${y}.png',
'http://c.tile.thunderforest.com/cycle/${z}/${x}/${y}.png']);
map.addLayers([OSMcycle,OSM]);
var position = new OpenLayers.LonLat(321550,507250).transform(EPSG27700,EPSG900913);
var markers = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markers);
markers.addMarker(new OpenLayers.Marker(position));
var zoom = 13;
map.setCenter(position,zoom);
}
Without the onload="init()"
the div is in the centre of the page, horizontally, and a short way down from the top. However, with init()
called, the div snaps back to the left-hand side, just below the title. It still has the correct size and the border, so the CSS styling isn't being ignored completely, but I don't understand why it's not staying in position? I've tried putting the CSS into a stylesheet instead of inline, and the same thing happens.
Upvotes: 4
Views: 1991
Reputation: 49774
OpenLayers comes with a default stylesheet that contains the following CSS
div.olMap {
margin: 0 !important;
}
This is overriding your inline css margin-right: auto
, margin-left: auto
, and margin-top: 10%
.
You can fix this by applying your preferred styles to the #map
selector in an external style sheet (or internal).
#map {
margin-left: auto !important;
margin-right: auto !important;
margin-top: 10% !important;
}
This works because your reference to an ID'ed selector, #map
, has a higher priority than the class'ed selector, .olMap
.
Here's a jsfiddle of a working solution.
Upvotes: 3