


HTML5 implements the function of obtaining geographical location information and positioning_html5 tutorial skills
HTML5 provides a geolocation function (Geolocation API), which can determine the user's location. We can use this feature of HTML5 to develop applications based on geolocation information. This article uses examples to share with you how to use HTML5 and use Baidu and Google Maps interfaces to obtain users' accurate geographical location information.
Source code download: Click here to download
How to use HTML5 geolocation function
Geolocation is a new feature of HTML5, so it can only run on modern browsers that support HTML5, especially handheld devices such as iPhones, where geolocation is more accurate. First we need to detect whether the user's device browser supports geolocation, and if so, obtain the geographic information. Note that this feature may infringe on the user's privacy. Unless the user agrees, the user's location information is not available. Therefore, when we access the application, we will be prompted whether to allow geolocation. Of course, we can choose to allow it.
function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition,showError);
}else{
alert("The browser does not support geolocation.");
}
}
The above code can know that if the user device supports geolocation, the getCurrentPosition() method is run. If getCurrentPosition() runs successfully, a coordinates object is returned to the function specified in the parameter showPosition. The second parameter showError of the getCurrentPosition() method is used to handle errors. It specifies the function to be run when obtaining the user's position fails.
Let’s first look at the function showError(), which stipulates some error code handling methods when obtaining the user’s geographical location fails:
function showError(error){
switch(error.code) {
case error.PERMISSION_DENIED:
alert("Positioning failed , the user refused to request geolocation");
break;
case error.POSITION_UNAVAILABLE:
alert("Positioning failed, location information is unavailable");
break;
case error. TIMEOUT:
alert("Positioning failed, request to obtain user location timed out");
break;
case error.UNKNOWN_ERROR:
alert("Positioning failed, positioning system failed");
break;
}
}
Let’s look at the function showPosition() again. Call the latitude and longitude of coords to get the user’s latitude and longitude.
function showPosition(position){
var lat = position.coords.latitude; //Latitude
var lag = position.coords.longitude; //Longitude
alert('Latitude:' lat ',Longitude:' lag);
}
Use Baidu Maps and Google Maps interfaces to obtain the user’s address
Above we learned that HTML5’s Geolocation can obtain the user’s latitude and longitude, so what we need to do What is needed is to convert abstract longitude and latitude into readable and meaningful real user geographical location information. Fortunately, Baidu Maps and Google Maps provide interfaces in this regard. We only need to pass the longitude and latitude information obtained by HTML5 to the map interface, and the user's geographical location will be returned, including province and city information, and even streets, House number and other detailed geographical location information.
We first define the div to display the geographical location on the page, defining id#baidu_geo and id#google_geo respectively. We only need to modify the key function showPosition(). Let's first look at the Baidu map interface interaction. We send the latitude and longitude information to the Baidu map interface through Ajax, and the interface will return the corresponding province, city, and street information. The Baidu map interface returns a string of JSON data. We can display the required information to div#baidu_geo according to our needs. Note that the jQuery library is used here, and the jQuery library file needs to be loaded first.
function showPosition(position){
var latlon = position.coords.latitude ',' position.coords.longitude;
//baidu
var url = "http://api.map.baidu.com/geocoder/v2/?ak=C93b5178d7a8ebdb830b9b557abce78b&callback=renderReverse&location=" latlon "&output=json&pois=0";
$.ajax({
type: "GET",
dataType: "jsonp",
url: url,
beforeSend: function(){
$("#baidu_geo").html('正在定位...');
},
success: function (json) {
if(json.status==0){
$("#baidu_geo").html(json.result.formatted_address);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#baidu_geo").html(latlon "地址位置获取失败");
}
});
});
再来看谷歌地图接口交互。同样我们将经纬度信息通过Ajax方式发送给谷歌地图接口,接口会返回相应的省市区街道详细信息。谷歌地图接口返回的也是一串JSON数据,这些JSON数据比百度地图接口返回的要更详细,我们可以根据需求将需要的信息展示给div#google_geo。
function showPosition(position){
var latlon = position.coords.latitude ',' position.coords.longitude;
var url = 'http://maps.google.cn/maps/api/geocode/json?latlng=' latlon '&language=CN';
$.ajax({
type: "GET",
url: url,
beforeSend: function(){
$("#google_geo").html('正在定位...');
},
success: function (json) {
if(json.status=='OK'){
var results = json.results;
$.each(results,function(index,array){
if(index==0){
$("#google_geo").html(array['formatted_address']);
}
});
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#google_geo").html(latlon "地址位置获取失败");
}
});
}
以上的代码分别将百度地图接口和谷歌地图接口整合到函数showPosition()中,我们可以根据实际情况进行调用。当然这只是一个简单的应用,我们可以根据这个简单的示例开发出很多复杂的应用,建议用手机浏览器访问DEMO演示。

H5 is HTML5, the fifth version of HTML. HTML5 improves the expressiveness and interactivity of web pages, introduces new features such as semantic tags, multimedia support, offline storage and Canvas drawing, and promotes the development of Web technology.

Accessibility and compliance with network standards are essential to the website. 1) Accessibility ensures that all users have equal access to the website, 2) Network standards follow to improve accessibility and consistency of the website, 3) Accessibility requires the use of semantic HTML, keyboard navigation, color contrast and alternative text, 4) Following these principles is not only a moral and legal requirement, but also amplifying user base.

The H5 tag in HTML is a fifth-level title that is used to tag smaller titles or sub-titles. 1) The H5 tag helps refine content hierarchy and improve readability and SEO. 2) Combined with CSS, you can customize the style to enhance the visual effect. 3) Use H5 tags reasonably to avoid abuse and ensure the logical content structure.

The methods of building a website in HTML5 include: 1. Use semantic tags to define the web page structure, such as, , etc.; 2. Embed multimedia content, use and tags; 3. Apply advanced functions such as form verification and local storage. Through these steps, you can create a modern web page with clear structure and rich features.

A reasonable H5 code structure allows the page to stand out among a lot of content. 1) Use semantic labels such as, etc. to organize content to make the structure clear. 2) Control the rendering effect of pages on different devices through CSS layout such as Flexbox or Grid. 3) Implement responsive design to ensure that the page adapts to different screen sizes.

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.


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

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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.

SublimeText3 Linux new version
SublimeText3 Linux latest version
