根据坐标,一屏展示,自动缩放居中
<script
type="text/javascript"
src="http://webapi.amap.com/maps?v=1.4.6&key=自己的key&plugin=AMap.Autocomplete,AMap.PlaceSearch"
></script>
<script src="https://webapi.amap.com/ui/1.0/main.js"></script>
<template>
<div id="mapContainer" style="width: 100%; height: 400px;"></div>
</template>
<script>
export default {
props:{
coordinate:{
type:String,
default:''
}
},
mounted() {
const temp = JSON.parse(this.coordinate)
const amapCoordinates = temp.map(coord => new window.AMap.LngLat(coord[0], coord[1]));
const map = new window.AMap.Map('mapContainer', {
center: this.calculateCenter(amapCoordinates),
zoom: 12,
});
const polyline = new window.AMap.Polyline({
path: amapCoordinates,
strokeColor: '#3673F5',
strokeOpacity: 1,
strokeWeight: 3,
strokeStyle: 'solid',
});
polyline.setMap(map);
map.setFitView();
},
methods: {
calculateCenter(coords) {
let totalLat = 0;
let totalLng = 0;
coords.forEach(coord => {
totalLat += coord.getLat();
totalLng += coord.getLng();
});
const avgLat = totalLat / coords.length;
const avgLng = totalLng / coords.length;
return new window.AMap.LngLat(avgLng, avgLat);
},
},
};
</script>
<style lang='less'>
#mapContainer {
background-color: #ffffff;
width: 100%;
height: 100%;
}
</style>