前端js高德地图,拖拽选址+搜索地址+自动定位,可以嵌套小程序webview不被拦截

高德地图实现拖拽选址、搜索、定位,可以嵌套小程序webview不被拦截

请不要忘记换成你的高德Key钥匙

写这篇文章的时候我也很纠结,因为有一些参数我也不太明白,但是呢因为陪同事加班无聊,所以就写了。先看一下效果:

在这里插入图片描述
在这里插入图片描述

简述一下这几个模块吧;

1、初始化地图大家都知道,所以我…还是给写上去

 const map = new AMap.Map('container', {
        zoom: 17,
        resizeEnable: true,
        rotateEnable: true,
        pitchEnable: true,
        pitch: 80,
        rotation: -15,
        viewMode: '3D',//开启3D视图,默认为关闭
        buildingAnimation: true,//楼块出现是否带动画
        enableHighAccuracy: true,//是否使用高精度定位,默认:true
        expandZoomRange: true,
        zooms: [3, 20],
    });

2、地图初始化完成进行定位

AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation();
        geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
                    map.setCenter([result.position.lng, result.position.lat]);//传入经纬度移动地图的方法
            } else {
                console.log('失败原因排查信息:' + result.message);
            }
        });
    });

3、拖拽地图配置

//这里使用了高德的loadUI
AMapUI.loadUI(['misc/PositionPicker'], function (PositionPicker) {

        var positionPicker = new PositionPicker({
            mode: 'dragMap',//dragMap:拖拽地图,dragMarker:拖拽点
            map: map
        });

        positionPicker.on('success', function (positionResult) {
            //拖拽成功的回调 positionResult里有你想要的东西
        });
        positionPicker.start();
    });

4、搜索配置

AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {

        const poiPicker = new PoiPicker({
            input: 'search'//DOM  ID
        });

        //初始化poiPicker  点击搜索结果列表的回调
        poiPicker.on('poiPicked', function (poiResult) {
            map.setCenter([item.location.lng, item.location.lat]);
        });
    });

5、根据经纬度获取省市区名称,从而获取你的省市区ID

geocoder.getAddress([mapInfo.longitude, mapInfo.latitude], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
                if (result && result.regeocode) {
                //你想要的result这里还有
                }
            } else {
                alert('获取省市区失败,请重新选择地址');
            }
        });

好了不详细说了,我下班了!以下所有代码:

<!doctype html>
<html lang="zh-CN">

<head>
    <!--    <base href="//webapi.amap.com/ui/1.1/ui/misc/PositionPicker/examples/"/>-->
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>选择选址</title>
    <style>
        html,
        body {
            height: 100%;
            margin: 0;
            width: 100%;
            padding: 0;
            overflow: hidden;
            font-size: 13px;
        }

        .map {
            height: 100%;
            width: 100%;
            float: left;
        }

        #right {
            display: none;
        }

        #footer {
            position: fixed;
            bottom: 0;
            left: 0;
            width: 100%;
            background: #fff;
            border-top: 1px solid #cccccc;
            z-index: 9999;
            padding: 10px 20px;
            box-sizing: border-box;
        }

        .addressBox {
            width: 100%;
            padding-left: 40px;
            box-sizing: border-box;
            position: relative;
            font-size: 16px;
            margin: 10px 0 15px;
        }

        .addressBox i {
            width: 24px;
            height: 28px;
            background: url("https://weixin.dzrlkj.com/image/location.png") no-repeat;
            background-size: 24px 28px;
            display: block;
            position: absolute;
            top: 50%;
            margin-top: -14px;
            left: 0;
        }

        .btnOk {
            line-height: 44px;
            text-align: center;
            background: #0091ff;
            font-size: 18px;
            color: #fff;
            border-radius: 5px;
        }

        .searchBox {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            z-index: 9999;
            height: auto;
            padding: 10px 20px;
            box-sizing: border-box;
            background: rgba(255, 255, 255, 0);
        }

        #search {
            width: 100%;
            height: 38px;
            border-radius: 20px;
            border: 1px solid #ccc;
            outline: none;
            background: rgba(255, 255, 255, .5);
            padding-left: 10px;
            box-sizing: border-box;
        }
    </style>
</head>

<body>
<div class="searchBox">
    <input type="text" id="search" placeholder="输入关键字选取地点" autocomplete="off">
</div>
<div id="container" class="map" tabindex="0"></div>
<div id="footer">
    <div class="addressBox">
        <i></i>
        <span id="address"></span>
    </div>
    <div class="btnOk" onclick="searchLocationId()">确定</div>
</div>

<script type="text/javascript"
        src='//webapi.amap.com/maps?v=2.0&key=你申请的Key钥匙&plugin=AMap.ToolBar'></script>
<!-- UI组件库 1.0 -->
<script src="//webapi.amap.com/ui/1.1/main.js?v=1.1.1"></script>


<script type="text/javascript">
    var center = '';
    const map = new AMap.Map('container', {
        zoom: 17,
        resizeEnable: true,
        rotateEnable: true,
        pitchEnable: true,
        pitch: 80,
        rotation: -15,
        viewMode: '3D',//开启3D视图,默认为关闭
        buildingAnimation: true,//楼块出现是否带动画
        enableHighAccuracy: true,//是否使用高精度定位,默认:true
        expandZoomRange: true,
        zooms: [3, 20],
    });
    var mapInfo = {
        latitude: 0,
        longitude: 0,
        address: ''
    };

    function searchLocationId() {
        const geocoder = new AMap.Geocoder({
            radius: 1000,
            extensions: "all"
        });
        console.log([mapInfo.longitude, mapInfo.latitude]);
        geocoder.getAddress([mapInfo.longitude, mapInfo.latitude], function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
                if (result && result.regeocode) {
                    // 具体地址
                    mapInfo.address = result.regeocode.formattedAddress;
                    // 省
                    mapInfo.province = result.regeocode.addressComponent.province;
                    // 市
                    mapInfo.city = result.regeocode.addressComponent.city;
                    if (mapInfo.city == '') mapInfo.city = mapInfo.province;
                    // 区
                    mapInfo.district = result.regeocode.addressComponent.district;
                    openAddress();
                }
            } else {
                alert('获取省市区失败,请重新选择地址');
            }
        });
    }


    function openAddress() {
        // cityData 你的省市区地址库为了获取省市区id
        var province = mapInfo.province;
        var city = mapInfo.city;
        var district = mapInfo.district;
        for (var i = 0; i < cityData.length; i++) {
            if (province.indexOf(cityData[i].text) >= 0 && cityData[i].children) {
                for (var j = 0; j < cityData[i].children.length; j++) {
                    if (city.indexOf(cityData[i].children[j].text) >= 0 && cityData[i].children[j].children) {
                        for (var k = 0; k < cityData[i].children[j].children.length; k++) {
                            if (cityData[i].children[j].children[k].text == district) {
                                mapInfo.provinceId = cityData[i].value;
                                mapInfo.cityId = cityData[i].children[j].value;
                                mapInfo.districtId = cityData[i].children[j].children[k].value;
                            }
                        }
                    }
                }
            }
        }
        console.log(mapInfo);
    }


    // getQueryString  获取地址栏的参数,这方法自行解决,或者留言
    // if (getQueryString('center')) {
    //     center = getQueryString('center').split(',').map(t => +t);
    // }
    //地图开始
    AMap.plugin('AMap.Geolocation', function () {
        var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,默认:true
            timeout: 10000,          //超过10秒后停止定位,默认:无穷大
            convert: true,           //自动偏移坐标,偏移后的坐标为高德坐标,默认:true
            showButton: true,        //显示定位按钮,默认:true
            showMarker: false,        //定位成功后在定位到的位置显示点标记,默认:true
            showCircle: false,        //定位成功后用圆圈表示定位精度范围,默认:true
            panToLocation: true,     //定位成功后将定位到的位置作为地图中心点,默认:true
            offset: [15, 150],//定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, 20)
            position: 'LB',    //定位按钮停靠位置,默认:'LB',左下角
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition(function (status, result) {
            if (status == 'complete') {
                console.log(result);
                mapInfo.longitude = result.position.lng;
                mapInfo.latitude = result.position.lat;
                mapInfo.address = result.formattedAddress;
                // console.log(center); // center [ll9.2323,39.89797]传入回显定位
                if (center != '') {
                    map.setCenter(center)
                } else {
                    map.setCenter([result.position.lng, result.position.lat]);
                }
                $('#address').html(result.formattedAddress);
            } else {
                if (center != '') {
                    map.setCenter(center)
                }
                console.log('失败原因排查信息:' + result.message);
            }
        });
    });
    AMapUI.loadUI(['misc/PositionPicker'], function (PositionPicker) {

        var positionPicker = new PositionPicker({
            mode: 'dragMap',//dragMap:拖拽地图,dragMarker:拖拽点
            map: map
        });

        positionPicker.on('success', function (positionResult) {
            console.log(positionResult);
            mapInfo = {
                latitude: positionResult.position.lat,
                longitude: positionResult.position.lng,
                address: positionResult.regeocode.formattedAddress
            };
            document.getElementById('address').innerHTML = positionResult.address;
        });
        positionPicker.on('fail', function (positionResult) {
            document.getElementById('address').innerHTML = ' ';
        });
        positionPicker.start();
    });
    AMapUI.loadUI(['misc/PoiPicker'], function (PoiPicker) {

        const poiPicker = new PoiPicker({
            input: 'search'
        });

        //初始化poiPicker
        poiPicker.on('poiPicked', function (poiResult) {
            console.log(poiResult);
            const item = poiResult.item;
            mapInfo = {
                latitude: item.location.lat,
                longitude: item.location.lng,
                address: item.district + ' ' + item.name + ' ' + item.address
            };
            map.setCenter([item.location.lng, item.location.lat]);
            $('#search').val('');
        });
    });
</script>
</body>

</html>

有问题请留言

  • 11
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值