Home >Web Front-end >H5 Tutorial >HTML5 implements the function of obtaining geographical location information and positioning_html5 tutorial skills

HTML5 implements the function of obtaining geographical location information and positioning_html5 tutorial skills

WBOY
WBOYOriginal
2016-05-16 15:46:461544browse

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.

Copy code
The code is as follows:

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:

Copy code
The code is as follows:

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.

Copy code
The code is as follows:

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.

Copy code
The code is as follows:

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;

//google
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演示。
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