preface

Map is widely used. At present, map services provide map operation, annotation, location search, travel planning, address resolution, street view and other interfaces, with very rich functions. In the actual development process, each has its advantages and disadvantages. Based on the demand, Tencent location service is used to develop an H5 page for the location marking of public toilets.

Version used this time: JavaScript API 2.0 version.

The project requirements

1. Project requirements

Based on Tencent location service, after WeChat scanning QR code, display the distribution map of public toilets in a county in the WeChat browser, sort according to the user’s current location and the distance between each toilet, and click the mark point to jump to Tanxin map for navigation.

2. Demand decomposition

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

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

The development of actual combat

1. Introduce function library and attachment library

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

2. Build Tencent map container

<! --> <div id="location" onclick="getLocation();" >! []({$url}{$STATIC}images/location.png)</div> <div id="txmap"></div>

3. Call the front-end positioning component

Because the project calls the map and location multiple times, both map and geolocation are set as global functions in the script script for this purpose.

var map; Var Geolocation = new QQ.Maps.Geolocation(appKey, "{$referer}"); var options = {timeout: 8000}; function getLocation() { geolocation.getLocation(showPosition, showErr, options); }

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

Get the current geographic location, call once is a relocation, positioning data is more accurate. SucCallback is a callback function successfully located, required; ErrCallback is a callback function that failed to locate. If not, set it to null. Options = timeout; options = timeout; timeout = 10s; FailtipFlag: Whether to prompt the user to open authorization or to turn on the location switch when the location fails. (forthcoming support)

1) Locate the successful callback function

function showPosition(position) {
}

Get the position coordinates to display the map

Map = new QQ.maps. map (document.getElementById(" txMap "), {// The center geographic coordinates of the map. center: new qq.maps.LatLng(position.lat, position.lng), zoom: 15 });

Defines the current position of the Maker style image

        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)
        });

Read the POINTS and mark them on the map

1. Standard JSON data format

For the convenience of presentation, only the data format is shown here, and the actual application can be done by using Ajax to get the data.

[{" 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": "Tangta public toilet ", "toilet_address":" Tangta plaza ", "toilet_url": "35.597050"}, {"toilet_url": "35.597050"}, {"toilet_name": "Tangta public toilet ", "toilet_address":" Tangta plaza ", "toilet_url": "35.597050"}, {"toilet_url": "Upload/preview / 2020-11/8 e5bda8c5b12f87ebad80c247d8f2b26. JPG", "toilet_lon" : "115.946365", "toilet_lat" : "35.602218"}]

2. Map marking and distance calculation

// Map annotation; getTxMap(newData, latlngs); // the distance between two points; getDistance(newData, latlngs);

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); }}

Calculates 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; // Stitch 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);

2. Locate failed callback function

// If the location fails, the page will be redirected automatically; Function showErr() {//alert(" Failed to locate!" ); window.location.href = "? m=Index&a=error" }

Coordinate latitude and longitude picking

1. Tencent coordinate picker

In the process of project development, coordinate longitude and latitude need to be picked up by oneself to meet the requirements of initial data testing and demonstration. Generally, coordinate pickers provided by Tencent will be used. Link address: https://lbs.qq.com/tool/getpo…

Support address accurate/fuzzy query; Support POI point coordinate display; Coordinate mouse follow display;

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

2, WebService API address resolution (address to coordinate)

After a project has completed testing, if you encounter hundreds of addresses, one by one, it seems not a qualified developer to do. At this point, we need to use the API interface to address resolution and inverse resolution, that is, in the process of data import into the database, automatically batch address into latitude and longitude coordinates, to meet the call of the front end.

In this example, the WebService API of Tencent location service is used, and the back-end language is PHP, which briefly presents the process.

1. Encapsulate the WebService API interface function

In the official instance, if the GetJSON function is used directly in the front end, the “same origin policy” will be prevented, for this need to be crawled back end after the “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 - WPB77
/* address to coordinate encapsulation function, filename is called points.php *$address, need to convert the address, the more detailed the longitude and latitude precision is higher; */ 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 from the front end; $address = $_GET["address"]; // Output JSON data format for front-end invocation; die(getGeoCoding($address));

2. Front-end call

// Automatic access to 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); }}); }

3. Effect demonstration

When importing address data, it must be the provincial and urban street numbers. 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>

By default, this is introduced into the front-end file during development. There is no problem with the test environment being the same as the build environment, or changing the environment all the time. However, if HTTP and HTTPS do not agree with the environment, the import file will be an error.

Recommended loading: SRC does not use the protocol name and lets it match automatically. Such as:

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

2. Introduction of additional libraries

The quickest way to learn a new project is to learn to use the official documentation, because these documents are the foundation of the basics. But the official documents are sometimes too official, and some details can not 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>

In this project, we need to calculate the longitude and latitude of automatic positioning and the distance between each toilet, so we need to use the Geometry Geometry operation library. In the premise of not understanding the official document, forced CSDN, walking many detour only to find: the development syntax is clearly right, but did not calculate the distance, that is, did not introduce the corresponding additional library.

3. Automatically locate component libraries

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

Needless to say, the geolocation.min.js add-on library must be introduced to use the auto-location function.

4. Latitude and longitude positions

If it is the first time to develop the map on the use of Tencent map, the possibility of this error is relatively low. If you have experience in the development of Baidu and AutoNavi map, do not take it for granted. It took half an hour to find that Tencent’s latitude and longitude were interchangeable with Baidu’s and Gaodi’s.

Tencent Longitude and Latitude

The new qq. Maps. LatLng (39.914850, 116.403765); // The object is constructed by (latitude, longitude).

Baidu longitude and latitude

Map. CenterAndZoom (new BMap. Point (116.4035, 39.915), 8). // The object is constructed by (longitude, latitude).

Gaud longitude and latitude

Position: new amap.lnglat (116.39, 39.9),//

When using the coordinate picker, be sure to choose the corresponding tools, navigation and other coordinates involved in the place must pay attention to.

5. Comparison of the development of Tencent, Baidu and AutoNavi

For the use of maps of different manufacturers, there are generally “preconceived” stereotypes, as well as the objective requirements of Party A.

Compare the item Tencent map Baidu map Scott map
function Annotation, information box, overlay, calculation distance, trajectory, 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 grammar 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, more cool and complete features, you can try to access to use.

Akiko: Oops sometimes

Link: https://lockdatav.blog.csdn.n…

Source: CSDN

The copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please note the source.