高德地图开发-常用api踩坑使用

一、高德地图的加载初始化

在这就踩过很多坑,新建项目正常显示没问题,放到我们的项目就是不显示,加载不出来,
这个时候不要慌,只要确保下面三部完成就莫问题了

1.引入高德地图开发者api

<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=4611f58483d79aa58bf6d2b508078f9c&plugin=AMap.Autocomplete,AMap.PlaceSearch"></script>

生成key的方式自行百度,一大堆,下面是我的
高德地图开发-常用api踩坑使用
我开发的时候在这就踩坑了,因为新接触的项目,不是很了解,系统前端是页面套页面的方式,所以我应该在公共页面main_null.html中引入api,而不是当前html
2.页面上给一个放地图的容器

<!--高德地图容器-->
            <div style="width: 500px; height: 400px;" id="dituContent"></div>

3.js里创建地图、初始化,放到页面地图容器中

map = new AMap.Map('dituContent',{
                resizeEnabel: false,//是否监控地图容器尺寸变化
                zoom: 10,//初始化地图层级
                center: [116.397428, 39.90923]//设置地图中心点
            });

创建地图语句固定,第一个参数为地图容器的id,第二个参数是初始化地图的属性,
这样地图就可以加载出来啦:
高德地图开发-常用api踩坑使用

二、给地图添加标注

地图上的这个小蓝点是怎么来的呢,

//1.定义标注的图标
var markerContentBlue = '' +
        '<div>' +
        '   <img  style ="width:25px;height:34px;" src="/common/main/images/mapblue.png">' +
        '</div>';
  //2.创建标注
marker1[0] = new AMap.Marker({
         position:new AMap.LngLat(116.39, 39.9),//标注显示的位置
         content: markerContentBlue,//上面定义的图标
         offset: new AMap.Pixel(-13, -14)//移动距离:绝对坐标、相对坐标
     });
     //3.将标注添加到地图上
     map.add(marker1[0]);

三、地图点击事件

我们开发当然是要实现点击地图,获取点击位置的经纬度,详细地址信息进行保存、业务处理
注释已经写很清楚啦

map.on('click', function (e) {
            //1.清楚地图标注
            map.remove(marker1[0]);
            //2.经纬度赋值
            $("#lng").val(e.lnglat.getLng());
            $("#lat").val(e.lnglat.getLat());
            //3.根据经纬度反向地理编码获取地图定位赋值
            var geocoder;
            var lnglatXY = new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat());
            //加载地理编码插件
            map.plugin(["AMap.Geocoder"], function () {
                geocoder = new AMap.Geocoder({
                    radius: 1000, //以已知坐标为中心点,radius为半径,返回范围内兴趣点和道路信息
                    extensions: "all"//返回地址描述以及附近兴趣点和道路信息,默认"base"
                });
                //返回地理编码结果
                AMap.event.addListener(geocoder, "complete", function (e) {
                    console.log(e.regeocode);
                    $("#suggestId").val(e.regeocode.formattedAddress);
                });
                //逆地理编码
                geocoder.getAddress(lnglatXY);
            });
            //4.添加标注
            marker1[0] = new AMap.Marker({
                position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
                offset: new AMap.Pixel(-13, -14),
                content: markerContentBlue,
                title: '北京'
            });
            map.add(marker1[0]);
        })

四、通过输入框去定位地图

当然还有很重要的一个功能就是 智能搜索,我们在输入框里输入位置,地图自动定位到当前范围

//根据输入框标注地图
    var auto = new AMap.Autocomplete({
        input:"suggestId",
        city:""
    });
    var placeSearch = new AMap.PlaceSearch({
        city: '',
    });
    //构造地点查询类
    AMap.event.addListener(auto, "select", select);//注册监听,当选中某条记录时会触发
    function select(e) {
        console.log(e.poi)
        map.remove(marker1[0]);
        placeSearch.search(e.poi.name);  //关键字查询查询
        map.setZoomAndCenter(15, [e.poi.location.lng, e.poi.location.lat]); //同时设置地图层级与中心点
    }

贴出全部代码:

<!doctype html>
<html>
<head>
    <title>关键字查询自我展示</title>
    <script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=4611f58483d79aa58bf6d2b508078f9c&plugin=AMap.Autocomplete,AMap.PlaceSearch"></script>
    <script type="text/javascript" src="https://cache.amap.com/lbs/static/PlaceSearchRender.js"></script>
    <script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
    <style>
        input{
            width:20px;
            height:30px;
            border-radius:18px;
            border:2px solid gray;
        }
    </style>
</head>
<body>
<div style = "  width:1000px;height:1000px;">
    <div>
        <div style="width: 500px; height: 400px;">
            <div id="r-result">
                <i></i>
                <input style="width: 500px; height: 30px;" id="suggestId" name="orientationAddress" type="text"   placeholder="请输入地图定位">
            </div>
            <div style="margin-top:2px;">
                <input  id="lng" name="longitude" type="text"  style="width: 150px;" placeholder="请输入经度">
                <input id="lat" name="latitude" type="text"  style="width: 150px;" placeholder="请输入纬度">
            </div>
            <div id="searchResultPanel" style="border: 1px solid #C0C0C0; width: 150px; height: auto; display: none;"></div>
            </br>
            <!--高德地图容器-->
            <div style="width: 500px; height: 400px;" id="dituContent"></div>
        </div>
    </div>
</div>
<script type="text/javascript">
    var lng;//经度
    var lat;//维度
    var marker1 = [];
    var map;
    var markerContentBlue = '' +
        '<div>' +
        '   <img  style ="width:25px;height:34px;" src="/common/main/images/mapblue.png">' +
        '</div>';
    $(document).ready(function(){
        if(lng == null || lat == null){
            map = new AMap.Map('dituContent',{
                resizeEnabel: false,
                zoom: 10,
                center: [116.397428, 39.90923]
            });
            marker1[0] = new AMap.Marker({
                position:new AMap.LngLat(116.39, 39.9),
                content: markerContentBlue,
                offset: new AMap.Pixel(-13, -14)//移动距离:绝对坐标、相对坐标
            });
            map.add(marker1[0]);
        }else{
            map = new AMap.Map('dituContent',{
                resizeEnable: false,
                zoom: 10,
                center: [lng1,lat1]
            });
            marker1[0] = new AMap.Marker({
                position:new AMap.lngLat(lng1,lat1),
                offset: new AMap.Pixel(-13,-14),
                content: markerContentBlue
            });
            map.add(marker1[0]);
        }
        map.on('click', function (e) {
            //1.清楚地图标注
            map.remove(marker1[0]);
            //2.经纬度赋值
            $("#lng").val(e.lnglat.getLng());
            $("#lat").val(e.lnglat.getLat());
            //3.根据经纬度反向地理编码获取地图定位赋值
            var geocoder;
            var lnglatXY = new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat());
            //加载地理编码插件
            map.plugin(["AMap.Geocoder"], function () {
                geocoder = new AMap.Geocoder({
                    radius: 1000, //以已知坐标为中心点,radius为半径,返回范围内兴趣点和道路信息
                    extensions: "all"//返回地址描述以及附近兴趣点和道路信息,默认"base"
                });
                //返回地理编码结果
                AMap.event.addListener(geocoder, "complete", function (e) {
                    console.log(e.regeocode);
                    $("#suggestId").val(e.regeocode.formattedAddress);
                });
                //逆地理编码
                geocoder.getAddress(lnglatXY);
            });
            //4.添加标注
            marker1[0] = new AMap.Marker({
                position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()),
                offset: new AMap.Pixel(-13, -14),
                content: markerContentBlue,
                title: '北京'
            });
            map.add(marker1[0]);
        })
        //根据输入框标注地图
        var auto = new AMap.Autocomplete({
            input:"suggestId",
            city:""
        });
        var placeSearch = new AMap.PlaceSearch({
            city: '',
        });
        //构造地点查询类
        AMap.event.addListener(auto, "select", select);//注册监听,当选中某条记录时会触发
        function select(e) {
            console.log(e.poi)
            map.remove(marker1[0]);
            placeSearch.search(e.poi.name);  //关键字查询查询
            map.setZoomAndCenter(15, [e.poi.location.lng, e.poi.location.lat]); //同时设置地图层级与中心点
        }
    })
</script>
</body>
</html>

效果:
高德地图开发-常用api踩坑使用

高德提供了很多开发实例可以参考:

https://lbs.amap.com/api/javascript-api/example/map-lifecycle/map-show

记录我踩过得坑:
智能搜索:高德提供的实例是:

<script type="text/javascript">
    //地图加载
    var map = new AMap.Map("container", {
        resizeEnable: true
    });
    //输入提示
    var autoOptions = {
        input: "tipinput"
    };
    var auto = new AMap.Autocomplete(autoOptions);
    var placeSearch = new AMap.PlaceSearch({
        map: map
    });  //构造地点查询类
    AMap.event.addListener(auto, "select", select);//注册监听,当选中某条记录时会触发
    function select(e) {
        placeSearch.setCity(e.poi.adcode);
        placeSearch.search(e.poi.name);  //关键字查询查询
    }
</script>

效果是:
高德地图开发-常用api踩坑使用
他是把北京大学这一片的关键位置都给标上了,然后我要实现点击每个点拿到当前位置,可是费了好大劲,虽然后来有个前端大神也给搞定了,但是也很难做到再点击另一个标注时把其它标注都换为蓝点,就是标注的事件就很难拿到,
后来发现只要把实例中var placeSearch = new AMap.PlaceSearch({ map: map }); //构造地点查询类智能搜索类的属性换为city就好了,var placeSearch = new AMap.PlaceSearch({ city: '', }); //构造地点查询类就不会有那些点了,可以通过点击事件去添加、删除标注了,也符合常用体验
不了解的话还真是一点小东西就能折腾好久