Home Web Front-end H5 Tutorial Detailed explanation of Html5 Geolocation sample code sharing for obtaining geographical location information

Detailed explanation of Html5 Geolocation sample code sharing for obtaining geographical location information

Mar 18, 2017 pm 03:59 PM

This article mainly introduces Html5 Geolocation to obtain geographical location information examples, which has certain reference value. Interested students can learn about it.

Html5 provides API for geographical location information, which can obtain the user's current location through the browser. Based on this feature, location-based service applications can be developed. Before obtaining geographical location information, the browser will first ask the user if they are willing to share their location information, and it can only be used after the user agrees.

Html5 obtains geographical location information through the Geolocation API, using its getCurrentPosition method. There are three parameters in this method, which are the callback function executed when the geographical location information is successfully obtained. The callback function and optional property configuration items executed in case of failure.

The following Demo demonstrates obtaining geographical location information through Geolocation and displaying the current location on Baidu Map (by calling Baidu Map API). The experimental results showed that the location was located at the entrance of Huandong 4th Road in the university town. The deviation from my location (HuaGong student dormitory) is still a bit large, reaching about 200-300 meters.

Detailed explanation of Html5 Geolocation sample code sharing for obtaining geographical location information

The code is as follows (convertor.js is the coordinate conversion file provided by Baidu Maps):

<!DOCTYPE html>
<html>
    <head>
        <title>H5地理位置Demo</title>
        <script src="http://api.map.baidu.com/api?v=1.3" type="text/javascript">
        </script>
        <script type="text/javascript" src="convertor.js">
        </script>
    </head>
    <body>
        <p id="map" style="width:600px; height:400px">
        </p>
    </body>
    <script type="text/javascript">
        if (window.navigator.geolocation) {
            var options = {
                enableHighAccuracy: true,
            };
            window.navigator.geolocation.getCurrentPosition(handleSuccess, handleError, options);
        } else {
            alert("浏览器不支持html5来获取地理位置信息");
        }
        
        function handleSuccess(position){
            // 获取到当前位置经纬度  本例中是chrome浏览器取到的是google地图中的经纬度
            var lng = position.coords.longitude;
            var lat = position.coords.latitude;
            // 调用百度地图api显示
            var map = new BMap.Map("map");
            var ggPoint = new BMap.Point(lng, lat);
            // 将google地图中的经纬度转化为百度地图的经纬度
            BMap.Convertor.translate(ggPoint, 2, function(point){
                var marker = new BMap.Marker(point);
                map.addOverlay(marker);
                map.centerAndZoom(point, 15);
            });
        }
        
        function handleError(error){
        
        }
    </script>
</html>
Copy after login

convertor.js file:

(function() { // 闭包
    function load_script(xyUrl, callback) {
        var head = document.getElementsByTagName(&#39;head&#39;)[0];
        var script = document.createElement(&#39;script&#39;);
        script.type = &#39;text/javascript&#39;;
        script.src = xyUrl;
        // 借鉴了jQuery的script跨域方法
        script.onload = script.onreadystatechange = function() {
            if ((!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) {
                callback && callback();
                // Handle memory leak in IE
                script.onload = script.onreadystatechange = null;
                if (head && script.parentNode) {
                    head.removeChild(script);
                }
            }
        };
        // Use insertBefore instead of appendChild to circumvent an IE6 bug.
        head.insertBefore(script, head.firstChild);
    }
    function translate(point, type, callback) {
        var callbackName = &#39;cbk_&#39; + Math.round(Math.random() * 10000); // 随机函数名
        var xyUrl = "http://api.map.baidu.com/ag/coord/convert?from=" + type
                + "&to=4&x=" + point.lng + "&y=" + point.lat
                + "&callback=BMap.Convertor." + callbackName;
        // 动态创建script标签
        load_script(xyUrl);
        BMap.Convertor[callbackName] = function(xyResult) {
            delete BMap.Convertor[callbackName]; // 调用完需要删除改函数
            var point = new BMap.Point(xyResult.x, xyResult.y);
            callback && callback(point);
        }
    }

    window.BMap = window.BMap || {};
    BMap.Convertor = {};
    BMap.Convertor.translate = translate;
})();
Copy after login

The above is the detailed content of Detailed explanation of Html5 Geolocation sample code sharing for obtaining geographical location information. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles