vue2 高德地图需要实现查询指定地区行政轮廓,这里将实现代码记录下来。
html代码
配置key 和 密钥,这里的key和密钥是乱写的,改成自己的就可以了。
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<title>高德地图使用实例</title>
<script>
window._AMapSecurityConfig = {
securityJsCode: 'b50af813de4363ab7eb122ca0f11f8f4',
}
</script>
<script
type="text/javascript"
src="https://webapi.amap.com/maps?v=1.4.15&key=8799ea91cf020faef54754fca59a2511&plugin=AMap.Geocoder,AMap.RangingTool,AMap.Heatmap,AMap.DistrictSearch,AMap.service"
></script>
</head>
<body>
<noscript>
<strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
Please enable it to continue.</strong>
</noscript>
<div id="app"></div>
</body>
</html>
vue 代码
<template>
<div class="gdMap">
<div class="container" ref="mapContainer" id="container"></div>
</div>
</template>
<script>
export default {
data () {
return {
map: null,
locationName: ''
}
},
mounted () {
var that = this
const huidongCountyCoords = [104.251332, 38.50599]
this.iconWidth = this.width * this.scale
this.iconHeight = this.width * this.aspect * this.scale
this.map = new AMap.Map(this.$refs.mapContainer, {
zoom: 10,
center: huidongCountyCoords
})
var district = null
var polygon
function drawBounds () {
//加载行政区划插件
if (!district) {
//实例化DistrictSearch
var opts = {
subdistrict: 0, //获取边界不需要返回下级行政区
extensions: 'all', //返回行政区边界坐标组等具体信息
level: 'district' //查询行政级别为 市
}
district = new AMap.DistrictSearch(opts)
}
//行政区查询
district.setLevel('district')
//行政区代码或行政区名称
district.search('620122', function (status, result) {
if (polygon) {
map.remove(polygon)//清除上次结果
polygon = null
}
if (!result || !result.districtList || !result.districtList[0]) {
log.warn('请正确填写名称或更新其他名称')
return
}
var bounds = result.districtList[0].boundaries
if (bounds) {
//生成行政区划polygon
for (var i = 0; i < bounds.length; i += 1) {//构造MultiPolygon的path
bounds[i] = [bounds[i]]
}
polygon = new AMap.Polygon({
strokeWeight: 1,
path: bounds,
fillOpacity: 0.4,
fillColor: '#80d8ff',
strokeColor: '#0091ea'
})
that.map.add(polygon)
that.map.setFitView(polygon)//视口自适应
}
})
}
drawBounds()
},
beforeDestroy () {
if (this.map) {
this.map.destroy()
}
},
methods: {
}
}
</script>
<style lang="scss" scoped>
.gdMap {
position: fixed;
width: 100%;
height: 100%;
z-index: 0;
.container {
position: relative;
width: 100%;
height: 100%;
z-index: 10;
}
}
* {
cursor: default !important;
}
</style>