Realize browser positioning through Gaode map API [and improve positioning accuracy and obtain detailed location information]

Directory

I. Introduction:

2. Text:

1. Register the developer of Gaode map and create an application

2. Develop with the help of official examples

3. Modify the official development example

4. Obtain detailed location information

5. Detailed code

3. Ending: Xiao Zhou has not been in contact with programming for a long time, and he has just started. If you have better suggestions, please leave a message to share. Please be sure to indicate the source when reprinting. Xiao Zhou is very grateful. Article source: Gaode map API realizes accurate positioning of browsers


1. Preface:

Xiao Zhou also developed by checking the developer documentation and examples given by AutoNavi. At the same time, he is a novice. From the perspective of a novice, he will record my implementation process step by step. The reason for writing this blog post is that in the searched articles, I found that the positioning offset is very large. I haven’t found a solution for a long time. Now that the problem has been solved, I want to give a solution to friends who have the same problem through blog posts. . The positioning of the mobile terminal is very accurate, but there is a big deviation when accessing through the computer. The accuracy in the article is based on mobile positioning

First look at the positioning comparison before and after

This is the very beginning, the positioning offset is very large, just give me the offset, the river outside the school is in the

This is the final effect, the positioning is very accurate:

2. Text:

1. Register Amap developer, create application

The registration process will not be described in detail, it should be possible (remember to perform personal developer certification), here is a talk about creating an application to obtain a key

Step1: First create an application in the console, as shown in the figure Open like this

Enter the name here and select [web end (JS API)]

Here you can set your own domain name to prevent the key from being stolen by others after the key is leaked, and then submit it to get the key and security key.

2. Development with official examples

Here is the official example document Gaode map browser precise positioning example

but! ! Found a problem! ! The positioning on the official platform is very accurate, but when it is deployed to its own server, it is still the same as other blog posts, with a large positioning deviation.

3. Modify the official development example

The latest JS positioning API of AutoNavi is version 2.0, and the example still stays at 1.4.15. Personally, I think this is also the reason for the positioning deviation, although I don’t know the difference between the two versions in detail. Version 2.0 needs to be used with a security key, but 1.4.15 does not. With the attitude of being a dead horse as a living horse doctor (because I have failed too many times before, I have no hope), and deployed the security key to the development document. As a result, the problem was solved, and the positioning was accurate all at once. up.

Here is the official document used by the security key to use the security key of the JS API of Gaode map

Here is my final result of Fu Xiaozhou’s website – Gaode map positioning

followed by the source code

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>Browser Precise Positioning</title>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
    <style>
        html, body, #container{
            height: 100%;
        }
        .info{
            width:26rem;
        }
    </style>
<body>
<div id='container'></div>
<div class="info">
    <h4 id='status'></h4>
    <p id='result'></p>
    <p>Because many browsers no longer support positioning requests in non-secure domains, in order to maintain the success rate and accuracy of positioning, please upgrade your site to HTTPS.</p>
</div>
<script type="text/javascript">
    window._AMapSecurityConfig = {
        securityJsCode:'your security key',
    }
</script>
<script type="text/javascript" src="//i2.wp.com/webapi.amap.com/maps?v=2.0 & amp;key=your Key"></script>
<script type="text/javascript">
    // Map initialization should be done after the map container div has been added to the DOM tree
    var map = new AMap.Map('container', {
        zoom: 12
    })
</script>
<script type="text/javascript">
    var map = new AMap.Map('container', {
        resizeEnable: true
    });
    AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap. Geolocation({
            enableHighAccuracy: true, //Whether to use high-precision positioning, default: true
            timeout: 10000, //Stop positioning after more than 10 seconds, default: 5s
            buttonPosition:'RB', //The docking position of the positioning button
            buttonOffset: new AMap.Pixel(10, 20),//The offset between the positioning button and the set docking position, default: Pixel(10, 20)
            zoomToAccuracy: true, //whether to automatically adjust the view of the map to the positioning point after the positioning is successful

        });
        map. addControl(geolocation);
        geolocation. getCurrentPosition(function(status,result){
            if(status=='complete'){
                onComplete(result)
                console. log(result);
                console.log(position_ie);
            }else{
                onError(result)
            }
        });
    });
    //Parse the positioning result
    function onComplete(data) {
        document.getElementById('status').innerHTML='Positioning succeeded'
        var str = [];
        str.push('positioning result:' + data.position);
        str.push('location category:' + data.location_type);
        if(data.accuracy){
            str.push('Accuracy:' + data.accuracy + 'meter');
        }//If it is an IP precise positioning result, there is no precision information
        str.push('Whether offset:' + (data.isConverted ? 'Yes' : 'No'));
        document.getElementById('result').innerHTML = str.join('<br>');
    }
    //Parse location error message
    function onError(data) {
        document.getElementById('status').innerHTML='Location failed'
        document.getElementById('result').innerHTML = 'Failure reason troubleshooting information:' + data.message;
    }
</script>
</body>
</html>

I use the security key here directly in plain text, and the official has a more secure way to use it.

4. Get detailed location information

Just a positioning does not meet my needs. I need detailed text information of the positioning results. This is just punctuation on the map to mark your location, which does not meet my needs. Then I started to explore again, and then, similar problems appeared again. In the developer documentation, the positioning will return a field [formattedAddress] document description, which contains detailed information about the current location. The official document address: Gaode map API – Positioning reference manual, here is a screenshot

I added some code to the official example as shown in the picture:

It was found that the location can be output normally, but! ! An embarrassing thing happened, I also added the same code on my own, but the prompt message is undefined

I can’t understand it. According to the official document, the GeolocationResult object will return this information. However, when the result information is printed on the console, it is found that a lot of information is missing, and [formattedAddress] is among the missing ones. I was idle in a certain advanced mathematics class, looked through the development documents, and found a document in a corner, which was different from the current document, and the location of the document was also given: Amap Reference Manual

Here is a slight difference from the previous manual. It is also GeolocationResult. Here are some details, as shown in the figure:

It is said here that it returns when the parameter needAddress needs to be passed in. At this time, I made another mistake. I went back to the previous reference manual to find the needAddress. As a result, I couldn’t find it after searching over and over again, as shown in the figure:

I searched all over, but I didn’t say how to use this needAddress. I turned over the development document in an advanced mathematics class when I was free one day, and found that it was in the more detailed development manual, which said how to use needAddress.

It turns out that needAddress: true is to be added to AMap.Geolocation; as shown in the figure

After that, the problem is solved

The desired information also appears in the returned result field, so that the information can be stored and how to use it.

5. Final detailed code

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>Browser Precise Positioning</title>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
    <style>
        html, body, #container{
            height: 100%;
        }
        .info{
            width:26rem;
        }
    </style>
<body>
<div id='container'></div>
<div class="info">
    <h4 id='status'></h4>
    <p id='result'></p>
    <p>Because many browsers no longer support positioning requests in non-secure domains, in order to maintain the success rate and accuracy of positioning, please upgrade your site to HTTPS.</p>
</div>
<script type="text/javascript">
    window._AMapSecurityConfig = {
        securityJsCode:'your security key',
    }
</script>
<script type="text/javascript" src="//i2.wp.com/webapi.amap.com/maps?v=2.0 & amp;key=your Key"></script>
<script type="text/javascript">
    // Map initialization should be done after the map container div has been added to the DOM tree
    var map = new AMap.Map('container', {
        zoom: 12
    })
</script>
<script type="text/javascript">
    var map = new AMap.Map('container', {
        resizeEnable: true
    });
    AMap.plugin('AMap.Geolocation', function() {
        var geolocation = new AMap. Geolocation({
            enableHighAccuracy: true, //Whether to use high-precision positioning, default: true
            timeout: 10000, //Stop positioning after more than 10 seconds, default: 5s
            buttonPosition:'RB', //The docking position of the positioning button
            buttonOffset: new AMap.Pixel(10, 20),//The offset between the positioning button and the set docking position, default: Pixel(10, 20)
            zoomToAccuracy: true, //whether to automatically adjust the view of the map to the positioning point after the positioning is successful
            needAddress: true,

        });
        map. addControl(geolocation);
        geolocation. getCurrentPosition(function(status,result){
            if(status=='complete'){
                onComplete(result)
                console. log(result);
                console.log(position_ie);
            }else{
                onError(result)
            }
        });
    });
    //Parse the positioning result
    function onComplete(data) {
        document.getElementById('status').innerHTML='Positioning succeeded'
        var str = [];
        str.push('positioning result:' + data.position);
        str.push('location category:' + data.location_type);
        /*str.push('Detailed location:' + data.formattedAddress);*/
        var position_de = data. formattedAddress;
        position_ie = data.formattedAddress;
        str.push('position:' + position_de);
        str.push('detailed information:' + data.message);
        if(data.accuracy){
            str.push('Accuracy:' + data.accuracy + 'meter');
        }//If it is an IP precise positioning result, there is no precision information
        str.push('Whether offset:' + (data.isConverted ? 'Yes' : 'No'));
        document.getElementById('result').innerHTML = str.join('<br>');
    }
    //Parse location error message
    function onError(data) {
        document.getElementById('status').innerHTML='Location failed'
        document.getElementById('result').innerHTML = 'Failure reason troubleshooting information:' + data.message;
    }
</script>
</body>
</html>

3. Ending: Xiao Zhou has not been in contact with programming for a long time, and he has just started. If you have better suggestions, please leave a message to share. Please be sure to indicate the source when reprinting. Xiao Zhou is very grateful. Article source: Gaode map API realizes accurate positioning of browser