search
HomeWeb Front-endH5 TutorialDetailed explanation of how to use HTML5's Geolocation API

Detailed explanation of how to use HTML5's Geolocation API

Mar 15, 2017 pm 04:21 PM
html5geographical location

Geolocation is one of the important features of HTML5. It provides the function of determining the user's location. With this feature, applications based on location information can be developed. Today this article will introduce it to you. HTML5's GeolocationAPIUsage tutorial.

Today when handheld devices are so common, location information is extremely important for applications. Taxi-hailing applications can use the user's location information Call nearby vehicles, group buying software can recommend nearby theaters and food based on the current location, MAP application can quickly plan the route to the destination based on the user's location, it can be said that location information is indispensable for mobile applications Short.
In order to follow this trend, HTML5 provides us with the Geolocation library, with which we can easily implement the above functions in web applications. So today I will introduce to you the use of this library.

Basic usage
First, we can get a Geolocation instance from the browser's navigator object through the geolocation attribute, As shown in the figure below:
Detailed explanation of how to use HTML5's Geolocation API

We can see in the figure that the Geolocation class has three commonly used methods, they are:

1.getCurrentPosition: Used to obtain the current position information
2.watchPosition: Used to monitor the position information in real time when the position changes
3.clearWatch: Cancel the current position Running monitoring operation
Let’s first take a look at the getCurrentPosition method. The following is its function signature:

navigator.geolocation.getCurrentPosition(success[, error[, options]]);
  1. The first parameter is used to specify a success The second parameter is used to specify an error handling function, and the third parameter is used to provide some optional configuration items to the function. Now let’s call this function:

JavaScript Code复制内容到剪贴板
navigator.geolocation.getCurrentPosition(function(position) {   
    //success handler code goes here   
    console.log(position);   
}, function(error) {   
    //error handler code goes here   
    console.log(error);   
}, {//options   
    enableHighAccuracy: true,   
    timeout: 5000,   
    maximumAge: 0   
});




##Once this code is run, a confirmation box will pop up in the browser window, requesting the user's authorization for location location:


Detailed explanation of how to use HTML5's Geolocation API

If we click

Allow allows the site to perform location positioning. This function starts to obtain location information from the device, triggers a successful callback function, and passes the location information object into the callback function. In the above code, we are controlling Position is printed on the console, and the console information is as follows:
Detailed explanation of how to use HTML5's Geolocation API

You can see that position is actually an instance of a Geoposition object, which includes co

ords and timestamp. An attribute, the latter is a timestamp , recording the time when the location was obtained. Coords contains a lot of location-related information:

accuracy: 位置的精确度范围,单位为米
altitude: 海拔高度,单位为米,如果设备不支持高度感应,则该属性为null
altitudeAccuracy: 海拔精确度范围,单位为米,如果设备不支持高度感应,则该属性为null
speed: 设备移动的速度,单位为米/秒,如果设备不能提供速度信息,该属性为null
heading: 当前移动的方向,以数字表示,单位为角度,以顺时针[0, 360)度表示偏离正北方的角度,0表示正北方向,90度表示正东方向,180度表示正南方向,270表示正西方向;需要注意的是,如果speed为0,则heading会是NaN,如果设备不能提供方向信息,则该属性为null
longitude: 经度信息
latitude: 纬度信息
我们在成功的回调函数中接收到这些信息,可以根据实际的设备和应用场景获取相应的信息,做进一步的操作。
回到刚才的确认框,如果我们点击了Block阻止该站点获取当前的位置信息,代码就会授权失败,相应地,失败的回调函数就会被触发,error错误对象也会被传入回调函数,我们的打印信息如下:
Detailed explanation of how to use HTML5's Geolocation API

可以看到error参数是一个PositionError实例,包含一个错误码code和message,分别表示错误的类型和错误提示消息,其中错误码有以下几种:

1: PERMISSION_DENIED - 用户拒绝了授权请求,授权失败
2: POSITION_UNAVAILABLE - 因为一些内部错误,导致位置获取失败
3: TIMEOUT - 超时,超过了配置的超时时间后还未获取到位置信息
上面就是失败的回调函数,一般获取位置出现错误时,我们都要及时捕获,并做相应的处理操作,以获取好的用户体验,这一点很重要。
在上面的调用中,我们还传入了第三个参数,一个简单的对象,里面包含了几个配置信息,它们都是用来配置函数运行参数的:

enableHighAccuracy: 默认值为false,如果指定为true,则表示在设备支持的情况下,尽可能获取高精准度的数据,但这会在时间和电量方面存在一定的消耗
timeout: 用于指定一个超时时间,单位为毫秒,表示在超时后停止位置获取的操作,默认值是Infinity,表示直到获取到数据后才停止该操作的进行
maximumAge: 用于指定一个缓存位置信息的最长时间,在这个时间段内,获取位置时会从缓存中取,单位为毫秒,默认值为0,表示不使用缓存,每次都取新的数据
上面是关于getCurrentPosition方法的介绍,在某些场景下,例如路线导航应用,我们需要实时地获取最新位置,进而为用户规划最新的路线,这时,上面的方法已经不能很好的满足需求了,我们需要使用watchPosition方法:

watchId = navigator.geolocation.watchPosition(success[, error[, options]]);

watchPosition方法的使用方式和getCurrentPosition类似,不同的是,success函数会执行多次,一旦获取到最新的位置数据,success函数就会被触发,与之相似地,如果连续获取最新的数据失败时,error函数也会被执行多次。
大家或许会注意到,上面的函数签名中,会返回一个watchId,它标示着当前的watch操作,当我们位置跟踪任务完成后,可以使用clearWatch函数将这个watchId清除即可:

navigator.geolocation.clearWatch(watchId);

上面就是Geolocation的常用的三个API,日常开发中我们可根据实际情况选用合适的方法,进而获取用户的位置信息。
现在大部分浏览器都已支持Geolocation了,可是为了兼容低版本的浏览器,我们需要判断它的支持情况:

if ('geolocation' in navigator) {   
  // getting usr's position   
} else {   
  // tips: your position is not available   
}

最后,我们用一个简单的例子来演示在开发中是如何使用Geolocation的:

var API = {   
    //get recommended data by current longitude and latitude   
    getSurroundingRecommendations: function(longitude, latitude, callback) {   
        //simulate data obtaining from server.   
        setTimeout(function() {   
            var data = [   
                {   
                    //item   
                },   
                {   
                    //item   
                }   
            ];   
            callback(data);   
        }, 500);   
    }   
};   
  
document.addEventListener('DOMContentLoaded', function() {   
    //detect if Geolocation is supported   
    if (!'geolocation' in navigator) {   
        console.log('Geolocation is not supported in your browser');   
        return;   
    }   
  
    var successHandler = function(position) {   
        var coords = position.coords,   
            longitude = coords.longitude,   
            latitude = coords.latitude;   
  
        API.getSurroundingRecommendations(longitude, latitude, function(data) {   
            console.log(data);   
        });   
    },   
    errorHandler = function(error) {   
        console.log(error.code, error.message);   
    },   
    options = {   
        enableHighAccuracy: true,   
        timeout: 5000,   
        maximumAge: 0   
    };   
  
    navigator.geolocation.getCurrentPosition(successHandler, errorHandler, options);   
  
}, false);


在上面的代码中,首先我们定义一个根据当前位置获取推荐数据的方法,然后在文档加载完成后,开始试图获取当前位置,并调研这个方法,获取模拟的数据,真是开发环境中,可能会进一步利用返回的数据做渲染UI等操作。

网络设备
位置服务用于估计您所在位置的本地网络信息包括:有关可见 WiFi 接入点的信息(包括信号强度)、有关您本地路由器的信息、您计算机的 IP 地址。位置服务的准确度和覆盖范围因位置不同而异。
总的来说,在PC的浏览器中 HTML5 的地理位置功能获取的位置精度不够高,如果借助这个 HTML5 特性做一个城市天气预报是绰绰有余,但如果是做一个地图应用,那误差还是太大了。不过,如果是移动设备上的 HTML5 应用,可以通过设置 enableHighAcuracy 参数为 true,调用设备的 GPS 定位来获取高精度的地理位置信息。

可选项
事实上,上述getCurrentPosition函数还支持第三个可选的参数,是一个 Option Object,一共有三个选项可以设定:

JavaScript Code复制内容到剪贴板
var options = {     
    enableHighAccuracy: false,     
    timeout: 5000,     
    maximumAge: 60000     
}


 
其中timeout是设定地理位置获取的超时时间(单位为毫秒,用户选择允许的时间不计算在内);而maximumAge表示允许设备从缓存中读取位置,缓存的过期时间,单位是毫秒,设为0来禁用缓存读取。如果返回的是缓存中的时间,会在timestamp中反映出来。
 

The above is the detailed content of Detailed explanation of how to use HTML5's Geolocation API. 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
H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

HTML5: The Standard and its Impact on Web DevelopmentHTML5: The Standard and its Impact on Web DevelopmentApr 27, 2025 am 12:12 AM

The core features of HTML5 include semantic tags, multimedia support, offline storage and local storage, and form enhancement. 1. Semantic tags such as, etc. to improve code readability and SEO effect. 2. Simplify multimedia embedding with labels. 3. Offline storage and local storage such as ApplicationCache and LocalStorage support network-free operation and data storage. 4. Form enhancement introduces new input types and verification properties to simplify processing and verification.

H5 Code Examples: Practical Applications and TutorialsH5 Code Examples: Practical Applications and TutorialsApr 25, 2025 am 12:10 AM

H5 provides a variety of new features and functions, greatly enhancing the capabilities of front-end development. 1. Multimedia support: embed media through and elements, no plug-ins are required. 2. Canvas: Use elements to dynamically render 2D graphics and animations. 3. Local storage: implement persistent data storage through localStorage and sessionStorage to improve user experience.

The Connection Between H5 and HTML5: Similarities and DifferencesThe Connection Between H5 and HTML5: Similarities and DifferencesApr 24, 2025 am 12:01 AM

H5 and HTML5 are different concepts: HTML5 is a version of HTML, containing new elements and APIs; H5 is a mobile application development framework based on HTML5. HTML5 parses and renders code through the browser, while H5 applications need to run containers and interact with native code through JavaScript.

The Building Blocks of H5 Code: Key Elements and Their PurposeThe Building Blocks of H5 Code: Key Elements and Their PurposeApr 23, 2025 am 12:09 AM

Key elements of HTML5 include,,,,,, etc., which are used to build modern web pages. 1. Define the head content, 2. Used to navigate the link, 3. Represent the content of independent articles, 4. Organize the page content, 5. Display the sidebar content, 6. Define the footer, these elements enhance the structure and functionality of the web page.

HTML5 and H5: Understanding the Common UsageHTML5 and H5: Understanding the Common UsageApr 22, 2025 am 12:01 AM

There is no difference between HTML5 and H5, which is the abbreviation of HTML5. 1.HTML5 is the fifth version of HTML, which enhances the multimedia and interactive functions of web pages. 2.H5 is often used to refer to HTML5-based mobile web pages or applications, and is suitable for various mobile devices.

HTML5: The Building Blocks of the Modern Web (H5)HTML5: The Building Blocks of the Modern Web (H5)Apr 21, 2025 am 12:05 AM

HTML5 is the latest version of the Hypertext Markup Language, standardized by W3C. HTML5 introduces new semantic tags, multimedia support and form enhancements, improving web structure, user experience and SEO effects. HTML5 introduces new semantic tags, such as, ,, etc., to make the web page structure clearer and the SEO effect better. HTML5 supports multimedia elements and no third-party plug-ins are required, improving user experience and loading speed. HTML5 enhances form functions and introduces new input types such as, etc., which improves user experience and form verification efficiency.

H5 Code: Writing Clean and Efficient HTML5H5 Code: Writing Clean and Efficient HTML5Apr 20, 2025 am 12:06 AM

How to write clean and efficient HTML5 code? The answer is to avoid common mistakes by semanticizing tags, structured code, performance optimization and avoiding common mistakes. 1. Use semantic tags such as, etc. to improve code readability and SEO effect. 2. Keep the code structured and readable, using appropriate indentation and comments. 3. Optimize performance by reducing unnecessary tags, using CDN and compressing code. 4. Avoid common mistakes, such as the tag not closed, and ensure the validity of the code.

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

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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