移动端 Leaflet

提示:在Leaflet官方教程的基础上,增加了一些注释以及链接,可帮助读者更好的学习Leaflet,有不正确或有待改进的地方,欢迎批评指出。

Leaflet

an open-source JavaScript library for mobile-friendly interactive maps.

Leaflet On Mobile

本教程中,主要了解如何为iPhone、iPad或Android手机等移动设备创建全屏幕地图,以及如何轻松检测和使用当前用户位置。

设置页面

  • 地图撑满整个屏幕
body { 
    padding: 0;
    margin: 0; 
}
html, body, #map { 
    height: 100%; 
    width: 100vw;
}
  • 禁止页面不必要的缩放,在head部分加入以下代码

初始化地图

fitWorld()用于设置一个地图视图,该视图主要包含整个世界,尽可能使用最大缩放级别。

var map = L.map('map').fitWorld();
L.tileLayer('http://t1.tianditu.com/vec_c/wmts?layer=vec&style=default&tilematrixset=c&Service=WMTS&Request=GetTile&Version=1.0.0&Format=tiles&TileMatrix={z}&TileCol={x}&TileRow={y}&tk=天地图密钥', {
    maxZoom: 20,
    tileSize: 256,
    zoomOffset: 1
}).addTo(map );

地理点位

Leaflet有一个非常方便的快捷方式,可以用setView选项将地图视图缩放到被检测到的位置:

map.locate({setView: true, maxZoom: 16});

定位成功给地图添加一个事件监听:

function onLocationFound(e) { 
    var radius = e.accuracy;   
    L.marker(e.latlng).addTo(map).bindPopup("You are within" + radius + "meters from this point").openPopup();
    L.circle(e.latlng, radius).addTo(map); 
} 
map.on('locationfound', onLocationFound);

定位失败反馈:

function onLocationError(e) { 
    alert(e.message); 
}
map.on('locationerror', onLocationError);

注:在同一个局域网下,可以在移动端进行测试!
移动端 Leaflet_第1张图片

你可能感兴趣的:(leaflet,javascript)