实现根据在线离线判断加载地图, 在线加载谷歌影响地图, 离线加载本地瓦片地图作者:Github:
html代码
tabindex="0"是为了启动键盘事件。
js代码
//地图中心点var center = ol.proj.transform([110.06667, 14.66667], 'EPSG:4326', 'EPSG:3857');//矢量图层源var vectorSource = new ol.source.Vector({ wrapX: false});//矢量图层var pointLayer = new ol.layer.Vector({ source: vectorSource});//地图视图var view;var rootLayer; //if (window.navigator.onLine == true) { console.log('online'); view = new ol.View({ center: center, zoom: 4, minZoom: 3, maxZoom: 15, }); rootLayer = new ol.layer.Tile({ source: new ol.source.TileImage({ url: 'http://mt2.google.cn/vt/lyrs=y&hl=zh-CN&gl=CN&src=app&x={x}&y={y}&z={z}&s=G' }) //加载谷歌影像地图 }); } else { console.log('offline'); view = new ol.View({ center: center, zoom: 4, minZoom: 3, maxZoom: 8, }); //地图图层 rootLayer = new ol.layer.Tile({ source: new ol.source.XYZ({ url: 'Map_new/{z}/{x}/{y}.png', //加载本地地图 wrapX: false }) });}// //创建地图var map = new ol.Map({ logo: false, //不显示openlayers的logo //添加图层 layers: [rootLayer, pointLayer], renderer: 'canvas', target: 'map', //添加视图 view: view});