background

Recently, I have been working on a functional module similar to alipay’s word-of-mouth merchants, in which a function is to calculate the distance between users and merchants, as shown below:

Screenshot of alipay’s word-of-mouth business page



Thought analysis

1. The merchant selects the store address and stores the coordinates, longitude and latitude in the database;

2. The mobile terminal locates the longitude and latitude of the current user coordinates;

3. Take out the longitude and latitude of the merchant from the database and calculate the longitude and latitude of the current user;

4. The calculated distance is displayed on the client;

Tools used

1. HTML5 geolocation API;

2. Baidu Map API;

Baidu Map API use

1. Register a developer account on baidu Map open platform;

2. Log in to the developer account and create the application in the console, as shown below:

Pay attention to: Mobile Web,The application typeRemember to chooseThe browser



Code implementation

1. Create a Seller. HTML file to provide the longitude and latitude of the address selected by the merchant;

Note: ak=” your key “in the code, remember to replace the AK key used to create the application 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, the user - the scalable = no" />
    <style type="text/css">
        body, html{
            width: 100%;
            height: 100%;
            margin:0;
            font-family:Microsoft Yahei;
            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= your key"</script> <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"Please enter :<inputtype="text" id="suggestId" size="20" value="Baidu" 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"> // Baidu Map API functionfunction G(id) {
        return document.getElementById(id);
    }

    var map = new BMap.Map("l-map");
    map.centerAndZoom("Beijing", 12); // Initialize the map, set the city and map level. Var ac = new map. Autocomplete(// create an Autocomplete object {"input" : "suggestId"
        ,"location" : map
    });


    var myValue;
    ac.addEventListener("onconfirm".function(e) {var _value = e.tem.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(); // Clear all overlay on the mapfunction myFun(){ var pp = local.getResults().getPoi(0).point; CenterAndZoom (pp, 18); // Get the first intelligent search result, map.centerandzoom (pp, 18); map.addOverlay(new BMap.Marker(pp)); // Add the annotation} varlocal= new map.localSearch (map, {// onSearchComplete: myFun}); local.search(myValue); } // Click to get the latitude and longitude of the click map.adDeventListener ("click".function(e){
        alert('The latitude and longitude of this click area is:'+e.point.lng + ","+ e.point.lat); }); </script>Copy the code



The running effect of Seller.html is as follows:


2. Create the user.html file to locate the longitude and latitude of the user coordinates and calculate the distance with the merchants;

Note 1: Since HTML5 geolocation only works on mobile devices, user.html needs to be run on mobile devices (you can send the file directly to the phone and open it on the phone).

Note 2: ak=” your key “in the code, remember to replace with the AK key used to create the application 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, the user - the scalable = no" />
    <script type="text/javascript" src="Http://api.map.baidu.com/api?v=2.0&ak= your key"></script> <title> Calculates the distance from the user to the merchant </title> </head> <body> </body> </ HTML >< scripttype="text/javascript"> // Use HTML5 geolocationfunction getLocation(){// Check whether the browser supports geolocationif(navigator.geolocation){ navigator.geolocation.getCurrentPosition(showPosition,showError); // If getCurrentPosition() runs successfully, a coordinates object is returned to the function specified in the argument showPosition // showError, the second argument to the getCurrentPosition() method, is used to handle the error. It specifies the function to run when the user location fails to be retrieved}else{
            alert("This device browser does not support geolocation."); }}functionshowPosition(position){ var Longitude=position.coords.longitude; Var Latitude=position.coords.latitude; Var ggPoint = new bmap.point (Longitude,Latitude); 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 map.point (data.points[0].lng,data.points[0].lat); Var pointB = new map.point (merchant longitude, merchant latitude); // Retrieve the latitude and longitude alert('Your distance to the business is:'+(map.getDistance(pointA,pointB)).toFixed(2)+' 米。'); }} var convertor = new map.convertor (); var pointArr = []; pointArr.push(ggPoint); convertor.translate(pointArr, 1, 5, translateCallback) }function showError(error){
      switch(error.code) {
        case error.PERMISSION_DENIED:
          alert("User does not allow geolocation")
          break;
        case error.POSITION_UNAVAILABLE:
          alert("Cannot get current location")
          break;
        case error.TIMEOUT:
          alert("Operation timed out")
          break;
        case error.UNKNOWN_ERROR:
          alert("Unknown error")
          break;
        }
      }

    getLocation();

</script>Copy the code



User. HTML running effect diagram:

1, the first run, ask whether to share location information


2. Click to confirm the shared location information, and the distance between the user and the merchant pops up


conclusion

1. Baidu Map API can also locate the longitude and latitude of the user’s coordinates, but there will be an offset, which is very different from the actual position. Therefore, HTML5 can be used to geo-locate the user’s original coordinates, and then convert the original coordinates into Baidu’s positioning coordinates

2. Since HTML5 geolocation only works on mobile devices, using HTML5 geolocation requires running on mobile devices


The last

If you think the article is good, please pay attention to it and give me a thumbs-up!

If you have questions about the article or want to technical exchanges, you can pay attention to the public number [GitWeb] and EXPLORE learning with me!

Wechat communication group: add friends in the public number, pull you into the group!