preface

Map application is very extensive. At present, map services all provide interfaces such as map operation, annotation, location search, travel planning, address resolution and street view, with very rich functions. In the actual development process, each has its advantages and disadvantages. This time based on demand, using Tencent location service as a public toilet location marking H5 page development.

Version: JavaScript API 2.0.

The project requirements

1. Project requirements

Based on Tencent location service, wechat can scan the TWO-DIMENSIONAL code and display the public toilet distribution map of a certain county in the wechat browser. The public toilet distribution map can be sorted according to the distance between the user’s current location and each toilet. Click the marked point to jump to the Tencent map for navigation.

2. Demand decomposition

Based on the above requirements, the used Tencent location service interface is decomposed as follows:

Tencent map loading; Automatic positioning; POINTS mark maker; Calculate the distance between annotation points; Navigation jump link API interface; Street and satellite map switching control; Zoom control;Copy the code

The development of actual combat

1. Introduce feature libraries and accessory libraries

    <script charset="utf-8"
            src="https://map.qq.com/api/js?v=2.exp&libraries=drawing,geometry,autocomplete,convertor&key={$appkey}"></script>
    <script type="text/javascript"
            src="https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>
Copy the code

2. Build Tencent map containers

<! <div id="location" onclick="getLocation();" ><img src="{$url}{$STATIC}images/location.png" alt=""></div> <div id="txmap"></div>Copy the code

3. Call the front-end positioning component

Map and geolocation are set as global functions in script scripts because the project calls maps and locations many times.

var map; // global function var geolocation = new q.maps. geolocation (appkey, "{$referer}"); var options = {timeout: 8000}; function getLocation() { geolocation.getLocation(showPosition, showErr, options); }Copy the code

GetLocation (sucCallback, errCallback, [options: {timeout: number, failTipFlag: Boolean}]) method

Obtain the current geographical location, call once that is to reposition once, positioning data is more accurate. SucCallback Specifies the success callback function. ErrCallback is a callback function for locating failure. If this parameter is not specified, set this parameter to null. Options indicates the location option. You can use the timeout parameter to set the location timeout period. The default value is 10s. FailTipFlag: Whether to prompt users to enable authorization or enable locating when locating fails. (Upcoming support)Copy the code

1) Locate the success callback function

function showPosition(position) {
}
Copy the code

Get the position coordinate display map

Map = new q.maps. map (document.getelementByid ("txmap"), {// The center of the map geographical coordinates. center: new qq.maps.LatLng(position.lat, position.lng), zoom: 15 });Copy the code

Defines the current location of the Makerstyle picture

        var imgUrl = "static/rooted/images/icon.png";
        var anchor = new qq.maps.Point(6, 6),
                size = new qq.maps.Size(45, 46),
                origin = new qq.maps.Point(0, 0),
                icon = new qq.maps.MarkerImage(imgUrl, size, origin, anchor);

        var marker2 = new qq.maps.Marker({
            icon: icon,
            map: map,
            position: new qq.maps.LatLng(position.lat, position.lng)
        });
Copy the code

Read the POINTS and mark them on the map

1. Standard JSON data format

For the convenience of display, only the data format is shown here, and the actual application is done by using Ajax.

[{" toilet_id ":" 9 ", "toilet_name" : "wisdom square", "toilet_address" : "xixi road Intelligence center ", "south toilet_url" : "Upload/preview / 2020-11/15784 affe0de0d45c5f33625851527e9. JPG", "toilet_lon" : "115.965248", "toilet_lat" : "35.597050"}, {"toilet_id": "14", "toilet_name": "Tong Ta Public toilet ", "toilet_address":" Tong Ta Plaza, North Dongmen Street ", "toilet_url": "Upload/preview / 2020-11/8 e5bda8c5b12f87ebad80c247d8f2b26. JPG", "toilet_lon" : "115.946365", "toilet_lat" : "35.602218"}]Copy the code

2. Map and calculate distances

// map annotation; getTxMap(newData, latlngs); // The distance between two points; getDistance(newData, latlngs);Copy the code

Latitude and longitude annotation encapsulation function

function getTxMap(newData, latlngs) { for (var i = 0; i < newData.length; i++) { (function (n) { var marker = new qq.maps.Marker({ position: latlngs[n], map: map }); Qq. Maps. Event. AddListener (marker, 'click', function () {var popHtml = '< div class = "pop" > here: < a href = "https://apis.map.qq.com/uri/v1/routeplan?type=walk&from= start position & fromcoord = '+ position. Lat +', '+ position. LNG + '&to=' + newData[n].toilet_name + '&tocoord=' + newData[n].toilet_lat + ',' + newData[n].toilet_lon + '&policy=0&referer={$referer}">' + newData[n].toilet_name + '</a></div>'; infoWin.open(); infoWin.setContent(popHtml); infoWin.setPosition(latlngs[n]); }); })(i); }}Copy the code

Compute the distance function encapsulation between two points

function getDistance(newData, latlngs) { var newArr = []; var start = new qq.maps.LatLng(position.lat, position.lng); for (var i = 0; i < latlngs.length; i++) { var end = latlngs[i]; var distance = Math.round(qq.maps.geometry.spherical.computeDistanceBetween(start, end) * 10) / 10; // Concatenate new distance array data; newArr.push({ toilet_id: newData[i].toilet_id, toilet_name: newData[i].toilet_name, toilet_address: newData[i].toilet_address, toilet_url: newData[i].toilet_url, toilet_lon: newData[i].toilet_lon, toilet_lat: NewData [I]. Toilet_lat, distance: distance})} function compare(key) { return function (value1, value2) { var val1 = value1[key]; var val2 = value2[key]; return val1 - val2; } } newArr.sort(compare('distance')); console.log(newArr);Copy the code

2. Locate the failure callback function

// The location fails, and the page is automatically redirected. Function showErr() {//alert(" error! ); window.location.href = "? m=Index&a=error" }Copy the code

Coordinates longitude and latitude pick up

1. Tencent coordinate picker

In the process of project development, it is necessary to pick up the longitude and latitude of coordinates by ourselves to meet the test and demonstration use of initial data. Tencent will generally use the coordinates provided by the picker. Link: lbs.qq.com/tool/getpoi…

Support precise/fuzzy address query; Support POI point coordinates display; Coordinate mouse follow display;Copy the code

If you have to pick up some problems, the map pick up box is too small, want to pick up coordinates arbitrarily, to zoom or drag many times, heart tired.

2. WebService API address resolution (address to coordinate)

Picking up hundreds of addresses one by one after a project is tested is not the behavior of a qualified developer. In this case, you need to use the API interface of address resolution and reverse resolution, that is, in the process of data import to the database, the address is automatically converted into latitude and longitude coordinates in batches, to meet the call of the front end.

In this example, Tencent Location service WebService API is used, and PHP is used as the back-end language to briefly present the process.

1. Encapsulate WebService API interface functions

Official example, if you use getJSON function directly in the front end, there will be “same origin policy” blocked, so you need to crawl the back end, “curve save the country”.

//GET request example, Pay attention to the parameter values for URL encoding https://apis.map.qq.com/ws/geocoder/v1/?address= colour and lane road, haidian district of Beijing haidian west street no. 74 & key = OB4BZ - D4W3U PJWW B7VVO - 4-6 TKDJ - WPB77Copy the code
$address = $address; $address = $address; */ function getGeoCoding($address) { $url = "https://apis.map.qq.com/ws/geocoder/v1/?address=" . $address . "&key={$key}"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); return $output; } // Get the address parameter passed by the front end; $address = $_GET["address"]; // Output json data format for the front-end call; die(getGeoCoding($address));Copy the code

2. Front-end calls

// Automatically get latitude and longitude; var getAddress = function transAddress() { var address = $("#address").val(); getPoints(address); } // front-end page output; function getPoints(address) { $.getJSON("points.php", {address: address}, function (res) { if (res.status == 0) { $("#lng").val(res.result.location.lng); $("#lat").val(res.result.location.lat); } else { $("#message").html(res.message); }}); }Copy the code

3. Effect demonstration

When importing address data, it must be the street number of the province and the city, the more detailed the address, the higher the accuracy, otherwise it will not be resolved, remember!

Matters needing attention

1, Script tag load API service

<script charset="utf-8" src="https://map.qq.com/api/js?v=2.exp&key=YOUR_KEY"></script>
Copy the code

This is introduced into the front-end file by default during development. The test environment is consistent with the build environment, or the replacement environment is always, there will be no problem. However, if the HTTP protocol and HTTPS protocol are inconsistent, an error message is displayed when importing files.

Recommended loading method: SRC does not use the protocol name, let it match automatically. Such as:

<script charset="utf-8" src="//map.qq.com/api/js?v=2.exp&key=YOUR_KEY"></script>
Copy the code

2. Introduction of additional libraries

The quickest way to learn a new project is to learn to use official documentation, because these documents are the foundation of the foundation. But official documents are sometimes too official, and some details cannot be clearly shown.

Official documentation can’t solve the problem, will “in the face of CSDN programming”, each developer is different, the problem of development experience is different, in CSDN record more is to avoid their next time “into the pit,” reminds, unable to complete the project details description is clear, that is for beginners to see clearly solved, why you can’t.

Here involves the introduction of Tencent map additional library.

    <script charset="utf-8"
            src="://map.qq.com/api/js?v=2.exp&libraries=drawing,geometry,autocomplete,convertor&key={$appkey}"></script>
Copy the code

In this project, it is necessary to calculate the longitude and latitude of automatic positioning and the distance between each toilet, which requires the use of geometry operation library. Forced CSDN on the premise of not understanding the official documents, I found that the development syntax was clearly correct, but the distance was not calculated, and the corresponding additional library was not introduced.

3. Automatically locate component libraries

   <script type="text/javascript"
            src="//3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js"></script>
Copy the code

To use the automatic positioning function, the additional geolocation.min.js library must be introduced. Needless to say.

4, latitude and longitude position

If it is the first time to develop the map using Tencent map, the possibility of this mistake is relatively low. If you have baidu and Autonavi map development experience, do not take it for granted. In this problem wasted half an hour only to find that Tencent’s latitude and longitude and Baidu, Autonavi’s problems are interchangeable.

Tenge latitude and longitude

The new qq. Maps. LatLng (39.914850, 116.403765); // Construct object is (latitude, longitude)Copy the code

Baidu latitude and longitude

Map. CenterAndZoom (new BMap. Point (116.4035, 39.915), 8). // Build the object with (latitude, longitude)Copy the code

Gauderian latitude and longitude

Position: new amap.lnglat (116.39, 39.9),// Construct the point object is (longitude, latitude)Copy the code

When using the coordinate picker, it is necessary to select the corresponding tools, navigation and other coordinates involved must be careful.

5. Tencent, Baidu and Autonavi development comparison

For the use of maps of different manufacturers, there are generally “preconceived” stereotypes, but also objective requirements for party A reasons.

Compare the item Tencent map Baidu map Scott map
function Annotation, information box, covering, calculation of distance, track, navigation and other common functions Like the previous Like the previous
coordinates Mars coordinates BD – 09 coordinates Mars coordinates
Coordinate structure (39.914850, 116.403765) (116.4035, 39.915) (116.39, 39.9)
Grammatical structure With gold Baidu’s own syntax With tencent
Development of the document Relatively concentrated Baidu map development platform has been upgraded to version 3.0, more documents, more class libraries Relatively concentrated
extension Data visualization API services Like the previous Like the previous

conclusion

Version used this time: JavaScript API 2.0 version, currently we provide JavaScript API GL version with more cool and complete functions, you can try to access and use.

Author: Missing engraving sometimes

Link: lockdatav.blog.csdn.net/article/det…

Source: CSDN

Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.