1、效果展示:
2、代码走一波:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>地址解析</title>
<style type="text/css">
* {
margin: 0px;
padding: 0px;
}
body,
button,
input,
select,
textarea {
font: 12px/16px Verdana, Helvetica, Arial, sans-serif;
}
p {
width: 603px;
padding-top: 3px;
margin-top: 10px;
overflow: hidden;
}
input#address {
width: 300px;
}
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
charset="utf-8"
src="http://map.qq.com/api/js?v=2.exp&key=UFYBZ-VRVL6-HAYSH-ECD2G-LNN56-IIFGY"
></script>
</head>
<body onload="init()">
<script>
var appkey = "UFYBZ-VRVL6-HAYSH-ECD2G-LNN56-IIFGY";
var geocoder = null;
var lat = 22.55329;
var lng = 113.88308;
var init = function () {
geocoder = new qq.maps.Geocoder();
mapInit();
};
function codeAddress() {
var address = document.getElementById("address").value;
//对指定地址进行解析
geocoder.getLocation(address);
//设置服务请求成功的回调函数
geocoder.setComplete(function (result) {
// alert(result.detail.location);
lat = result.detail.location.lat;
lng = result.detail.location.lng;
console.log(result.detail);
mapInit();
});
//若服务请求失败,则运行以下函数
geocoder.setError(function () {
alert("出错了,请输入正确的地址!!!");
});
}
function mapInit() {
var map = new qq.maps.Map(document.getElementById("container"), {
center: new qq.maps.LatLng(lat, lng),
zoom: 12,
});
//添加监听事件 获取鼠标单击事件
qq.maps.event.addListener(map, "click", function (event) {
var marker = new qq.maps.Marker({
position: event.latLng,
map: map,
});
$("#poi_lat").html(event.latLng.getLat().toFixed(6));
$("#poi_lng").html(event.latLng.getLng().toFixed(6));
jiexiaddress(
event.latLng.getLat().toFixed(6),
event.latLng.getLng().toFixed(6)
);
qq.maps.event.addListener(map, "click", function (event) {
marker.setMap(null);
});
});
}
//解析地址
function jiexiaddress(lat, lng) {
var url3 = encodeURI(
"https://apis.map.qq.com/ws/geocoder/v1/?location=" +
lat +
"," +
lng +
"&key=" +
appkey +
"&output=jsonp&&callback=?"
);
$.getJSON(url3, function (result) {
if (result.result != undefined) {
$("#poi_address").html(result.result.address);
} else {
$("#poi_address").html("");
}
});
}
</script>
<div style="padding: 20px">
<input id="address" type="textbox" value="广东省深圳市" />
<button onclick="codeAddress()">search</button>
</div>
<div style="padding: 20px">
您点击的位置(经度:<span id="poi_lat"></span>,纬度:<span id="poi_lng"></span
>,解析出来的地址:<span id="poi_address"></span>)
</div>
<div id="container" style="width: 800px; height: 800px; margin: 0 auto"></div>
</body>
</html>