How to Use the HTML5 location locating Function
How to Use the HTML5 location locating Function
With relatively simple JavaScript code, you can create a Web application that can determine the geographical location details of users, including longitude and latitude and altitude. Some Web applications can even provide navigation functions by monitoring users' location movements over time, and integrate map systems such as GoogleMaps API.
HTML5 provides the Geolocation API to determine the user location. We can use this feature to develop applications based on geographic 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.
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.
?
1 2 3 4 5 6 7 8 |
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:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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.
?
1 2 3 4 5 |
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.
First, define the div to display the geographical location on the page, 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 div # baidu_geo as needed. Note that the jQuery library is used here. You need to load the jQuery library file first.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
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 div # google_geo as needed.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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.