将mapbox/leaflet映射放置在容器div中 [英] positioning a mapbox/leaflet map inside a container div

查看:401
本文介绍了将mapbox/leaflet映射放置在容器div中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Ruby on Rails应用程序中使用Mapbox.为了我的一生,我无法使地图遵循任何简单的CSS.允许地图出现的唯一CSS是为其提供一个绝对位置,其顶部和底部均为0.更改高度和宽度以外的任何值都会使地图消失.我想将地图居中放在容器div中.这是代码:

I am working with Mapbox in a Ruby on Rails app. For the life of me, I cannot get the map to adhere to any simple CSS. The only CSS that allows the map to appear is giving it an absolute position with a top and bottom of 0. Altering anything other than the height and width causes the map to disappear. I want to have the map centered inside a container div. Here is the code:

<div id="map-container">
  <div id='map'>
  </div>
</div>

<script>

L.mapbox.accessToken = 'pk.eyJ1IjoiYWxvb2thdG9tbW9yb3ciLCJhIjoiNGM4ODhkZjUwMGM1ZDE4M2VjNzQ4MmQ4ODcxMjk5ZjMifQ.XVvFc8kl-0z4NAblE-mNqw';
var map = L.mapbox.map('map', 'mapbox.streets').setView([40, -74.50], 10);

</script>

以及以下CSS:

#map {
  position: absolute;
  top: 0;
  bottom: 0;
  height: 50%;
  width: 50%;
}

如果我更改了任何内容,地图就会消失.我试图给map-container div一个相对的位置.那行不通.我只想将地图包含在div中,这似乎并不困难. 2013年有一篇关于此的文章,但已过时.感谢您的帮助.

If I change anything, the map disappears. I have tried to give the map-container div a position of relative. That does not work. All I want is for the map to be contained within a div, it doesn't seem like it should be difficult. There is one post about this from 2013 but it is outdated. Thanks for your help.

推荐答案

必须为Leaflet的 设置唯一的CSS规则(Mapbox是传单)元素:

The only css rule that must be set for Leaflet's (Mapbox is an extended version of Leaflet) element when positioned static/relative is an absolute height:

#map {
    height: 200px;
}

示例: http://plnkr.co/edit/vdeyLv?p=preview

这将始终有效,与元素嵌套的深度无关.如果未设置宽度,它将使用所有可用宽度.当您要切换为以百分比设置高度时,您需要确保map元素的所有anchestor元素也都设置了高度:

That will work always, doesn't matter how deep the element is nested. When width is not set it will use all the width available. When you want to switch to setting height in percentages, you'll need to make sure that all the anchestor elements of the map element have a height set also:

#html, #body, #map-container {
    height: 100%;
}

#map {
    height: 40%;
}

示例: http://plnkr.co/edit/rAuNC0?p=preview

我猜想在Mapbox示例中使用绝对定位的背后原因是不必解释以上内容,因为无论您嵌套地图元素的深度如何,它都可以正常工作.

I guess the reasoning behind using absolute positioning in the Mapbox examples is that one does not have to explain the above because no matter how deep you nest the map's element, it just works.

这篇关于将mapbox/leaflet映射放置在容器div中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆