openlayers一:显示地图与鼠标地理坐标

openlayers两个好用的开源JS互动地图库之一,另一个是leaflet。

openlayers的特点是是大而全,自身包含绝大多数功能,文档好看。

leaflet是小而美,自身小,但支持扩展,好用扩展很多。

谷歌地图:

Google Maps​www.google.cn

从上面可以获取到谷歌地图瓦片图的连接为:

http://www.google.cn/maps/vt?lyrs=y@802&gl=cn&x={x}&y={y}&z={z}

那么要显示地图,只需:

 1 this.tileLayer = new ol.layer.Tile({
 2      source: new ol.source.XYZ({
 3          attributions: new ol.Attribution({
 4          html: '作者: 愤怒的小明'
 5          }),
 6          url: 'http://www.google.cn/maps/vt?lyrs=y@802&gl=cn&x={x}&y={y}&z={z}'
 7      })
 8 });
 9 this.map.addLayer(this.tileLayer);
10 //地图默认是莫卡托投影,从经纬度转成莫卡托座标
11 var center = ol.proj.fromLonLat([113.2569444444, 23.1336111111]);
12 //设置地图中心
13 var view = this.map.getView();
14 view.setCenter(center);

 

鼠标漂浮显示当前位置:

1 var mousePositionControl = new ol.control.MousePosition({
2     coordinateFormat: ol.coordinate.createStringXY(6),
3     projection: 'EPSG:4326',
4     className: 'custom-mouse-position',
5     target: document.getElementById('mouse-position'),
6     undefinedHTML: '&nbsp'
7 });
8 this.map.addControl(mousePositionControl);

 

最终效果:

 

整体代码:

链接:  密码: dfxz

posted on 2018-06-10 20:31  愤怒的小Ming  阅读(909)  评论(0编辑  收藏  举报

导航