OpenStreetMap会覆盖map div位置

时间:2014-04-24 19:39:02

标签: css openlayers openstreetmap

我开始学习OpenStreetMap / OpenLayers API,将地图放入我的网络应用程序中。虽然我必须掌握映射本身,但我发现包含地图的div不会停留在我放置的位置。到目前为止,这是我的代码:

maptest.htm

<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>

maptest.js

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);
}

如果没有onload="init()",则div位于页面的中心,水平,并且从顶部向下一小段。但是,在调用init()时,div会快速回到标题下方的左侧。它仍然具有正确的大小和边框,因此CSS样式不会被完全忽略,但我不明白它为什么不能保持原位?我已经尝试将CS​​S放入样式表而不是内联,同样的事情发生了。

1 个答案:

答案 0 :(得分:3)

OpenLayers附带一个包含以下CSS的默认样式表

div.olMap {
    margin: 0 !important;
}

这会覆盖您的内联css margin-right: automargin-left: automargin-top: 10%

您可以通过将首选样式应用于外部样式表(或内部)中的#map选择器来解决此问题。

#map {
    margin-left: auto !important;
    margin-right: auto !important;
    margin-top: 10% !important;
}

这样做是因为您对ID&#39选择器#map的引用优先级高于类选择器.olMap

Here's a jsfiddle of a working solution