<!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width"> <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" /> <style> html, body, #container { width: 100%; height: 100%; } #map-zoom, #map-center { color: #0288d1; } </style> <title>地图级别与中心点</title> </head> <body> <div id="container"></div> <div class="info"> <h4>获取地图级别与中心点坐标</h4> <p>当前级别:<span id="map-zoom">11</span></p> <p>当前中心点:<span id="map-center">121.498586,31.239637</span></p> </div> <script src="https://webapi.amap.com/maps?v=2.0&key=您申请的key值"></script> <script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script> <script> //初始化地图 var map = new AMap.Map('container', { zoom: 11, //初始地图级别 center: [121.498586, 31.239637], //初始地图中心点 }); //显示地图层级与中心点信息 function logMapinfo(){ var zoom = map.getZoom(); //获取当前地图级别 var center = map.getCenter(); //获取当前地图中心位置 document.querySelector("#map-zoom").innerText = zoom; document.querySelector("#map-center").innerText = center.toString(); }; //绑定地图移动与缩放事件 map.on('moveend', logMapinfo); map.on('zoomend', logMapinfo); </script> </body> </html> 转成vue2语法
时间: 2024-03-09 21:51:09 浏览: 181
可以将上述代码放在Vue组件的template和script标签中,如下所示:
```
<template>
<div>
<div id="container"></div>
<div class="info">
<h4>获取地图级别与中心点坐标</h4>
<p>当前级别:<span id="map-zoom">{{ zoom }}</span></p>
<p>当前中心点:<span id="map-center">{{ center }}</span></p>
</div>
</div>
</template>
<script>
import AMap from 'AMap';
import 'AMap/dist/AMap.css';
export default {
mounted() {
AMap.loadPlugin('AMap.Map', () => {
const map = new AMap.Map('container', {
zoom: 11,
center: [121.498586, 31.239637],
});
function logMapinfo() {
const zoom = map.getZoom();
const center = map.getCenter();
this.zoom = zoom;
this.center = center.toString();
}
this.zoom = map.getZoom();
this.center = map.getCenter().toString();
map.on('moveend', logMapinfo.bind(this));
map.on('zoomend', logMapinfo.bind(this));
});
},
data() {
return {
zoom: '',
center: '',
};
},
};
</script>
<style>
html, body, #container {
width: 100%;
height: 100%;
}
#map-zoom, #map-center {
color: #0288d1;
}
</style>
```
在Vue组件中,首先通过import引入AMap,然后在mounted()方法中使用AMap.loadPlugin()加载地图插件。然后在回调函数中创建地图实例,并将其显示在页面中。接着定义一个函数logMapinfo()来获取地图的层级和中心点位置,并将其绑定到地图的移动和缩放事件上。同时,在Vue组件中定义了两个数据zoom和center,用来保存当前地图的层级和中心点位置,并将它们显示在页面上。注意,在logMapinfo()函数中,由于this指向了地图实例,需要使用bind()方法将this绑定到Vue实例上,以便在函数中访问到Vue组件的数据。最后,通过style标签设置页面样式。
阅读全文