java div中放置map,将mapbox / leaflet地图放置在容器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:

L.mapbox.accessToken = 'pk.eyJ1IjoiYWxvb2thdG9tbW9yb3ciLCJhIjoiNGM4ODhkZjUwMGM1ZDE4M2VjNzQ4MmQ4ODcxMjk5ZjMifQ.XVvFc8kl-0z4NAblE-mNqw';

var map = L.mapbox.map('map', 'mapbox.streets').setView([40, -74.50], 10);

And the following CSS:

#map {

position: absolute;

top: 0;

bottom: 0;

height: 50%;

width: 50%;

}

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.

解决方案

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;

}

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

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值