uniapp 使用高德地图,选择开始和结束地点,生成驾车路径

uniapp 使用高德地图,选择开始和结束地点,生成驾车路径

vue文件内容

<template>
    <view>
        <u--input
            placeholder="请输入开始地点"
            border="surround"
            shape="circle"
            v-model="startPlaceName"
            @change="searchLocation('startPlaceName')"
            @focus="startPlaceFocus"
          ></u--input>
          <u-picker  :show="startPlaceNameListOpen" :columns="[startPlaceNameList]" keyName="name" @confirm="confirmStart" @cancel="cancelStart" @close="cancelStart"></u-picker>
          <u--input
              placeholder="请输入结束地点"
              border="surround"
                shape="circle"
              v-model="endPlaceName"
              @change="searchLocation('endPlaceName')"
              @focus="endPlaceFocus"
            ></u--input>
            <u-picker  :show="endPlaceNameListOpen" :columns="[endPlaceNameList]" keyName="name" @confirm="confirmEnd" @cancel="cancelEnd" @close="cancelEnd"></u-picker>
        <div id="container" style="width: 100%; height: 450px;"></div>
        <div id="panel"></div>
        <u-notify ref="uNotify" message="请先选择开始结束地点"></u-notify>
        <u-picker :show="strategyListOpen" :columns="[strategyList]" keyName="name" @confirm="selectStrategy1" @cancel="strategyListOpen = false" @close="strategyListOpen = false"></u-picker>
        
        <u-row >
            <u-col span="6">
                <u-button @click="strategyListOpen = true" text="选择路线策略"></u-button>
            </u-col>
            <u-col span="6">
                <u-button @click="drivingSearch" text="搜索路线"></u-button>
            </u-col>
        </u-row>
        <u-button @click="drivingSearch" text="保存路线"></u-button>
    </view>
</template>

<script>
    import AMapLoader from '@amap/amap-jsapi-loader';
    window._AMapSecurityConfig = {
      securityJsCode: ''
    }
    export default {
        data() {
            return {
                map: null,
                AMap:null,
                center:[112.5226,32.985824],
                startPlaceName:'',
                endPlaceName:'',
                startPlaceNameList:[],
                endPlaceNameList:[],
                startPlaceNameListOpen:false,
                endPlaceNameListOpen:false,
                startLocation:null,
                endLocation:null,
                startMarker:null,
                endMarker:null,
                path:[],
                strategyList:[],
                strategyListOpen:false,
                selectStrategy:null
            }    
        },
        mounted(){
            this.init();
        },
        methods: {
            init(){
                AMapLoader.load({
                    "key": "",              // 申请好的Web端开发者Key,首次调用 load 时必填
                    "version": "2.0",   // 指定要加载的 JSAPI 的版本,缺省时默认为 1.4.15
                    "plugins": ["AMap.GraspRoad","AMap.PolyEditor","AMap.Driving","AMap.DrivingPolicy","AMap.Marker","AMap.LngLat","AMap.AutoComplete"],           // 需要使用的的插件列表,如比例尺'AMap.Scale'等
                }).then((AMap)=>{
                    this.map = new AMap.Map('container',{
                        zoom:10,
                        center:[...this.center]
                    });
                    this.AMap = AMap;
                    
                    var thih = this;
                    this.map.on('click', function(ev) {
                      var lnglat = ev.lnglat;
                      if(thih.startLocation == null){
                          thih.startLocation = [lnglat.getLng(),lnglat.getLat()];
                          thih.startMarker = new AMap.Marker({
                              position: thih.startLocation,   // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
                              title: "无效"
                          });
                           thih.startMarker.setContent("<span style=\"color:red;font-size:20px;\">开始</span>");
                          thih.startMarker.setMap(thih.map);
                          thih.startMarker.on('click', function(ev) {
                              thih.startLocation=null;
                              thih.startMarker.remove(thih.map);
                              thih.startMarker=null;
                          });
                      }else if(thih.endLocation == null){
                          thih.endLocation=[lnglat.getLng(),lnglat.getLat()];
                          thih.endMarker = new AMap.Marker({
                              position: thih.endLocation,   // 经纬度对象,也可以是经纬度构成的一维数组[116.39, 39.9]
                              title: "无效"
                          });
                          thih.endMarker.setContent("<span style=\"color:red;font-size:20px;\">结束</span>");
                          thih.endMarker.setMap(thih.map);
                          thih.endMarker.on('click', function(ev) {
                              thih.endLocation=null;
                              thih.endMarker.remove(thih.map);
                              thih.endMarker=null;                  
                          }); 
                      }else{
                          return ;
                      }
                    });
                    
                    this.strategyList.push({"value":AMap.DrivingPolicy.LEAST_TIME,"name":"最快捷模式"});
                    this.strategyList.push({"value":AMap.DrivingPolicy.LEAST_FEE,"name":"最经济模式"});
                    this.strategyList.push({"value":AMap.DrivingPolicy.LEAST_DISTANCE,"name":"最短距离模式"});
                    this.strategyList.push({"value":AMap.DrivingPolicy.REAL_TRAFFIC,"name":"考虑实时路况"});
                }).catch(e => {
                    console.log(e);
                })
            },
            drivingSearch(){
                let AMap = this.AMap;
                var thih = this;
                if(thih.startLocation == null || thih.endLocation==null){
                    this.$refs.uNotify.show({
                        top: 10,
                        type: 'warning',
                        color: '#000',
                        bgColor: '#e8e8e8',
                        message: '请先选择开始结束地点',
                        duration: 1000 * 3,
                        fontSize: 20,
                        safeAreaInsetTop:true
                    })
                    return
                }
                if(this.selectStrategy==null){
                    this.selectStrategy = 0;
                }
                var drivingOption = {
                    policy: this.selectStrategy, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
                    ferry: 1, // 是否可以使用轮渡
                    province: '京', // 车牌省份的汉字缩写 
                    map: thih.map,
                    //panel: 'panel'
                }
                 // 构造路线导航类
                 var driving = new AMap.Driving(drivingOption)
                 // 根据起终点经纬度规划驾车导航路线
                 driving.search(new AMap.LngLat(...thih.startLocation), new AMap.LngLat(...thih.endLocation), function(status, result) {
                     // result 即是对应的驾车导航信息,相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
                     if (status === 'complete') {
                         var steps= result.routes[0].steps;
                         var dian=[];
                         for(var i =0;i<steps.length;i++){
                             var yijie=steps[i].path;
                              for(var j =0;j<yijie.length;j++){
                                 var path=yijie[j];
                                 dian.push([path.getLng(),path.getLat()]);
                             } 
                             /*dian.push([yijie[0].getLng(),yijie[0].getLat()]);
                             dian.push([yijie[yijie.length-1].getLng(),yijie[yijie.length-1].getLat()]);*/ 
                         }
                         thih.path=dian;
                       console.log(result)
                       console.log(JSON.stringify(dian))
                     } else {
                         log.error('获取驾车数据失败:' + result)
                     }
                 });
            },
            searchLocation(varName){
                var keyword = '';
                if(varName=='startPlaceName'){
                    keyword = this.startPlaceName;
                    if(keyword == ''){
                        this.startPlaceNameList=[];
                        this.startPlaceNameListOpen=false;
                    }
                }else if(varName=='endPlaceName'){
                    keyword = this.endPlaceName;
                    if(keyword == ''){
                        this.endPlaceNameList=[];
                        this.endPlaceNameListOpen=false;
                    }
                }
                
                
                let AMap = this.AMap;
                var thih = this;
                var autoOptions = {
                    //city 限定城市,默认全国
                    city: '全国'
                };
                // 实例化AutoComplete
                var autoComplete= new AMap.AutoComplete(autoOptions);
                // 根据关键字进行搜索
                autoComplete.search(keyword, function(status, result) {
                    // 搜索成功时,result即是对应的匹配数据 startPlaceNameList 
                    if(result != "NO_PARAMS"){
                        var data=result.tips;
                        if(varName=='startPlaceName'){
                            for(var i =0;i<data.length;i++){
                                thih.startPlaceNameList.push({name:data[i]['name']+"-"+data[i]['district'],location:data[i]['location']!=null && typeof(data[i]['location'].getLng)=="function" ?[data[i]['location'].getLng(),data[i]['location'].getLat()]:null});
                            }
                            thih.startPlaceNameListOpen=true;
                        }else if(varName=='endPlaceName'){
                            for(var i =0;i<data.length;i++){
                                thih.endPlaceNameList.push({name:data[i]['name']+"-"+data[i]['district'],location:data[i]['location']!=null && typeof(data[i]['location'].getLng)=="function" ?[data[i]['location'].getLng(),data[i]['location'].getLat()]:null});
                            }
                            thih.endPlaceNameListOpen=true;
                        }
                    }
                })
            },
            confirmStart(e){
                var l=e.value[0].location;
                var n=e.value[0].name;
                if(l!=null){
                    this.map.setCenter(l);
                }
                //this.startPlaceName=n;
                this.startPlaceNameListOpen=false;
            },
            cancelStart(){
                this.startPlaceNameListOpen=false;
            },
            cancelEnd(){
                this.endPlaceNameListOpen=false;
            },
            confirmEnd(e){
                var l=e.value[0].location;
                var n=e.value[0].name;
                if(l!=null){
                    this.map.setCenter(l);
                }
                //this.startPlaceName=n;
                this.endPlaceNameListOpen=false;
            },
            startPlaceFocus(){
                if(this.startPlaceNameList.length>0){
                    this.startPlaceNameListOpen=true;
                }
            },
            endPlaceFocus(){
                if(this.endPlaceNameList.length>0){
                    this.endPlaceNameListOpen=true;
                }
            },
            selectStrategy1(e){
                var v=e.value[0].value;
                this.selectStrategy=v;
                this.strategyListOpen=false;
            }
        }
    }
</script>

<style>

</style>
  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值