What we are going to learn today is to use Geolocation to implement positioning functions. We can obtain the Geolocation object through navigator.geolocation, which provides the following methods:
getCurrentPosition(callback,errorCallback,options): Get the current position;
watchPosition(callback,error,options): Start monitoring the current location;
clearWatch(id): Stop monitoring the current location.
Note: The browser used in the example below is chrome. If you use other browsers, I cannot guarantee that the running results will be consistent with the results displayed in the example.
1. Get the current position
We will use the getCurrentPosition method to obtain the current position. The location information will not be returned directly in the form of a result. We Need to use callback function for processing. There will be some delays in getting the coordinates, and you will be asked for access permissions. Let's look at the following example:
<!DOCTYPE HTML><html><head> <title>Example</title> <style> table{border-collapse: collapse;} th, td{padding: 4px;} th{text-align: right;} </style></head><body> <table border="1"> <tr> <th>Longitude:</th> <td id="longitude">-</td> <th>Latitude:</th> <td id="latitude">-</td> </tr> <tr> <th>Altitude:</th> <td id="altitude">-</td> <th>Accuracy:</th> <td id="accuracy">-</td> </tr> <tr> <th>Altitude Accuracy:</th> <td id="altitudeAccuracy">-</td> <th>Heading:</th> <td id="heading">-</td> </tr> <tr> <th>Speed:</th> <td id="speed">-</td> <th>Time Stamp:</th> <td id="timestamp">-</td> </tr> </table> <script> navigator.geolocation.getCurrentPosition(displayPosition); function displayPosition(pos) { var properties = ['longitude', 'latitude', 'altitude', 'accuracy', 'altitudeAccuracy', 'heading', 'speed']; for (var i = 0, len = properties.length; i < len; i++) { var value = pos.coords[properties[i]]; document.getElementById(properties[i]).innerHTML = value; } document.getElementById('timestamp').innerHTML = pos.timestamp; } </script></body></html>
The returned position object contains two attributes, coords: returns coordinate information; timestamp: the time when coordinate information was obtained. Among them, coords includes the following attributes: latitude: latitude; longitude: longitude; altitude: height; accuracy: accuracy (meters); altitudeAccuracy: altitude accuracy (meters); heading: direction of travel; speed: speed of travel (meters/second) .
Not all information will be returned, depending on the device you are hosting your browser on. Mobile devices with GPS, accelerometer, and compass will return most of the information, but home computers will not. The location information obtained by the home computer depends on the network environment or wifi. Let's look at the results of the above example.
Click Allow to obtain coordinate information.
2. Handling exceptions
Now we introduce theException handling of getCurrentPosition, which is done by using errorCallback Callback function implemented. The parameter error returned by the function contains two attributes, code: error type code; message: error message. The code contains three values: 1: The user is not authorized to use geolocation; 2: Unable to obtain coordinate information; 3: Timeout for obtaining information.
Let’s look at an example:<!DOCTYPE HTML><html><head> <title>Example</title> <style> table{border-collapse: collapse;} th, td{padding: 4px;} th{text-align: right;} </style></head><body> <table border="1"> <tr> <th>Longitude:</th> <td id="longitude">-</td> <th>Latitude:</th> <td id="latitude">-</td> </tr> <tr> <th>Altitude:</th> <td id="altitude">-</td> <th>Accuracy:</th> <td id="accuracy">-</td> </tr> <tr> <th>Altitude Accuracy:</th> <td id="altitudeAccuracy">-</td> <th>Heading:</th> <td id="heading">-</td> </tr> <tr> <th>Speed:</th> <td id="speed">-</td> <th>Time Stamp:</th> <td id="timestamp">-</td> </tr> <tr> <th>Error Code:</th> <td id="errcode">-</td> <th>Error Message:</th> <td id="errmessage">-</td> </tr> </table> <script> navigator.geolocation.getCurrentPosition(displayPosition, handleError); function displayPosition(pos) { var properties = ["longitude", "latitude", "altitude", "accuracy", "altitudeAccuracy", "heading", "speed"]; for (var i = 0; i < properties.length; i++) { var value = pos.coords[properties[i]]; document.getElementById(properties[i]).innerHTML = value; } document.getElementById("timestamp").innerHTML = pos.timestamp; } function handleError(err) { document.getElementById("errcode").innerHTML = err.code; document.getElementById("errmessage").innerHTML = err.message; } </script></body></html>Authorization denied, running result:
3 .Use geolocation optional parameter items
The options in getCurrentPosition(callback,errorCallback,options) have the following parameters that can be used, enableHighAccuracy: use the best effect; timeout: timeout time (milliseconds); maximumAge : Specifies thecache time (milliseconds). Let’s take the following example:
<!DOCTYPE HTML><html><head> <title>Example</title> <style> table{border-collapse: collapse;} th, td{padding: 4px;} th{text-align: right;} </style></head><body> <table border="1"> <tr> <th>Longitude:</th> <td id="longitude">-</td> <th>Latitude:</th> <td id="latitude">-</td> </tr> <tr> <th>Altitude:</th> <td id="altitude">-</td> <th>Accuracy:</th> <td id="accuracy">-</td> </tr> <tr> <th>Altitude Accuracy:</th> <td id="altitudeAccuracy">-</td> <th>Heading:</th> <td id="heading">-</td> </tr> <tr> <th>Speed:</th> <td id="speed">-</td> <th>Time Stamp:</th> <td id="timestamp">-</td> </tr> <tr> <th>Error Code:</th> <td id="errcode">-</td> <th>Error Message:</th> <td id="errmessage">-</td> </tr> </table> <script> var options = { enableHighAccuracy: false, timeout: 2000, maximumAge: 30000 }; navigator.geolocation.getCurrentPosition(displayPosition, handleError, options); function displayPosition(pos) { var properties = ["longitude", "latitude", "altitude", "accuracy", "altitudeAccuracy", "heading", "speed"]; for (var i = 0; i < properties.length; i++) { var value = pos.coords[properties[i]]; document.getElementById(properties[i]).innerHTML = value; } document.getElementById("timestamp").innerHTML = pos.timestamp; } function handleError(err) { document.getElementById("errcode").innerHTML = err.code; document.getElementById("errmessage").innerHTML = err.message; } </script></body></html>
4. Monitor position changes
Below we introduce the use of watchPosition method to monitor position changes. Its usage is the same as getCurrentPosition. . Let’s look at an example:<!DOCTYPE HTML><html><head> <title>Example</title> <style> table{border-collapse: collapse;} th, td{padding: 4px;} th{text-align: right;} </style></head><body> <table border="1"> <tr> <th>Longitude:</th> <td id="longitude">-</td> <th>Latitude:</th> <td id="latitude">-</td> </tr> <tr> <th>Altitude:</th> <td id="altitude">-</td> <th>Accuracy:</th> <td id="accuracy">-</td> </tr> <tr> <th>Altitude Accuracy:</th> <td id="altitudeAccuracy">-</td> <th>Heading:</th> <td id="heading">-</td> </tr> <tr> <th>Speed:</th> <td id="speed">-</td> <th>Time Stamp:</th> <td id="timestamp">-</td> </tr> <tr> <th>Error Code:</th> <td id="errcode">-</td> <th>Error Message:</th> <td id="errmessage">-</td> </tr> </table> <button id="pressme">Cancel Watch</button> <script> var options = { enableHighAccuracy: false, timeout: 2000, maximumAge: 30000 }; var watchID = navigator.geolocation.watchPosition(displayPosition, handleError, options); document.getElementById("pressme").onclick = function (e) { navigator.geolocation.clearWatch(watchID); }; function displayPosition(pos) { var properties = ["longitude", "latitude", "altitude", "accuracy", "altitudeAccuracy", "heading", "speed"]; for (var i = 0; i < properties.length; i++) { var value = pos.coords[properties[i]]; document.getElementById(properties[i]).innerHTML = value; } document.getElementById("timestamp").innerHTML = pos.timestamp; } function handleError(err) { document.getElementById("errcode").innerHTML = err.code; document.getElementById("errmessage").innerHTML = err.message; } </script></body></html>
The above is the detailed content of HTML5 Guide (4) - Detailed explanation of using Geolocation. For more information, please follow other related articles on the PHP Chinese website!

Best practices for H5 code include: 1. Use correct DOCTYPE declarations and character encoding; 2. Use semantic tags; 3. Reduce HTTP requests; 4. Use asynchronous loading; 5. Optimize images. These practices can improve the efficiency, maintainability and user experience of web pages.

Web standards and technologies have evolved from HTML4, CSS2 and simple JavaScript to date and have undergone significant developments. 1) HTML5 introduces APIs such as Canvas and WebStorage, which enhances the complexity and interactivity of web applications. 2) CSS3 adds animation and transition functions to make the page more effective. 3) JavaScript improves development efficiency and code readability through modern syntax of Node.js and ES6, such as arrow functions and classes. These changes have promoted the development of performance optimization and best practices of web applications.

H5 is not just the abbreviation of HTML5, it represents a wider modern web development technology ecosystem: 1. H5 includes HTML5, CSS3, JavaScript and related APIs and technologies; 2. It provides a richer, interactive and smooth user experience, and can run seamlessly on multiple devices; 3. Using the H5 technology stack, you can create responsive web pages and complex interactive functions.

H5 and HTML5 refer to the same thing, namely HTML5. HTML5 is the fifth version of HTML, bringing new features such as semantic tags, multimedia support, canvas and graphics, offline storage and local storage, improving the expressiveness and interactivity of web pages.

H5referstoHTML5,apivotaltechnologyinwebdevelopment.1)HTML5introducesnewelementsandAPIsforrich,dynamicwebapplications.2)Itsupportsmultimediawithoutplugins,enhancinguserexperienceacrossdevices.3)SemanticelementsimprovecontentstructureandSEO.4)H5'srespo

The tools and frameworks that need to be mastered in H5 development include Vue.js, React and Webpack. 1.Vue.js is suitable for building user interfaces and supports component development. 2.React optimizes page rendering through virtual DOM, suitable for complex applications. 3.Webpack is used for module packaging and optimize resource loading.

HTML5hassignificantlytransformedwebdevelopmentbyintroducingsemanticelements,enhancingmultimediasupport,andimprovingperformance.1)ItmadewebsitesmoreaccessibleandSEO-friendlywithsemanticelementslike,,and.2)HTML5introducednativeandtags,eliminatingthenee

H5 improves web page accessibility and SEO effects through semantic elements and ARIA attributes. 1. Use, etc. to organize the content structure and improve SEO. 2. ARIA attributes such as aria-label enhance accessibility, and assistive technology users can use web pages smoothly.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version
Visual web development tools