ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

地图

2020-06-08 10:03:45  阅读:235  来源: 互联网

标签:function map val qq 地图 marker new


let mapProvince = '';
let mapDistrict = '';
let mapCity = '';
let mapStreet = '';
var box = document.getElementById("container");
var center, map, marker, infoWindow, geocoder;
//腾讯地图
$(function () {
    init();
});
function init() {
    //定义map变量 调用 qq.maps.Map() 构造函数   获取地图显示容器
    center = new qq.maps.LatLng($("#hidLat").val(), $("#hidLng").val());
    map = new qq.maps.Map(box, {
        center: center,
        zoom: 15
    });
    //以当前点为坐标添加marker
    newMarker(center);
    //marker = new qq.maps.Marker({
    //    position: center,
    //    draggable: true,
    //    map: map
    //});
    //var label = new qq.maps.Label({
    //    position: center,
    //    map: map,
    //    content: '移动标注取货位置'
    //});

    //地图添加监听事件   获取鼠标单击事件
    qq.maps.event.addListener(map, 'click', function (event) {
        //marker.setMap(null);
        //marker = new qq.maps.Marker({
        //    position:event.latLng,
        //    draggable: true,
        //    map:map
        //});
        //更新地址和坐标信息
        setLatLngAndAddr(event.latLng.lat, event.latLng.lng);
    });
    //添加提示窗
    infoWindow = new qq.maps.InfoWindow({
        map: map
    });
    //qq.maps.event.addListener(marker, 'click', function () {
    //    infoWindow.open();
    //    infoWindow.setContent('<div style="text-align:center;white-space:nowrap;' +
    //    'margin:10px;">移动标注取货位置</div>');
    //    infoWindow.setPosition(center);
    //});
    //逆地址解析
    geocoder = new qq.maps.Geocoder({
        complete: function (result) {
            //alert('解析成功:' + result.detail.address);
            mapProvince = result.detail.addressComponents.province;
            mapCity = result.detail.addressComponents.city;
            mapDistrict = result.detail.addressComponents.district;
            if(result.detail.addressComponents.streetNumber != ''){
                mapStreet = result.detail.addressComponents.streetNumber;
            }else{
                mapStreet = result.detail.addressComponents.street;
            }
            $("#addr").html(result.detail.address);
        }
    });

    //更换地址
    $("#updLocation").on('click',function () {
        $("#container").css("display", "");
    });
    // $("#updLocation").click(function () {
    //     $("#container").css("display", "");
    // });
}
//微信配置
wx.config({
    debug: false, // 开启调试模式
    appId: "@ViewBag.appId",
    timestamp: "@ViewBag.timestamp",
    nonceStr: "@ViewBag.nonceStr",
    signature: "@ViewBag.signature",
    jsApiList: [
        'getNetworkType',//网络状态接口
        'openLocation',//使用微信内置地图查看地理位置接口
        'getLocation' //获取地理位置接口
    ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});

wx.ready(function () {
    //获取当前地理位置
    get_now_location();

    //// 查看地理位置
    //$("#openLocation").click(function () {
    //    alert($("#hidLat").val() + "==" + $("#hidLng").val());
    //    wx.openLocation({
    //        latitude: parseFloat($("#hidLat").val()),
    //        longitude: parseFloat($("#hidLng").val()),
    //        name: '这是哪?',
    //        address: '详细地址我也不清楚',
    //        scale: 14,
    //        infoUrl: 'http://weixin.qq.com'
    //    });
    //});

});
function get_now_location() {
    wx.getLocation({
        type: 'gcj02', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'
        success: function (res) {
            //console.log(res);
            var latitude = res.latitude;
            var longitude = res.longitude;
            //alert(JSON.stringify(res));

            //保存获取当前位置的经纬度
            $("#hidNowLat").val(latitude);
            $("#hidNowLng").val(longitude);
            //更新地址和坐标信息
            setLatLngAndAddr(latitude, longitude);
            //$("#hidLat").val(latitude);
            //$("#hidLng").val(longitude);
            ////逆地址解析
            //var coord = new qq.maps.LatLng(latitude, longitude);
            //geocoder.getAddress(coord);

        },
        cancel: function (res) {
            alert('用户拒绝授权,无法获取地理位置');
        }

    });
}
function setLatLngAndAddr(latitude, longitude) {
    var coord = new qq.maps.LatLng(latitude, longitude);
    map.setCenter(coord);
    //以当前点为坐标添加marker
    newMarker(coord);

    $("#hidLat").val(latitude);
    $("#hidLng").val(longitude);
    //逆地址解析
    geocoder.getAddress(coord);
}
function newMarker(coordinate) {
    if (marker != null) {
        marker.setMap(null);
    }
    marker = new qq.maps.Marker({
        position: coordinate,
        draggable: true,
        map: map
    });
    //marker事件
    qq.maps.event.addListener(marker, 'dragend', function (event) {
        //更新地址和坐标信息
        setLatLngAndAddr(event.latLng.lat, event.latLng.lng);
    });
    qq.maps.event.addListener(marker, 'click', function (event) {
        //更新地址和坐标信息
        setLatLngAndAddr(event.latLng.lat, event.latLng.lng);
    });
}
function GoApp(typeID) {
    //获取的当前位置
    var nowLng = $("#hidNowLng").val();
    var nowLat = $("#hidNowLat").val();
    //目的地
    var lng = $("#hidLng").val();
    var lat = $("#hidLat").val();
    var addr = $("#addr").html();
    if (typeID == 1) {//腾讯APP http://lbs.qq.com/webApi/uriV1/uriGuide/uriWebRoute
        window.location.href = "http://apis.map.qq.com/uri/v1/routeplan?type=drive&from=当前位置&fromcoord=" + nowLat + "," + nowLng + "&to=" + addr + "&tocoord=" + lat + "," + lng + "&policy=0&referer=wuliupingtai";
    }
    else if (typeID == 2) {//高德APP https://lbs.amap.com/api/uri-api/guide/travel/route
        window.location.href = "https://uri.amap.com/navigation?from=" + nowLng + "," + nowLat + ",当前位置&to=" + lng + "," + lat + "," + addr + "&mode=car&policy=0&coordinate=gaode&callnative=1&src=wuliupingtai";
    }
    else if (typeID == 3) {//百度APP http://lbsyun.baidu.com/index.php?title=uri/api/web
        window.location.href = "http://api.map.baidu.com/direction?origin=name:当前位置|latlng:" + nowLat + "," + nowLng + "&destination=latlng:" + lat + "," + lng + "|name:" + addr + "&origin_region=起点城市&destination_region=终点城市&mode=driving&coord_type=gcj02&output=html&src=wuliupingtai";
    }
}


//百度地图  http://api.map.baidu.com/direction?origin=latlng:36.064937,120.380959|name:当前位置&destination=latlng:40.010024,116.392239|name:您的位置&origin_region=青岛&destination_region=西安&mode=driving&coord_type=gcj02&output=html&src=wuliupingtai

//高德地图  https://uri.amap.com/navigation?from=120.380959,36.064937,当前位置&to=116.392239,40.010024,您的位置&mode=car&policy=0&coordinate=gaode&callnative=1&src=wuliupingtai

//$(function () {
//    GetGPSLocation();
//});
////GPS获取当前坐标位置cityNameID-放城市名称容器的ID  typeID=0是从Default页面来要去index页 =1是文本框 =2是div
//function GetGPSLocation() {
//    //    alert("hello");
//    var map = new BMap.Map("container");
//    var point = new BMap.Point(120.380959, 36.064937); //new BMap.Point(116.414106, 39.897034);
//    map.centerAndZoom(point, 15);
//    var marker = new BMap.Marker(point);
//    map.addOverlay(marker);

//    var geolocation = new BMap.Geolocation();
//    geolocation.getCurrentPosition(function (r) {
//        if (this.getStatus() == BMAP_STATUS_SUCCESS || this.getStatus() == 0) {
//            map.removeOverlay(marker);

//            alert('您的位置:' + r.point.lng + ',' + r.point.lat + ',' + this.getStatus());
//            marker = new BMap.Marker(r.point);
//            map.addOverlay(marker);
//            map.panTo(r.point);
//            $("#hidLng").val(r.point.lng);
//            $("#hidLat").val(r.point.lat);
//        }
//        else {
//            alert('failed' + this.getStatus());
//        }
//    });

//    ////实例化浏览器定位对象。
//    //var geolocation = new bmap.geolocation();
//    ////定位结果对象会传递给r变量
//    //geolocation.getcurrentposition(function (r) {
//    //    alert("this.getstatus()=" + this.getstatus());

//    //    //通过geolocation类的getstatus()可以判断是否成功定位。
//    //    if (this.getstatus() == bmap_status_success || this.getstatus() == 0) {
//    //        //获取gps定位得到的点
//    //        point = r.point;
//    //        alert(r.point.lng + "??" + r.point.lat);
//    //        //$("#hidlng").val(r.point.lng);
//    //        //$("#hidlat").val(r.point.lat);
//    //        //setbaidugeocoder(r.point.lng, r.point.lat, citynameid, typeid);
//    //    }
//    //    else {
//    //        alert('failed' + this.getstatus());
//    //        //getjbox("green", "开启gps可自动定位");
//    //    }
//    //}, { enablehighaccuracy: true });

//}
<div id="app">
<van-cell-group>
<van-row>
<van-col span="21">
<van-field v-model="OriginAddr" name="OriginAddr" label="发货地址" placeholder="街道门牌、楼层房间号等信息" ></van-field>
</van-col>
<van-col span="3" class="lh44">
<van-icon v-on:click="addressmap(1)" class="iconfont iconmap1" style="font-size: 0.44rem; padding:5px 10px 5px 0;" class-prefix='iconmap1' name="iconmap1"></van-icon>
</van-col>
</van-row>
</van-cell-group>
    <div style="display:none;">
<div>取货地址:
<div id="addr"></div>
@*<a id="openLocation">查看位置</a>*@
<a id="updLocation">点击更换地址</a>
</div>
<div>经度:<input id="hidLng" value="120.380959" type="text"/></div>
<div>纬度:<input id="hidLat" value="36.064937" type="text"/></div>
<div onclick="GoApp(1)">腾讯地图APP</div>
<div onclick="GoApp(2)">高德地图APP</div>
<div onclick="GoApp(3)">百度地图APP</div>
<div>当前位置的经度:<input id="hidNowLng" value="120.380959" type="text"/></div>
<div>当前位置的纬度:<input id="hidNowLat" value="36.064937" type="text"/></div>
</div>
</div>

<!--地图的容器,必须在根目录-->
<div id="container" style="display:none;"></div>
<!--弹窗地图组件-->
<template id="mymap">
<div>
<div id="linshi"></div>
<div style="padding:16px 16px 0 16px;">
<div id="addr" style="height: 25px;"></div>
<!--<div>经度:<input id="hidLng" value="120.380959" type="text"/></div>-->
<!--<div>纬度:<input id="hidLat" value="36.064937" type="text"/></div>-->
<!--<div>当前位置的经度:<input id="hidNowLng" value="120.380959" type="text"/></div>-->
<!--<div>当前位置的纬度:<input id="hidNowLat" value="36.064937" type="text"/></div>-->
</div>
<van-row style="padding:16px;">
<van-col span="11">
<van-button type="warning" style="width:100%;" v-on:click="myclosemap" native-type="button">取消</van-button>
</van-col>
<van-col span="2"></van-col>
<van-col span="11">
<van-button type="info" style="width:100%;" v-on:click="mysubmap" native-type="button">确认</van-button>
</van-col>
</van-row>
</div>
</template>

<script charset="utf-8" src="/Scripts/jweixin-1.6.0.js "></script>
<script type="text/javascript" charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=7M5BZ-EXN6D-SLM4J-PCA26-K56E2-VFBOH"></script>
<script type="text/javascript" src="/Scripts/map.js "></script>

//点击小图标展开地图
        addressmap(num){
            if(num == 1){
                this.curNum = 1;//始发地
                //如果已经设置过经纬值,再次定位的情况下,可以将坐标定位到上次设置的地点
                if(this.address1["Lat"] != undefined && this.address1["Lat"] != 0){
                    setLatLngAndAddr(this.address1["Lat"], this.address1["Lng"]);
                }
            }else{
                this.curNum = 2;//目的地
                //如果已经设置过经纬值,再次定位的情况下,可以将坐标定位到上次设置的地点
                if(this.address2["Lat"] != undefined && this.address2["Lat"] != 0){
                    setLatLngAndAddr(this.address2["Lat"], this.address2["Lng"]);
                }
            }
            let self = this;
            this.addarea_map = true;//展开地图
            //将地图容器显示设置宽高
            $("#container").css({"display":"block","width":"100%","height":"350px"});
            //console.log($("#container"));
            this.$nextTick(function(){
                //让地图html码插入子组件容器
                $("#linshi").append($("#container"))
            })
            //console.log($("#hidNowLng").val(),$("#hidNowLat").val());
            //console.log($("#hidLng").val(),$("#hidLat").val());
        },
        //关闭地图
        closemap(){
            this.addarea_map = false;
        },
        //确认地图
        submap(){
            let pcode = 0,ccode = 0,acode = 0;
            if(encodeURI(mapProvince) == encodeURI(mapCity)){
                mapCity = '市辖区'
            }
            this.getMapCodeFn(mapProvince,mapCity,mapDistrict,this.curNum)
            //console.log(mapProvince,mapCity,mapDistrict,mapStreet)
            //判断现在展开的是始发地或目的地
            if(this.curNum == 1){
                //经纬度
                this.address1["Lng"] = /^(\d+)(\.\d{7})?/.exec($("#hidLng")[0].value)[0];//经度(最多保留7位小数),未取值默认传0
                this.address1["Lat"] = /^(\d+)(\.\d{7})?/.exec($("#hidLat")[0].value)[0];//纬度(最多保留7位小数),未取值默认传0
                //console.log($("#hidLng")[0].value,$("#hidLat")[0].value,$("#hidNowLng")[0].value,$("#hidNowLat")[0].value,$("#addr").text())
            }else{
                this.address2["Lng"] = /^(\d+)(\.\d{7})?/.exec($("#hidLng")[0].value)[0];//经度(最多保留7位小数),未取值默认传0
                this.address2["Lat"] = /^(\d+)(\.\d{7})?/.exec($("#hidLat")[0].value)[0];//纬度(最多保留7位小数),未取值默认传0
                //console.log($("#hidLng")[0].value,$("#hidLat")[0].value,$("#hidNowLng")[0].value,$("#hidNowLat")[0].value,$("#addr").text())
            }
            //console.log(this.address1,this.address2)
        },


        //通过省市区名称获取code
        async getMapCodeFn(province,city,area,num){
            //num也可以不传的直接拿this.curNum
            let self = this;
            await getMapCode(province,city,area).then(msg => {
                //console.log(msg.status.sub_msg)
                if (msg.status.code == 1) {
                    let ary = msg.status.sub_msg.split(',');
                    if(num == 1){
                        //1始发地
                        this.screenval1 = city + "-" + area;//始发地不显示省province + "-" +
                        this.address1["OProvince"] = province;
                        this.address1["OCity"] = city;
                        this.address1["OArea"] = area;
                        this.address1["OPCode"] = ary[0];
                        this.address1["OCCode"] = ary[1];
                        this.address1["OACode"] = ary[2];

                        this.OriginAddr = mapStreet;
                        this.addarea_map = false;
                    }else{
                        //2目的地
                        // this.screenval2 = city + "-" + area;//province + "-" +
                        // this.address2["DProvince"] = province;
                        // this.address2["DCity"] = city;
                        // this.address2["DArea"] = area;
                        // this.address2["DPCode"] = ary[0];
                        // this.address2["DCCode"] = ary[1];
                        // this.address2["DACode"] = ary[2];
                        //
                        // this.addarea_map = false;
                    }
                //console.log(this.address1,this.address2)
                } else {
                    self.$toast(msg.status.msg)
                    return;
                };
            }).catch(msg=>{
                console.log(msg)
                //self.$toast(msg)
            })
        },

 

标签:function,map,val,qq,地图,marker,new
来源: https://www.cnblogs.com/liufeiran/p/13063933.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有