第一个例子:简单的地图显示
直接上代码
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://openlayers.org/en/v4.1.0/css/ol.css" type="text/css">
<style>
.map {
height: 600px;//显示地图的高度
width: 100%;//显示地图的宽度
}
</style>
<script src="https://openlayers.org/en/v4.1.0/build/ol.js" type="text/javascript"></script>
<title>OpenLayers example</title>
</head>
<body>
<h2>My Map</h2>
<div id="map" class="map"></div>
<script type="text/javascript">
var map = new ol.Map({
target: 'map',
layers: [
new ol.layer.Tile({
source: new ol.source.OSM()
})
],
view: new ol.View({
//114:26E 38:03N
center: ol.proj.fromLonLat([114.45, 38.03]), //显示的地图中心(经纬度坐标)
zoom: 20 //缩放比例,默认为0-28,越大标识显示越详细的地图
})
});
</script>
</body>
</html>
第二个例子:加载静态图片的地图
<!DOCTYPE html>
<html>
<head>
<title>Static Image</title>
<link rel="stylesheet" href="https://openlayers.org/en/v4.1.0/css/ol.css" type="text/css">
<!-- The line below is only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://openlayers.org/en/v4.1.0/build/ol.js"></script>
</head>
<body>
<div id="map" class="map"></div>
<script>
// Map views always need a projection. Here we just want to map image
// coordinates directly to map coordinates, so we create a projection that uses
// the image extent in pixels.
var extent = [0, 0, 418, 600];
var projection = new ol.proj.Projection({
code: 'xkcd-image',
units: 'pixels',
extent: extent
});
var map = new ol.Map({
layers: [
new ol.layer.Image({
source: new ol.source.ImageStatic({
url: 'timg.jpg',//这里添加静态图片的地址
projection: projection,
imageExtent: extent
})
})
],
target: 'map',
view: new ol.View({
projection: projection,
center: ol.extent.getCenter(extent),
zoom: 2,
maxZoom: 8
})
});
</script>
</body>
</html>