search
HomeWeb Front-endH5 TutorialHow to correctly use HTML geolocation in HTML5?

There is no doubt that HTML5 is a hot topic for developers. If you need to quickly understand the basic principles of HTML5 functions, this article mainly explains HTML5 geolocation.

HTML5 geolocation usage

HTML5 Geolocation (geolocation) is used to locate the user's location.

Locate the user's location

HTML5 Geolocation API is used to obtain the user's geographical location.

Given that this feature may violate user privacy, user location information is not available unless the user agrees.

Browser support

Internet Explorer 9, Firefox, Chrome, Safari and Opera support geolocation.

Note: For devices with GPS, such as iPhone, geolocation is more precise.

HTML5 - Using geolocation

Please use the getCurrentPosition() method to get the user's location.

The following example is a simple geolocation example that returns the longitude and latitude of the user's location.

Here are examples:

<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML="Latitude: " + position.coords.latitude +
  "<br />Longitude: " + position.coords.longitude;
  }
</script>

Explanation of examples:

Detect whether geolocation is supported

If supported, run getCurrentPosition( ) method. If not supported, a message is displayed to the user.

If getCurrentPosition() runs successfully, a coordinates object is returned to the function specified in the parameter showPosition

The showPosition() function obtains and displays the longitude and latitude

The above example Is a very basic geolocation script without error handling.

Handling errors and rejections

The second parameter of the getCurrentPosition() method is used to handle errors. It specifies the function to be run when obtaining the user's location fails:

There is also an example:

function showError(error)
  {
  switch(error.code)
    {
    case error.PERMISSION_DENIED:
      x.innerHTML="User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML="Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML="The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML="An unknown error occurred."
      break;
    }
  }

Error code:

Permission denied - User is not allowed to geolocate

Position unavailable - Unable to obtain the current position

Timeout - Operation timeout

Display the results in the map

To display the results in the map , you need to access a map service that can use latitude and longitude, such as Google Maps or Baidu Maps:

Also examples:

function showPosition(position)
{
var latlon=position.coords.latitude+","+position.coords.longitude;
var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML="<img  src=&#39;"+img_url+"&#39; / alt="How to correctly use HTML geolocation in HTML5?" >";
}

In the above example, we use the returned latitude and longitude data in Google Maps Display position (using static image).

The link above shows you how to use a script to display an interactive map with markers, zoom and drag options.

Information for a given location

This page demonstrates how to display the user's location on the map. However, geolocation is also useful for information about a given location.

Update local information

Display points of interest around the user

Interactive car navigation system (GPS)

getCurrentPosition() method - return data

If successful, the getCurrentPosition() method returns the object. The latitude, longitude, and accuracy properties are always returned. If available, the other following properties are returned.

Properties and descriptions:

coords.latitude(latitude as a decimal number)

coords.longitude(longitude as a decimal number)

coords.accuracy( Position accuracy)

coords.altitude (elevation, in meters above sea level)

coords.altitudeAccuracy (elevation accuracy of the position)

coords.heading (direction, from True north start in degrees)

coords.speed(speed in meters per second)

timestamp(date/time of response)

Geolocation object - other Interesting method

watchPosition() - returns the user's current position and continues to return the updated position as the user moves (like a GPS in a car).

clearWatch() - Stop watchPosition() method

The following example shows the watchPosition() method. You need an accurate GPS device to test this example (such as an iPhone):

There are examples to prove:

<script>
var x=document.getElementById("demo");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.watchPosition(showPosition);
    }
  else{x.innerHTML="Geolocation is not supported by this browser.";}
  }
function showPosition(position)
  {
  x.innerHTML="Latitude: " + position.coords.latitude +
  "<br />Longitude: " + position.coords.longitude;
  }
</script

[Related recommendations]

The development history of HTML and HTML5

The basic elements of html, allowing you to learn HTML from scratch


The above is the detailed content of How to correctly use HTML geolocation in HTML5?. 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
How to Add Audio to My HTML5 Website?How to Add Audio to My HTML5 Website?Mar 10, 2025 pm 03:01 PM

This article explains how to embed audio in HTML5 using the <audio> element, including best practices for format selection (MP3, Ogg Vorbis), file optimization, and JavaScript control for playback. It emphasizes using multiple audio f

How to Use HTML5 Forms for User Input?How to Use HTML5 Forms for User Input?Mar 10, 2025 pm 02:59 PM

This article explains how to create and validate HTML5 forms. It details the <form> element, input types (text, email, number, etc.), and attributes (required, pattern, min, max). The advantages of HTML5 forms over older methods, incl

How do I use the HTML5 Page Visibility API to detect when a page is visible?How do I use the HTML5 Page Visibility API to detect when a page is visible?Mar 13, 2025 pm 07:51 PM

The article discusses using the HTML5 Page Visibility API to detect page visibility, improve user experience, and optimize resource usage. Key aspects include pausing media, reducing CPU load, and managing analytics based on visibility changes.

How do I use viewport meta tags to control page scaling on mobile devices?How do I use viewport meta tags to control page scaling on mobile devices?Mar 13, 2025 pm 08:00 PM

The article discusses using viewport meta tags to control page scaling on mobile devices, focusing on settings like width and initial-scale for optimal responsiveness and performance.Character count: 159

How do I handle user location privacy and permissions with the Geolocation API?How do I handle user location privacy and permissions with the Geolocation API?Mar 18, 2025 pm 02:16 PM

The article discusses managing user location privacy and permissions using the Geolocation API, emphasizing best practices for requesting permissions, ensuring data security, and complying with privacy laws.

How to Create Interactive Games with HTML5 and JavaScript?How to Create Interactive Games with HTML5 and JavaScript?Mar 10, 2025 pm 06:34 PM

This article details creating interactive HTML5 games using JavaScript. It covers game design, HTML structure, CSS styling, JavaScript logic (including event handling and animation), and audio integration. Essential JavaScript libraries (Phaser, Pi

How do I use the HTML5 Drag and Drop API for interactive user interfaces?How do I use the HTML5 Drag and Drop API for interactive user interfaces?Mar 18, 2025 pm 02:17 PM

The article explains how to use the HTML5 Drag and Drop API to create interactive user interfaces, detailing steps to make elements draggable, handle key events, and enhance user experience with custom feedback. It also discusses common pitfalls to a

How do I use the HTML5 WebSockets API for bidirectional communication between client and server?How do I use the HTML5 WebSockets API for bidirectional communication between client and server?Mar 12, 2025 pm 03:20 PM

This article explains the HTML5 WebSockets API for real-time, bidirectional client-server communication. It details client-side (JavaScript) and server-side (Python/Flask) implementations, addressing challenges like scalability, state management, an

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

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.