HTML5 geopositioning + Map API: calculate the distance to the business user

Recently doing a similar reputation Alipay business function module, which has a function that calculates the distance between the user and the merchant, as shown below:

14469463-d3dcf0aa2b7640c8
image

Alipay word of mouth business page screenshot

Ideas analysis


1, select the store business address, latitude and longitude coordinates stored in the database;

2, the mobile terminal positioning latitude and longitude coordinates of the current user;

3, the latitude and longitude merchant taken out from the calculated latitude and longitude of the current user database;

4, the calculated distance is displayed on the user terminal;

Used tool


1, HTML5 geopositioning API;

2, Baidu Maps API;

Baidu Maps API to use


1, registered developer account in Baidu map open platform;

2, Log developer account, create an application, as shown in the console:

14469463-9dc5d1c60ade9ba9
image

Note : mobile web end, then, the type of application remember to choose the browser

Code


1, create seller.html file, select the business to provide latitude and longitude coordinates of an address;

Note : The code in ak = "your key", remember to create a console application into key AK

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
        body, html{
            width: 100%;
            height: 100%;
            margin:0;
            font-family:"微软雅黑";
            font-size:14px;
        }
        #l-map{
            height:300px;
            width:100%;
        }
        #r-result{
            width:100%;
        }
    </style>
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的密钥"></script>
    <title>商家选取店铺地址</title>
</head>
<body>
    <div style="display: flex;">
        <div style="width: 50%;height: 700px" id="l-map"></div>
        <div style="width: 50%">
            <div id="r-result">请输入:<input type="text" id="suggestId" size="20" value="百度" style="width:150px;" /></div>
            <div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
        </div>
    </div>

</body>
</html>
<script type="text/javascript">
    // 百度地图API功能
    function G(id) {
        return document.getElementById(id);
    }

    var map = new BMap.Map("l-map");
    map.centerAndZoom("北京",12);       // 初始化地图,设置城市和地图级别。

    var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
        {"input" : "suggestId"
        ,"location" : map
    });


    var myValue;
    ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
    var _value = e.item.value;
        myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
        G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;

        setPlace();
    });

    function setPlace(){
        map.clearOverlays();    //清除地图上所有覆盖物
        function myFun(){
            var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
            map.centerAndZoom(pp, 18);
            map.addOverlay(new BMap.Marker(pp));    //添加标注
        }
        var local = new BMap.LocalSearch(map, { //智能搜索
          onSearchComplete: myFun
        });
        local.search(myValue);
    }


    //鼠标单击获取点击的经纬度
    map.addEventListener("click",function(e){
        alert('该点击区域的经纬度为:'+e.point.lng + "," + e.point.lat);//将该经纬度存入数据库中
    });

</script>

seller.html operating results is as follows:

14469463-a72291908a62a75d
image

2, creates a file user.html, latitude and longitude coordinates used to locate the user, and the distance calculation with the merchant;

Note 1 : Due to HTML5 geopositioning take effect only at the end of the movement, and therefore user.html need to run in a mobile terminal (files can be sent directly to your phone, open the run on the phone)

Note 2 : code ak = "your key", remember to create a console application into key AK

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=您的密钥"></script>
    <title>计算用户到商家的距离</title>
</head>
<body>

</body>
</html>
<script type="text/javascript">

    //使用HTML5地理定位
    function getLocation(){

        //检测浏览器是否支持地理定位
      if (navigator.geolocation){
            navigator.geolocation.getCurrentPosition(showPosition,showError);
            //如果getCurrentPosition()运行成功,则向参数showPosition中规定的函数返回一个coordinates对象
            //getCurrentPosition()方法的第二个参数showError用于处理错误。它规定当获取用户位置失败时运行的函数
        }else{
            alert("该设备浏览器不支持地理定位");
        }

      }


    function showPosition(position){

        var Longitude=position.coords.longitude;//HTML5定位获取的经度
        var Latitude=position.coords.latitude;//HTML5定位获取的纬度

        //将HTML5定位获取的经纬度,通过百度地图API转换成适应于百度定位的经纬度
        var ggPoint = new BMap.Point(Longitude,Latitude);

        //坐标转换完之后的回调函数
        translateCallback = function (data){
          if(data.status === 0) {
            var map = new BMap.Map();
            console.log(data.points[0]);//转换后新的用户经纬度
            var pointA = new BMap.Point(data.points[0].lng,data.points[0].lat);//用户的经纬度
            var pointB = new BMap.Point(商家经度,商家纬度);//从数据库中取出商家的经纬度
            alert('您到商家的距离是:'+(map.getDistance(pointA,pointB)).toFixed(2)+' 米。');  //获取两点距离,保留小数点后两位
          }
        }

        var convertor = new BMap.Convertor();
        var pointArr = [];
        pointArr.push(ggPoint);
        convertor.translate(pointArr, 1, 5, translateCallback)

    }

    function showError(error){
      switch(error.code) {
        case error.PERMISSION_DENIED:
          alert("用户不允许地理定位")
          break;
        case error.POSITION_UNAVAILABLE:
          alert("无法获取当前位置")
          break;
        case error.TIMEOUT:
          alert("操作超时")
          break;
        case error.UNKNOWN_ERROR:
          alert("未知错误")
          break;
        }
      }

    getLocation();

</script>

user.html run effect diagram:

1, the initial run, asking whether to share location information

14469463-d04814c28fae3abe
image

2. Click OK to share location information from the user and the business of pop

14469463-bf15cef56504ea9f
image

to sum up


1, may be positioned Baidu Maps API latitude and longitude coordinates of the user, but there will be an offset from the actual position differ greatly, so the original coordinates HTML5 user may use the geographic positioning, then converted into the original coordinate location coordinates of Baidu

2, since the commencement HTML5 geopositioning only the mobile terminal, so using HTML5 geopositioning needs to run at the mobile terminal

Guess you like

Origin blog.csdn.net/weixin_34122810/article/details/90826930