search
HomeWeb Front-endH5 TutorialUse Geolocation to obtain geographical location information

This time I will bring you the use of Geolocation to obtain geographical location information, and what are the precautions for using Geolocation to obtain geographical location information. The following is a practical case, let's take a look.

Html5 provides an API for geographical location information to 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 executed when the geographical location information is successfully obtainedCallback function, the callback function and optional attribute configuration items executed when failure occurs.

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 show that the location is 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.

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

nbsp;html>

    
        <title>H5地理位置Demo</title>
        <script>
        </script>
        <script>
        </script>
    
    
        <p>
        </p>
    
    <script>
        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>

convertor.js file:

(function() { // 闭包
    function load_script(xyUrl, callback) {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        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 = 'cbk_' + 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;
})();

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

Detailed explanation of the use of paging query

Detailed explanation of the use of foldable panels in JS

The above is the detailed content of Use Geolocation to obtain geographical location information. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
cdn.bin是一个什么样的文件cdn.bin是一个什么样的文件Feb 19, 2024 pm 02:53 PM

cdn.bin是一种文件格式,通常与内容分发网络(CDN)有关。CDN是一种网络架构,旨在提高用户对Web内容的访问速度和性能。它使用位于全球各地的服务器节点来缓存和分发网站的静态内容,以减少用户从源服务器获取内容的时间和距离。cdn.bin文件是CDN服务器上存储的二进制文件。它可以包含各种静态资源,例如HTML文件、JavaScript文件、样式表、图片

抖音ip属地怎么关闭抖音ip属地怎么关闭Feb 07, 2024 pm 01:20 PM

抖音是一款备受欢迎的短视频社交平台,用户量已经突破了数十亿。在抖音上,用户不仅可以分享自己的生活点滴,还可以观看他人的短视频。并且在互动评论中还能展示自己的所在的IP省份,不过很多用户不希望暴露自己的位置信息。那么抖音ip属地怎么关闭呢?还不清楚的小伙伴也别着急,接下来小编为大家带来了关闭ip属地的具体步骤,希望能够帮助到大家。抖音ip属地怎么关闭1、首先打开设置,在设置里点击“安全与隐私”。2、点击“权限管理”。3、选择“抖音”应用。4、点击“定位”。5、将权限改为“禁止”状态即可。

win10教育版激活错误 0×c004f074怎么解决win10教育版激活错误 0×c004f074怎么解决Feb 07, 2024 pm 10:54 PM

用户在启用他们的电脑系统时,遇到了激活失败且显示错误代码0xc004f074的情况,本文将详细阐述Win10激活失败且获取到错误代码0xc004f074的解决方法。win10教育版激活错误0×c004f074怎么解决1、首先按下Win+R键,调出运行对话框,随后输入services.msc并敲击回车键,以此来打开标准服务对话框。2、用户需找到名称为"SoftwareProtection"的服务,确认该服务状态是否处于启动状态。3、然后将启动类型调整至“自动”选项,接着单击“启动”功能按钮,最后点

使用PHP和XML来处理和显示地理位置和地图数据使用PHP和XML来处理和显示地理位置和地图数据Aug 01, 2023 am 08:37 AM

使用PHP和XML来处理和显示地理位置和地图数据概述:在开发Web应用程序时,处理和显示地理位置和地图数据是一个常见的需求。PHP是一种流行的服务器端编程语言,可以与XML格式的数据进行交互。本文将介绍如何使用PHP和XML来处理和显示地理位置和地图数据,并提供一些示例代码。1.准备工作:在开始之前,需要确保服务器上已安装了PHP和相关的扩展,如Simple

Ubuntu如何配置软件镜像源?Ubuntu如何配置软件镜像源?Feb 19, 2024 am 11:15 AM

配置软件镜像源在Ubuntu中是提高下载速度和获取软件更新的有效方法。以下是配置的步骤:打开终端:在Ubuntu桌面上,按下Ctrl+Alt+T组合键可以打开终端。备份原有的软件源配置文件(可选):如果你想保留原有的软件源配置备份,可以执行以下命令备份/etc/apt/sources.list文件:sudocp/etc/apt/sources.list/etc/apt/sources.list.backup编辑软件源配置文件:使用文本编辑器(如nano或vi)打开软件源配置文件:sudonano

UniApp实现地理位置选择与地址搜索的实现指南UniApp实现地理位置选择与地址搜索的实现指南Jul 04, 2023 pm 12:40 PM

UniApp是一个基于Vue.js开发的跨平台开发框架,它的特点是一次编写,多端运行,可以同时开发iOS、Android、H5等多个平台的应用。在许多地理位置相关的应用中,地理位置选择和地址搜索是非常重要的功能。本文将带领大家通过UniApp实现地理位置选择与地址搜索的实现指南,并提供相关的代码示例。地理位置选择地理位置选择是指用户通过选择地图上

抹茶交易所是哪个国家的?抹茶交易所总部在哪里?抹茶交易所是哪个国家的?抹茶交易所总部在哪里?Jan 31, 2024 am 08:27 AM

抹茶交易所是一家全球领先的加密货币交易平台,被誉为是“新一代全球数字资产交易平台”的代表。它的交易市场包括比特币、以太坊、莱特币等数字货币,其交易所的总部在哪里?它是哪个国家的?抹茶交易所总部在哪里?抹茶交易所总部位于法属波利尼西亚的帕皮提市,是一家全球性的加密货币交易平台。帕皮提市是法属波利尼西亚的一个城市,以其壮丽的自然风光和迷人的海滩而闻名。抹茶交易所在该地的设立,为公司在加密货币市场上的竞争力和发展前景带来了巨大的提升。帕皮提市的美丽景色以及法属波利尼西亚政府的支持,使得抹

ccmac版本语言包?ccmac版本语言包?Feb 19, 2024 am 10:21 AM

导读:很多朋友问到关于ccmac版本语言包的相关问题,本文本站就来为大家做个详细解答,供大家参考,希望对大家有所帮助!一起来看看吧!苹果cctalk缓存的课如何导入本地在电脑网页端登录cctalk的官网后,打开所需下载的课程页面,在软件安装完成的情况下,你会看到右下方出现两个下载图标。点击其中一个图标,即可跳转至下载页面。在点击后,软件将自动获取该视频的m3u8下载地址。可以。首先打开ipad并登录自己的账号。其次打开ipad上cctalk缓存点击复制。最后将ipad上cctalk缓存能导出即可

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft