1
头图

Recently, I am working on a functional module similar to Alipay word-of-mouth merchants. One of the functions is to calculate the distance between the user and the merchant, as shown below:
图片
Alipay word of mouth merchant page screenshot

Thought analysis

1. The merchant selects the store address and stores the coordinate latitude and longitude in the database;
2. The mobile terminal locates the latitude and longitude of the current user coordinates;
3. Take the latitude and longitude of the merchant from the database and calculate the latitude and longitude of the current user;
4. The calculated distance is displayed on the user side;

tools used

1. HTML5 Geolocation API;
2. Baidu Map API;

Baidu map API usage

1. Register a developer account on the Baidu Map Open Platform;
2. Log in to the developer account and create an application in the console, as shown below:
图片
Note: For mobile web terminal, remember to select browser terminal for application type

Code

1. Create a seller.html file to provide the latitude and longitude of the address selected by the merchant;
Note : ak="your key" in the code, remember to replace it with the AK key of the application created in the console

 <!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>

The running effect of seller.html is as follows:
图片

2. Create a user.html file to locate the latitude and longitude of the user's coordinates and calculate the distance from the merchant;
Note 1 : Since HTML5 geolocation is only valid on the mobile terminal, user.html needs to be run on the mobile terminal (the file can be sent directly to the mobile phone and opened and run on the mobile phone)
Note 2 : ak="your key" in the code, remember to replace it with the AK key of the application created in the console

 <!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 running renderings:
1. Run for the first time and ask whether to share location information
图片
2. Click to confirm the shared location information, and the distance between the user and the business will pop up
图片

Summarize

1. Baidu Maps API can also locate the user's coordinate latitude and longitude, but there will be an offset, which is very different from the actual location. Therefore, you can use HTML5 to geolocate the user's original coordinates, and then convert the original coordinates into Baidu's positioning coordinates.
2. Since HTML5 geolocation is only valid on the mobile terminal, the use of HTML5 geolocation needs to run on the mobile terminal

at last

I think the article is good, give me a like wow, pay attention!
For technical exchanges, you can pay attention to the WeChat public account [GitWeb], and add my friends to discuss the WeChat communication group: add friends (remarks) to invite you to join the group, learn together and make progress together

图片


Winn
2.7k 声望2.9k 粉丝

国内头部医美企业全栈开发者