tnblog
首页
视频
资源
登录

C#腾讯地图Web端定位地址搜索及手机导航

6095人阅读 2018/11/29 9:18 总访问:177935 评论:0 收藏:0 手机
分类: .NET

前段时间项目涉及到腾讯地图的业务,这里马克一下。

一开始做腾讯地图功能完全是懵逼的,一搜网上做百度地图居多,问为什么不用百度地图,原因是后面会衔接微信,百度定图定位会有偏差,网上一搜,果真有不少网友吐槽有一公里左右偏差,然后屁颠屁颠的跑去看腾讯地图的官方文档了。

腾讯地图API入口:https://lbs.qq.com/javascript_v2/demo.html   重点看参考手册和示例

腾讯地图API技术交流群:161525145 (本人保证没有收任何广告费)

我要实现的业务是:

①后台网页端加载腾讯地图,显示实现设置好的几个坐标点

②如果默认没有标点的话显示浏览器当前位置

③自定义地址,可以在地图上搜索位置,取得经纬度加进数据库

④在手机端显示数据库坐标点 实现导航效果  

在网页端后台显示地图  话不多说 上代码


HTML部分

  <div class="mapBox">
         <div id="mapBox" style="height:300px">
           <p id="mapInfo"></p>
          </div>
  </div>


引入两个JS


 <script charset="utf-8" src="http://map.qq.com/api/js?v=2.exp"></script>
 <script src="http://g.tbcdn.cn/mtb/lib-flexible/0.3.4/??flexible_css.js,flexible.js">


JS部分(关键代码)


 <script type="text/javascript">
        jQuery(document).ready(function () {
            VGeneral.init('Site');
            Site.init();
            showMap();
        });
        function showMap() {
            var map = new qq.maps.Map(document.getElementById("mapBox"), {    //地图部分初始化
                zoom: 24,               //设置地图缩放级别
                center: new qq.maps.LatLng(24.968320, 118.571190),     //设置中心点
                zoomControl: true,    //不启用缩放控件
                mapTypeControlOptions: {  //设置控件的地图类型为普通街道地图
                    mapTypeIds: qq.maps.MapTypeId.ROADMAP
                }
            });
 
            var info = new qq.maps.InfoWindow({ map: map });      //添加提示窗
            $.post("/Site/GetData", function (data) {
                var result = $.parseJSON(data);
                //result中数据 用于显示标记、和标记点击时的提示信息
                if (result.total > 0) {
                    for (var i = 0; i < result.rows.length; i++) {
                        var row = result.rows[i];
                        if (row.IsShowGIS) {
                            var marker = new qq.maps.Marker({
                                position: new qq.maps.LatLng(row.latitude, row.longitude),
                                map: map
                            });
                            //创建标记
                            //***将必要的数据存入每一个对应的marker对象
                            marker.id = row.ID;
                            marker.name = row.Name;
                            marker.locate = row.Address;
                            marker.latitude = row.latitude;
                            marker.longitude = row.longitude;
                            //点击坐标点
                            qq.maps.event.addListener(marker, 'click', function () {
                                $('#dg').datagrid('clearSelections');
                                $('#dg').datagrid('selectRow', $('#dg').datagrid('getRowIndex', this.id));
                            });
                        }
 
                    };
                }
            });
        }
    </script>


添加搜索坐标点

HTML部分

<div class="row-fluid">
                        <div class="span6 ">
                            <div class="control-group">
                                <label class="control-label">GIS地图</label>
                                <div class="controls">
                                    <label class="checkbox">
                                        <input type="checkbox" id="txtIsShowGIS" checked /> 显示
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row-fluid">
                        <div class="span6 ">
                            <div class="control-group">
                                <label class="control-label">纬度</label>
                                <div class="controls">
                                    <input type="text" id="txtlatitude" class="easyui-validatebox textbox m-wrap span12" data-options="" />
                                </div>
                            </div>
                        </div>
                        <div class="span6 ">
                            <div class="control-group">
                                <label class="control-label">经度</label>
                                <div class="controls">
                                    <input type="text" id="txtlongitude" class="easyui-validatebox textbox m-wrap span12" data-options="" />
                                </div>
                            </div>
                        </div>
                    </div>
                   <h3 class="form-section">GIS地图</h3>
                    <div class="row-fluid">
                        <div class="span4 ">
                            <div class="control-group">
                                <label class="control-label">省市</label>
                                <div class="controls">
                                    <input type="text" id="regionText" class="easyui-validatebox textbox m-wrap span12" data-options="" value="泉州"/>
                                </div>
                            </div>
                        </div>
                        <div class="span4 ">
                            <div class="control-group">
                                <label class="control-label">地址</label>
                                <div class="controls">
                                    <input type="text" id="poiText" class="easyui-validatebox textbox m-wrap span12" data-options="" />
                                </div>
                            </div>
                        </div>
                        <div class="span4 ">
                            <button type="button" class="btn blue" onclick="getResult()">查 询<i class="m-icon-swapright m-icon-white"></i></button>
                        </div>
                        
                    </div>
                    <div class="row-fluid">
                        <div class="span6 ">
                            <div id="container" style="height:400px"></div>
                        </div>
                        <div class="span6 ">
                            <div id="infoDiv">
                            </div>
                            <div>
                                <span style="display: none" id="city"></span>
                            </div>
                        </div>
                        
                    </div>


JS部分


<script charset="utf-8" src="http://map.qq.com/api/js?v=2.exp"></script>
<script type="text/javascript" src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>
    <script type="text/javascript">
        jQuery(document).ready(function ()
        {
            $("#hidid").val('@ViewData["id"]');
            VGeneral.init('SiteEdit');
            Site.initedit();
            
            
        });
        /***************************************网页经纬度*************************************************************/
        var geocoder, searchService = null;
        var map = null;
        var markersArray = [];
        var latLng = null;
        var init = function () {
 
            var center = new qq.maps.LatLng(39.916527, 116.397128);            
            var city = document.getElementById("city");
            map = new qq.maps.Map(document.getElementById('container'), {
                center: center,
                zoom: 28,
            });
            
            //移除绑定事件
            window.removeEvent = function () {
                qq.maps.event.removeListener(listener);
            };
            //地址和经纬度之间进行转换服务
            geocoder = new qq.maps.Geocoder();
            if ($("#txtlatitude").val() != "" && $("#txtlongitude").val() != "") {
                center = new qq.maps.LatLng($("#txtlatitude").val(), $("#txtlongitude").val());
                map.setCenter(center);
                var marker = new qq.maps.Marker({
                    map: map,
                    position: center
                });
                qq.maps.event.addListener(map, 'click', function (event) {
                    marker.setMap(null);
                });
            }
            else {
                codeAddress();
            }
            //点击显示坐标 ****************************************************************************
            var listener = qq.maps.event.addListener(map, 'click', function (event) {
 
                //alert('您点击的位置为: [' + event.latLng.getLat().toFixed(5) + ', ' + event.latLng.getLng().toFixed(5) + ']');
                var marker = new qq.maps.Marker({
                    position: event.latLng,
                    map: map
                });
                qq.maps.event.addListener(map, 'click', function (event) {
                    marker.setMap(null);
                });
                //获取输入框的经纬度
                var lat = event.latLng.getLat().toFixed(5);
                var lng = event.latLng.getLng().toFixed(5);
                latLng = new qq.maps.LatLng(lat, lng);
                $("#txtlatitude").val(lat);
                $("#txtlongitude").val(lng);
               
            });
            
 
            //设置Poi检索服务,用于本地检索、周边检索
            searchService = new qq.maps.SearchService({
                pageCapacity: 5,
                panel: document.getElementById('infoDiv'),
                map: map,
            });
        }
        //搜索方法
        function getResult() {
            //设置searchRequest
            var poiText = document.getElementById("poiText").value;
            var regionText = document.getElementById("regionText").value;
            searchService.setLocation(regionText);
            searchService.search(poiText);
        }
 
        //根据地址定位
        function codeAddress() {
            var address = "泉州软件园";
            geocoder.getLocation(address);
            //设置服务请求成功的回调函数
            geocoder.setComplete(function (result) {
                map.setCenter(result.detail.location);
               
        }
 
    </script>


手机端运行导航

HTML部分

<body onload="showMap()">
    <div class="mapBox">
        <div id="mapBox">
            <p id="mapInfo"></p>
        </div>
    </div>
    <div>
        <div class="mapInfo">
            <ul id="J_List"></ul>
        </div>
 
    </div>
</body>
</html>


CSS部分(界面有点丑)


    <style>
        body {
            height: 100vh;
            background: #fff;
            color: #3D3D3D;
        }
 
            body > div {
                width: 100% !important;
            }
 
        .mapBox {
            width: 100%;
            font-size: 14px;
            height: 50%;
        }
 
            .mapBox > #mapInfo {
                padding: 20px;
            }
 
            .mapBox > div {
                width: 100%;
                height: 100%;
            }
 
            .mapBox > p {
                padding: 20px;
            }
 
        .mapInfo > p.center {
            text-align: center;
        }
 
        .mapInfo > p {
            line-height: 0.533333rem;
        }
 
    </style>


JS部分


    <script src="@(Request.Url.Scheme)://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
    <script charset="utf-8" src="http://map.qq.com/api/js?v=2.exp"></script>
    <script src="http://g.tbcdn.cn/mtb/lib-flexible/0.3.4/??flexible_css.js,flexible.js"></script>
    <script>
        function showMap() {
            var map = new qq.maps.Map(document.getElementById("mapBox"), {    //地图部分初始化
                zoom: 24,               //设置地图缩放级别
                center: new qq.maps.LatLng(24.968320, 118.571190),     //设置中心点
                zoomControl: false,    //不启用缩放控件
                mapTypeControlOptions: {  //设置控件的地图类型为普通街道地图
                    mapTypeIds: qq.maps.MapTypeId.ROADMAP
                }
            });
 
            var info = new qq.maps.InfoWindow({ map: map });      //添加提示窗
            $.post("/WX/GetSiteCountList", function (data) {
                var result = $.parseJSON(data);
                //result中数据 用于显示标记、和标记点击时的提示信息
                if (result.total > 0) {
                    for (var i = 0; i < result.rows.length; i++) {
                        var row = result.rows[i];
                        if (row.IsShowGIS) {
                            var marker = new qq.maps.Marker({
                                position: new qq.maps.LatLng(row.latitude, row.longitude),
                                map: map
                            });
                            //创建标记
                            //***将必要的数据存入每一个对应的marker对象
                            marker.id = row.ID;
                            marker.name = row.SiteName;
                            marker.locate = row.Address;
                            marker.latitude = row.latitude;
                            marker.longitude = row.longitude;                            
                            document.getElementById("J_List").innerHTML += "<li latitude=" + row.latitude + " longitude=" + row.longitude + " name=\"" + row.SiteName + "\" locate=\"" + row.Address + "\"  sid=" + i + " id=" + row.ID + " ><div><p>" + row.SiteName + "</p><p>" + "<img style=\"width:30px\" src=\"/Content/WeiXinUseJS/Image/wz.png\"/>" + row.Address + "</p></div><a href=\"javascript:void(0);\" syle=\"float:right\" onclick=\"bindShop('" + row.ID + "','" + row.SiteName + "','" + row.Address + "'," + Number(row.latitude) + "," + Number(row.longitude) + ")\"><img style=\"width:25px\" src=\"/Content/WeiXinUseJS/Image/qzl.png\"/>去这里</a></li>\n\t";
                        }
                        
                    };
                    
                }
            });
        }
        wx.config({
            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
            appId: '@Model.AppId', // 必填,公众号的唯一标识
            timestamp: '@Model.Timestamp', // 必填,生成签名的时间戳
            nonceStr: '@Model.NonceStr', // 必填,生成签名的随机串
            signature: '@Model.Signature',// 必填,签名
            jsApiList: [
             'getLocation',
                    'openLocation'
            ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2。详见:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
        });
        wx.error(function (res) {
            // console.log(res);
            alert('验证失败');
        });
        function bindShop(id, name, address, latitude, longitude) {    //地图标注提示窗上按钮 点击后执行的函数
 
            var zb1 = latitude;
            var zb2 = longitude;
            var dz = address;
            
            ////使用微信内置地图查看位置接口
            wx.openLocation({
                latitude: latitude, // 纬度,浮点数,范围为90 ~ -90   '24.948280'
                longitude: longitude, // 经度,浮点数,范围为180 ~ -180。'118.603630'
                name: name, // 位置名
                address: address, // 地址详情说明
                scale: 10, // 地图缩放级别,整形值,范围从1~28。默认为最大
 
            });
        }
    </script>


鉴于公司项目  就不放效果图出来了  代码是真的  效果也是真的。


欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739

评价
真正的顺其自然,其实是竭尽所能之后的不强求,而非两手一摊的不作为
排名
6
文章
6
粉丝
16
评论
8
{{item.articleTitle}}
{{item.blogName}} : {{item.content}}
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2024TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术