龙空技术网

百度地图接口实现添加坐标点和路线

知了堂 376

前言:

今天看官们对“百度地图api使用教程”可能比较讲究,我们都想要剖析一些“百度地图api使用教程”的相关文章。那么小编同时在网络上汇集了一些有关“百度地图api使用教程””的相关资讯,希望各位老铁们能喜欢,兄弟们快快来了解一下吧!

之前在工作中实现了一个小的功能模块是调用百度地图的接口,实现初始化位置点和路线以及自己添加位置点和路线的功能,现在记录一下,方便自己以后来回顾知识。 此demo主要实现了以下功能

在地图上添加位置点,并添加位置点的名称备注,右键停止添加位置点,添加点之后在左侧有一个位置点的列表,当点击列表中的点时,地图会将中心点移动到该点,并在点上显示标签为该位置点的名称备注。在地图上可以添加一条路线,完成路线时右键停止,然后点击保存路线会弹出该线上所有折点的位置点所构成的字符串,点击编辑路线,路线就开启编辑功能,可以修改路线。

下面是添加点的效果图

添加路线时的效果图

以下是JS部分源码

var map;var myVue;var addpoint = false;  //添加点的判断var addline = false;  //添加线的判断$(function () {    initMap();    myVue = new Vue({        el:'#app',        data:{            action:'',            points:[],      // 点的集合            linepoints:[],  //路线上的点的集合            mouseMarker:'',  //跟随鼠标移动的marker点            mouseMarkerTitle:'',  //鼠标移动时显示的label            lines:[],       //线的集合            mouseLine:{} ,   //跟随鼠标移动时的虚拟线            initLine:null,    //初始化时的线            myIcon: '',            tmpLabel:'',            editLine:'',     //可编辑的路线            dialogVisible:false,   //控制信息框的显示与隐藏            lineInfo:'',          //路线上的折点组成的字符串  lng,lat;lng,lat...        },        methods:{            //菜单项位置点点击事件            pointClick:function () {                this.clear();                this.action = "point";                map.disableDoubleClickZoom();                map.addEventListener('rightclick',myVue.clear);                map.addEventListener('mousemove',myVue.mouseMove);                map.addEventListener('click',myVue.addpoint);            },            //菜单项线点击事件            lineClick:function () {                myVue.clear();                this.action = "line";                map.addEventListener('click',this.addLine)                map.addEventListener('rightclick',myVue.clear);                map.addEventListener('mousemove',myVue.mouseMove);            },            save:function () {                if (this.editLine!=""){                    this.editLine.disableEditing();                    this.linepoints = this.editLine.getPath();                }               const {linepoints} = this;               this.lineInfo = "";               for(let i=0;i<linepoints.length;i++){                   this.lineInfo += linepoints[i].lat+','+linepoints[i].lng+';';               }                this.dialogVisible = true;                //console.log(this.linepoints);            },            lineEditClick:function () {                const lines = this.lines;                for (let i=0;i<lines.length;i++){                    map.removeOverlay(lines[i]);                }                this.lines = [];                const editline = new BMap.Polyline(myVue.linepoints,{strokeColor: '#00F0f0',strokeWeight:5,strokrOpacity:1});                map.addOverlay(editline);                this.editLine = editline;                editline.enableEditing();            },            lineDelClick:function () {                const lines = this.lines;                for (let i=0;i<lines.length;i++){                    map.removeOverlay(lines[i]);                }                this.lines = [];                this.linepoints = [];            },            clear:function () {                map.removeEventListener('mousemove',myVue.mouseMove);                map.removeEventListener('click',myVue.addpoint);                map.removeEventListener('click',myVue.addLine);                map.removeEventListener('rightclick',myVue.clear);                map.removeOverlay(myVue.mouseMarker);                this.action = "";                this.mouseMarker = '';                if (this.mouseLine!=""){                    map.removeOverlay(this.mouseLine);                    this.mouseLine = "";                }            },            handleClose(done) {                this.$confirm('确认关闭?')                    .then(_ => {                        done();                    })                    .catch(_ => {});            },            mouseMove:function (e) {                //console.log(1);                if (this.action=='point'){                    myVue.showMousePoint(e);                }else if(this.action=='line'){                    myVue.showMouseLine(e);                }            },            addpoint:function (e) {                if (this.action=='point'){                    this.$prompt('请输入位置点名称', '提示', {                        confirmButtonText: '确定',                        cancelButtonText: '取消',                    }).then(({ value }) => {                        var marker = new BMap.Marker(e.point,{icon:this.myIcon});                        map.addOverlay(marker);                        marker.name = value;                        myVue.points.push(marker);                        this.$message({                            type: 'success',                            message: '位置点: ' + value+'添加成功',                        });                    }).catch(() => {                        this.$message({                            type: 'info',                            message: '位置点添加失败'                        });                    });                }            },            addLine:function (e) {                if(this.action=='line'){                    if (this.linepoints.length>0){                        const line = new BMap.Polyline([this.linepoints[this.linepoints.length-1],e.point],{strokeColor: '#00F0f0',strokeWeight:5,strokrOpacity:1});                        map.addOverlay(line);                        this.lines.push(line);                    }                    this.linepoints.push(e.point)                }            },            showMouseLine:function (e) {                if (this.mouseMarker==""){                    const mouseMarker = new BMap.Marker(e.point,{icon:this.myIcon});                    map.addOverlay(mouseMarker);                    this.mouseMarker = mouseMarker;                }else {                    this.mouseMarker.setPosition(e.point);                }                if (this.linepoints.length>0){                    const mouseline = new BMap.Polyline([this.linepoints[this.linepoints.length-1],e.point],{strokeColor: '#00F5A9',strokeWeight:5,strokrOpacity:0.3});                    map.addOverlay(mouseline);                    map.removeOverlay(this.mouseLine);                    this.mouseLine = mouseline;                }            },            showMousePoint:function (e) {                if (this.mouseMarker==""){                    this.mouseMarker = new BMap.Marker(e.point,{icon:this.myIcon});                    map.addOverlay(this.mouseMarker);                }                this.mouseMarker.setPosition(e.point);            },            toCenter:function (i) {               if (myVue.tmpLabel!=''){                   map.removeOverlay(myVue.tmpLabel);                   myVue.tmpLabel = '';               }                map.panTo(myVue.points[i].point);                var str = " <div class='point_label'> "+myVue.points[i].name+"</div>";                const label = new BMap.Label(str,{position:myVue.points[i].point});                myVue.tmpLabel = label;                map.addOverlay(label);            }        },        mounted:function () {            var myIcon = new BMap.Icon("imgs/point.png", new BMap.Size(40, 50))                myIcon.setImageSize(new BMap.Size(40,50));            this.myIcon = myIcon;            this.points = initPoints();        }    })})function initPoints(){    var myIcon = new BMap.Icon("imgs/point.png", new BMap.Size(40, 50))    myIcon.setImageSize(new BMap.Size(40,50));    var marker = [];    marker[0] = new BMap.Marker(new BMap.Point(118.082868,36.829153),{icon:myIcon});    marker[0].name = "东方实验学校";    marker[1] = new BMap.Marker(new BMap.Point(118.075933,36.830077),{icon:myIcon});    marker[1].name = "东方星城";    marker[2] = new BMap.Marker(new BMap.Point(118.067365,36.834728),{icon:myIcon});    marker[2].name = "温馨家园";    marker[3] = new BMap.Marker(new BMap.Point(118.070112,36.83906),{icon:myIcon});    marker[3].name = "魏家庄";    marker[4] = new BMap.Marker(new BMap.Point(118.0575,36.829644),{icon:myIcon});    marker[4].name = "流泉新村";    marker[5] = new BMap.Marker(new BMap.Point(118.0564458,36.838945),{icon:myIcon});    marker[5].name = "中房翡翠园";    marker[6] = new BMap.Marker(new BMap.Point(118.055272,36.833977),{icon:myIcon});    marker[6].name = "柳泉中学";    marker[7] = new BMap.Marker(new BMap.Point(118.042174,36.834829),{icon:myIcon});    marker[7].name = "金丽大厦";    marker[8] = new BMap.Marker(new BMap.Point(118.047978,36.830424),{icon:myIcon});    marker[8].name = "淄博市公安局";    for (let i=0;i<marker.length;i++){        map.addOverlay(marker[i]);    }    return marker;}function initMap() {    map = new BMap.Map('map');    var center = new BMap.Point(118.065728,36.818262);    map.centerAndZoom(center, 15);    map.enableScrollWheelZoom();}

拓展:高德地图接口api

<!DOCTYPE html><html lang="en"> <head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <meta http-equiv="X-UA-Compatible" content="ie=edge">    <title>Document</title>    <script src="jquery-3.4.1.min.js"></script>    <script type="text/javascript"        src=";></script>    <!--  异步版本 ui组件, 用于添加城市信息 -->    <script src=";></script>    <!-- <script src="//webapi.amap.com/ui/1.0/main-async.js"></script> -->    <!-- 移动端开发时, 添加以下内容 -->    <meta name="viewport" content="initial-scale=1.0, user-scalable=no"></head><style>    #container {        width: 600px;        height: 480px;        display: inline-block;    }    #container1 {        width: 600px;        height: 480px;    }    #right{        float: left;        margin-top: 40px;    }</style> <body>    <!-- 先在开发者页面创建应用,申请key, 然后使用 -->    <!-- 高德教程地址   -->     <!-- 选择城市教程         -->    <div id="container"> </div>    <div id='right'>        <div>            <div class='title'>选择模式</div>            <input type='radio' name='mode' value='dragMap' checked>拖拽地图模式</input>            <!-- </br> -->            <input type='radio' name='mode' value='dragMarker' checked>拖拽图标模式</input>        </div>        <div>            <button id='start'>开始选点</button>            <button id='stop'>关闭选点</button>        </div>        <div>            <div class='title'>选址结果</div>            <div class='c'>经纬度:</div>            <div id='lnglat'></div>            <div class='c'>地址:</div>            <div id='address'></div>            <div class='c'>最近的路口:</div>            <div id='nearestJunction'></div>            <div class='c'>最近的路:</div>            <div id='nearestRoad'></div>            <div class='c'>最近的POI:</div>            <div id='nearestPOI'></div>        </div>    </div>    <div id="container1"> </div>    <!-- 同步加载 -->    <!-- <script type="text/javascript">        var map = new AMap.Map('container', {            center: [117.000231, 36.456755],            zoom: 11        })    </script> -->     <!-- 异步加载,推荐使用, 异步加载指的是为 js API指定加载的回调函数,在 js API 的主体资源加载完毕之后,将自动调用该回调函数. 回调函数应该声明在 JS API入口文件引用之前,异步加载可以减少其对其他脚本执行的阻塞, -->    <script type="text/javascript">        // var position = new AMap.LngLat(116, 39);//标准写法        // var position = [116, 39]; //简写, 经纬度不能加引号         // 创建地图        // 如果不传入center坐标, 会默认定位到所在城市,可以使用插件进行自动定位        var map = new AMap.Map('container', {            // center: [117.000000, 38.000000], //设置地图中心点坐标            zoom: 14, //级别, 级别与地图尺寸成正比,越大越详细, web最小为3级,高德最大为20            viewMode: '2D', // 设置地图的显示样式            lang: 'zh_cn',  //设置地图语言类型            mapStyle: 'amap://styles/whitesmoke',  //设置地图的显示样式        });        // 加载一个(不使用数组)或多个插件        AMap.plugin(['AMap.ToolBar', 'AMap.Driving', 'AMap.CitySearch', 'Zepto'], function () {            var toolbar = new AMap.ToolBar(); //工具条, 地图的缩放,平移            map.addControl(toolbar);            // var driving = new AMap.Driving(); // 驾车路线规划            // driving.search("参数")             // ip定位            var citySearch = new AMAP.citySearch()            citySearch.getLocalCity(function (status, result) {                if (status === 'complete' && result.info === 'OK') {                    // 查询成功, result为当前所在城市信息                    // result.bounds  为当前所在经纬度, 113.315606,34.536169                    if (result && result.city && result.bounds) {                        var cityinfo = result.city;                        var citybounds = result.bounds;                        // document.getElementById('info').innerHTML = '您当前所在城市:' + result.bounds;                        //地图显示当前城市                        map.setBounds(citybounds);                    }                } else {                    // document.getElementById('info').innerHTML = result.info;                }            });         });          // 加载ui模块, 可以地图选点        // 'control/BasicControl' 多个地图图层的组件        // misc/PositionPicker 选坐标的组件        AMapUI.loadUI(['misc/PositionPicker', 'control/BasicControl'], function (PositionPicker) {            // 如果使用ui组件, map 则在ui组件里定义即可            var map = new AMap.Map('container', {                zoom: 16,                scrollWheel: false            })            var positionPicker = new PositionPicker({                mode: 'dragMarker',                map: map,                iconStyle: { //自定义外观                    url: ';,                    ancher: [24, 40],                    size: [48, 48]                }            });             positionPicker.on('success', function (positionResult) {                document.getElementById('lnglat').innerHTML = positionResult.position;                document.getElementById('address').innerHTML = positionResult.address;                document.getElementById('nearestJunction').innerHTML = positionResult.nearestJunction;                document.getElementById('nearestRoad').innerHTML = positionResult.nearestRoad;                document.getElementById('nearestPOI').innerHTML = positionResult.nearestPOI;            });            positionPicker.on('fail', function (positionResult) {                document.getElementById('lnglat').innerHTML = ' ';                document.getElementById('address').innerHTML = ' ';                document.getElementById('nearestJunction').innerHTML = ' ';                document.getElementById('nearestRoad').innerHTML = ' ';                document.getElementById('nearestPOI').innerHTML = ' ';            });            var onModeChange = function (e) {                positionPicker.setMode(e.target.value)            }            var startButton = document.getElementById('start');            var stopButton = document.getElementById('stop');            var dragMapMode = document.getElementsByName('mode')[0];            var dragMarkerMode = document.getElementsByName('mode')[1];            AMap.event.addDomListener(startButton, 'click', function () {                positionPicker.start(map.getBounds().getSouthWest())            })            AMap.event.addDomListener(stopButton, 'click', function () {                positionPicker.stop();            })            AMap.event.addDomListener(dragMapMode, 'change', onModeChange)            AMap.event.addDomListener(dragMarkerMode, 'change', onModeChange);            positionPicker.start();        })         //多个地图图层        AMapUI.loadUI(['control/BasicControl'], function (BasicControl) {            var layerCtrl1 = new BasicControl.LayerSwitcher({                position: 'tr'            });            var map1 = new AMap.Map('container1', {                //这里将layerCtrl中启用的图层传递给map                layers: layerCtrl1.getEnabledLayers()            });            map1.addControl(layerCtrl1);            var layerCtrl2 = new BasicControl.LayerSwitcher({                theme: 'dark',                //自定义基础图层                baseLayers: [{                    enable: true, //默认显示                    id: 'tile',                    name: '标准图',                    layer: new AMap.TileLayer()                }, {                    id: 'satellite',                    name: '卫星图',                    layer: new AMap.TileLayer.Satellite()                }],                //自定义覆盖图层                overlayLayers: [{                    enable: true,                    id: 'traffic',                    name: '路况图',                    layer: new AMap.TileLayer.Traffic()                }, {                    id: 'roadNet',                    name: '路网图',                    layer: new AMap.TileLayer.RoadNet()                }]            });            var map2 = new AMap.Map('container1', {                //这里将layerCtrl中启用的图层传递给map                layers: layerCtrl2.getEnabledLayers()            });            map2.addControl(layerCtrl2);        });           map.on('complete', function () {            // 地图加载完成后触发complete事件        })        // map.destroy(); // 销毁地图,并清空地图容器       </script>    <script type="text/javascript"        src=";></script>    <!-- 或者 -->    <!-- <script>        window.onLoad = function(){            var map = new AMap.Map("container");        }        var url = ';        var jsapi = document.createElement('script');        jsapi.charset = 'utf-8';        jsapi.scr = url;        document.head.appendChild(jsapi);    </script> --></body> </html>
两者的区别1、对于使用者的主要区别:

高德注重导航的功能,

1、有很多路连名字都没有,但是高德依旧可以标记出来

用于骑行、徒步等低速运动,需要更详细地显示细节,高德地图则好于百度

2、高德语音提示比较全面,导航只听语音的话

百度注重生活的功能

1、实景功能 三维效果逼真,方便用户能够精准的找出目的位置

2、商家服务 对查找商家等

路线的优选

高德会给出路程最短的(省油,适合长图)

百度则有更多的考虑,包括避开拥堵路段(省时,适合城市里)

2、对开发者的主要区别:百度地图:

网页版地图平台更好(Android、IOS、WEB)。

支持全景API

POI数据很丰富

缺点:api文档(烂的一批)

高德地图:

开发者人群的支持面更高,

平台适用性更好(Android、IOS、windows phone、Win8、web)。

标签: #百度地图api使用教程