直接上代码
<!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"><title>逆地理编码(经纬度->地址)</title><meta name="viewport"content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no,viewport-fit=cover"><script src="js/jquery-3.6.3.js"></script><link rel="stylesheet" href="css/xinxigai.css"><script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=2ba918f5c295c0b85be0322ccf084de6"></script><style>/* 地图 */.map {margin-top: 5%;width: 100%;height: 30vh;}#container {width: 100%;height: 30vh;}/* 信息显示框 */#coordinate{/width: 39%;height: 50px;}</style>
</head>
<body><!-- 地址 --><div class="contacte"><p>地址:</p><div class="work"><input type="text" id="contacte" onkeyup="this.value=this.value.replace(/[^\u4e00-\u9fa5]/g,'')" placeholder="请输入内容" value=""></div></div><div class="map" style="position: relative;"><div id="container"></div></div><script>// 地图let position = '';let leng = '35.302616';let lang = '113.883991';//初始化地图时,若center属性缺省,地图默认定位到用户所在城市的中心,function ad() {var map = new AMap.Map('container', {resizeEnable: true, //是否监控地图容器尺寸变化zoom: 14, //初始化地图层级center: [lang, leng] //初始化地图中心点});}ad();// 初始化地图let map = new AMap.Map('container', {resizeEnable: true,zoom: 14,center: [lang, leng]});// // 点击地图事件map.on('click', function(e) {console.log(666);let position = e.lnglat; // 获取点击位置的经纬度坐标console.log(position.lng, position.lat); // 显示经纬度坐标// 这里你可以将经纬度坐标显示在页面上的指定位置,比如一个div容器中document.getElementById('contacte').innerHTML = '经度:' + position.lng + ', 纬度:' + position.lat;});var backgroundColor = $('.toggle-switch-handle').css('background-color');console.log(backgroundColor);// 切换事件获取状态let asd = [];let asf = [];leng = '35.281454'lang = '113.978255'asd = ['35.281454']asf = ['113.978255']sessionStorage.setItem('zuo', asd)sessionStorage.setItem('biao', asf)ad()map = new AMap.Map('container', {resizeEnable: true,zoom: 14,center: [lang, leng]});// 调用高德地图的逆地理编码服务AMap.service('AMap.Geocoder', function() {var geocoder = new AMap.Geocoder({// 结果返回参数city: "0371", // 城市,可选,默认是全国radius: 1000 // 范围,默认是500});// 将获取到的经纬度坐标作为参数传递给逆地理编码服务$.ajax({// dataType: 'json', //服务器返回json格式数据type: 'GET', //HTTP请求类型timeout: 10000, //超时时间设置为10秒;url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',data:{key:'e67e44d2b82a84aabe5cb87b7235188a',// location:position.lng+','+position.lat// '113.978441 + ',' + 35.28117',location:'113.978441,35.28117'},success: function(res) {let str=res.regeocode.formatted_address;//省市区//res.regeocode.addressComponent.district;单独到区console.log(res);$('#contacte').val(str)laction=str;console.log(laction);},error: function(res) {}});});</script>
</body>
</html>
这是效果图跟自身定位获取城市
提示这里调用了逆地理编码一定要先因这个链接 <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=你申请的key值">
</script>