HTML5: Obtain and locate geographic location information _ html5 tutorial skills-

Source: Internet
Author: User
This article mainly introduces HTML5 to obtain and locate geographic location information. This article describes three methods for obtaining and locating geographical location information, such as native HTML5, Baidu map, and Google map, you can refer to the Geolocation API provided by html5. you can use this feature to develop applications based on geographical location information. This article uses examples to show you how to use HTML5 and use Baidu and Google map interfaces to obtain accurate geographical location information.

Source code download: Click here to download

How to Use the HTML5 location locating Function

Geolocation is a new feature of HTML5. Therefore, it only runs on modern browsers that support HTML5, especially handheld devices such as the iphone. First, we need to check whether the browser of the user's device supports geographic location. If so, we need to obtain geographic information. Note that this feature may infringe on user privacy. Unless agreed by the user, the user location information is unavailable. Therefore, when accessing this application, we will prompt whether to allow geographic location, of course, you can select allow.

The Code is as follows:


Function getLocation (){
If (navigator. geolocation ){
Navigator. geolocation. getCurrentPosition (showPosition, showError );
} Else {
Alert ("the browser does not support location. ");
}
}


The code above shows that if your device supports geographic location, run the getCurrentPosition () method. If getCurrentPosition () runs successfully, a coordinates object is returned to the function specified in the showPosition parameter. The second parameter showError of the getCurrentPosition () method is used to handle errors, it specifies the function that runs when the user location fails to be obtained.
Let's take a look at the showError () function, which specifies how to handle some error codes that fail to get users' geographic locations:

The Code is as follows:


Function showError (error ){
Switch (error. code ){
Case error. PERMISSION_DENIED:
Alert ("location failed, user refused to request location ");
Break;
Case error. POSITION_UNAVAILABLE:
Alert ("positioning failed, location information is unavailable ");
Break;
Case error. TIMEOUT:
Alert ("locating failed, request to get user location timeout ");
Break;
Case error. UNKNOWN_ERROR:
Alert ("locating failed, locating system failed ");
Break;
}
}


Let's take a look at the showPosition () function. Call the latitude and longpolling functions of coords to obtain the user's latitude and longitude.

The Code is as follows:


Function showPosition (position ){
Var lat = position. coords. latitude; // latitude
Var lag = position. coords. longpolling; // longitude
Alert ('latitude: '+ lat +', longitude: '+ lag );
}



Use Baidu maps and Google Maps to get user addresses

We learned above that HTML5 Geolocation can obtain the user's latitude and longitude, so what we need to do is to convert the abstract latitude and longitude into a readable and meaningful real user geographic location information. Fortunately, Baidu maps and Google Maps provide this interface. We only need to pass the latitude and longitude information obtained by HTML5 to the map interface, and then return the geographical location of the user, including provincial and municipal information, and even detailed geographic location information such as street and house number.
On the page, we first define the p where the geographical location is to be displayed, and define id # baidu_geo and id # google_geo respectively. We only need to modify the key function showPosition (). First, let's look at Baidu map interface interaction. We send the latitude and longitude information to Baidu map interface via Ajax, and the interface will return the corresponding provincial and municipal street information. The Baidu map interface returns a string of JSON data. We can display the required information to p # baidu_geo as needed. Note that the jQuery library is used here. You need to load the jQuery library file first.

The Code is as follows:


Function showPosition (position ){
Var latlon = position. coords. latitude + ',' + position. coords. longpolling;

// 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" pai.html ('positioning ...');
},
Success: function (json ){
If (json. status = 0 ){
$ ("# Baidu_geo" ).html (json. result. formatted_address );
}
},
Error: function (XMLHttpRequest, textStatus, errorThrown ){
$ ("# Baidu_geo" ).html (latlon + "An error occurred while obtaining the address location ");
}
});
});


Let's take a look at Google map interface interaction. Similarly, we send the latitude and longitude information to the Google map interface through Ajax, and the interface will return the corresponding provincial and municipal street details. The Google map interface also returns a string of JSON data, which is more detailed than the Baidu map interface. We can display the required information to p # google_geo as needed.

The Code is as follows:


Function showPosition (position ){
Var latlon = position. coords. latitude + ',' + position. coords. longpolling;

// Google
Var url = 'HTTP: // maps.google.cn/maps/api/geocode/json? Latlng = '+ latlon +' & language = cn ';
$. Ajax ({
Type: "GET ",
Url: url,
BeforeSend: function (){
$ ("# Google_geo" pai.html ('positioning ...');
},
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 + "An error occurred while obtaining the address location ");
}
});
}


The above code integrates Baidu map interface and Google map interface into the function showPosition (), which can be called according to the actual situation. Of course, this is just a simple application. We can develop many complicated applications based on this simple example. We recommend that you use a mobile browser to access the DEMO.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.