一、申请key
参考高德地图API(https://lbs.amap.com/api/javascript-api/guide/abc/prepare)
1、首先需要注册开发者账号,成为高德开放平台开发者;
2、 登陆之后,在进入「应用管理」 页面「创建新应用」;
3、 为应用添加 Key,「服务平台」一项请选择「 Web 端 ( JSAPI ) 」
二、开发准备
1、在页面添加 JS API 的入口脚本标签,并将其中「您申请的key值」替换为您刚刚申请的 key;
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=您申请的key值"></script>
2、添加div标签作为地图容器,同时为该div指定id属性;
<div id="container"></div>
3、为地图容器指定高度、宽度;
#container {width:300px; height: 180px; }
4、进行移动端开发时,请在head内添加viewport设置,以达到最佳的绘制性能;
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
三、业务代码
需求:实现选择省市区后,在地图上根据区级圈出指定区域,并可在区域内选择任意位置,拿到经纬度和详细地址。
参考高德地图API(https://lbs.amap.com/api/javascript-api/guide/services/district-search)
用的是vue框架,写了一个测试html,直接附代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>获取经纬度</title>
</head>
<body>
<div id="app">
<div id="container" style="width:1000px; height:800px"></div>
</div>
</body>
</html>
<script src="vue.js"></script>
<script type="text/javascript"
src="https://webapi.amap.com/maps?v=1.4.1&&key=040a7c6537e9acae3221a78dbfd23557&plugin=AMap.MarkerClusterer,AMap.Geocoder,AMap.DistrictSearch,AMap.Polygon,AMap.CitySearch,AMap.Geolocation,AMap.Autocomplete,AMap.ToolBar,AMap.PlaceSearch"></script>
<script>
var app = new Vue({
el: '#app',
data: {
dataForm: {}
},
mounted() {
this.requireLoaction()
this.marker()
},
methods: {
requireLoaction() {
let map = new AMap.Map("container", {
resizeEnable: true,
zoom: 10,
center: ""
});
map.setZoom(15);
map.plugin(['AMap.Scale'], function () {
var scale = new AMap.Scale({});
map.addControl(scale);
});
map.plugin('AMap.Geolocation', function () {
var geolocation = new AMap.Geolocation({
enableHighAccuracy: true,// 是否使用高精度定位,默认:true
convert: true,
showMarker: true,
panToLocation: true,
timeout: 10000
});
geolocation.getCurrentPosition();
map.addControl(geolocation);
AMap.event.addListener(geolocation, 'complete', onComplete)
AMap.event.addListener(geolocation, 'error', onError)
function onComplete(data) {
// data是具体的定位信息
// window.alert(data.formattedAddress);
console.log(data.addressComponent)
}
function onError(data) {
// 定位出错
window.alert("定位出错!");
console.log(data)
}
})
},
marker() {
let _self = this;
var map,
marker,
lnglat,
adcode,
address,
districtaddres,
districtvalue,
level;
// 地理编码转换
var geocoder = new AMap.Geocoder({
city: '全国', // 城市默认:“全国”
radius: 1000 // 范围,默认:500
});
let addressAll = '陕西省宝鸡市凤翔县' //将选中的省市区地址赋给addressAll
geocoder.getLocation(addressAll, function (status, result) {
if (status === "complete" && result.geocodes.length) {
adcode = result.geocodes[0].adcode;
lnglat = result.geocodes[0].location;
level = result.geocodes[0].addressComponent.level;
districtvalue = result.geocodes[0].addressComponent.district;
map = new AMap.Map("container", {
resizeEnable: true,
center: lnglat,
zoom: 13
});
// 加载行政区划插件
var district = null;
var polygons = [];
if (!district) {
// 实例化DistrictSearch
var opts = {
subdistrict: 0, // 获取边界不需要返回下级行政区
extensions: "all", // 返回行政区边界坐标组等具体信息
level: level // 查询行政级别为 市
};
district = new AMap.DistrictSearch(opts);
}
// 行政区划线
if (adcode == '370282') {
adcode = '370215' //这里的重新赋值是因为青岛市即墨区的区域编码修改
}
district.search(adcode, function (status, result) {
//这里是根据区域编码来圈区域的,还可以根据行政区名称(将adcode换成'凤翔县')、citycode
map.remove(polygons); // 清除上次结果
polygons = [];
var bounds = [];
bounds = result.districtList[0].boundaries;
if (bounds) {
for (var i = 0, l = bounds.length; i < l; i++) {
// 生成行政区划polygon
var polygon = new AMap.Polygon({
strokeWeight: 1,
path: bounds[i],
fillOpacity: 0.4,
fillColor: "#80d8ff",
strokeColor: "#0091ea"
});
polygons.push(polygon);
}
}
map.add(polygons);
map.setFitView(polygons); // 视口自适应
});
// 标记中心点
if (!marker) {
marker = new AMap.Marker({
position: map.getCenter(),
icon:
"//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
offset: new AMap.Pixel(-13, -30),
// 设置是否可以拖拽
draggable: true,
cursor: "move",
// 设置拖拽效果
raiseOnDrag: true
});
marker.setPosition(map.getCenter());
map.setFitView(marker);
map.add(marker);
geocoder.getAddress(map.getCenter(), function (status, result) {
if (status === "complete" && result.regeocode) {
address = result.regeocode;
console.log(address.addressComponent.adcode, adcode)
if (address.addressComponent.adcode === adcode) {
_self.dataForm.merAddressLongitude = lnglat.lng;
_self.dataForm.merAddressLatitude = lnglat.lat;
// 地址赋值只给详细地址
_self.dataForm.merAddress =
address.addressComponent.township +
address.addressComponent.street +
address.addressComponent.streetNumber;
// _self.dataForm.sp_address = address.formattedAddress;
} else {
//alert("超出所在区域请重新选择")
// 当超出区域回到原点
marker.setPosition(map.getCenter());
}
} else {
alert(JSON.stringify(result));
}
});
marker.on("dragend", function (e) {
console.log(e)
let lngstring = marker.getPosition(map).lng;
let latstring = marker.getPosition(map).lat;
let lnglatsmall = lngstring + "," + latstring;
console.log(lngstring, latstring)
geocoder.getAddress(lnglatsmall, function (status, result) {
if (status === "complete" && result.regeocode) {
address = result.regeocode;
console.log(address.addressComponent.adcode, adcode)
if (address.addressComponent.adcode === adcode) {
_self.dataForm.merAddressLongitude = lngstring;
_self.dataForm.merAddressLatitude = latstring;
_self.dataForm.merAddress =
address.addressComponent.township +
address.addressComponent.street +
address.addressComponent.streetNumber;
} else {
//alert("超出所在区域请重新选择");
// 当超出区域回到原点
marker.setPosition(map.getCenter());
}
} else {
alert(JSON.stringify(result));
}
});
});
} else {
alert(JSON.stringify(result));
}
}
});
}
}
});
</script>
四、效果图
气球可以在区域内进行拖拽来改变详细地址和经纬度