A more popular type of service is called location-based service (LBS). This type of service is the information that enterprises use areas near the coordinates of a certain point (such as the location where the user is located), such as common map-related services. In HTML5, a new geolocation API was added to determine and share geolocation.
Privacy StatementPrivacy is a concern when sharing a physical location with a remote web server. Therefore, the geolocation API requires the user to provide permissions before the web application can access the location information. When you first access a web page that requests geolocation data, the browser will display a notification bar prompting you to provide access to the user's location. Follow the browser's prompts and select the relevant authorization.
If the user does not grant permissions, location information is not provided to the web application. Calling the relevant API will not trigger a successful callback.
Check browser supportThe geolocation API is supported in the latest version of mainstream browsers, but in order to be compatible with old browsers, you still need to check it out. If the Geolocation API is not available, window.navigator.geolocation will be null as follows:
function show_islocationenabled()
{
var str = "No, geolocation is not supported.";
if (window.navigator.geolocation) {
str = "Yes, geolocation is supported.";
}
alert( str );
}
The Geolocation API is based on a new property of the navigation global object: navigator.geolocation, which provides some useful information about the visitor's browser and system. Geolocation information can be obtained through many means: such as base stations, web databases or GPS. The accuracy of Geolocation information obtained using different methods is also different. Generally speaking, the most accurate one is obtained through GPS (the most GPS is used on mobile platforms, and the PC platform basically relies on network data). By chance, in some locations, you may not be able to obtain clear geographic location readings or receive no data.
Position the current locationUse the getCurrentPosition() method of navigation.geolocation to get the user's current location. This method only gets the location information once. When the method is called by the script, the method attempts to obtain the current location of the host device in an asynchronous manner.
Method signature: getCurrentPosition(geolocationSuccessCallback,[geolocationErrorCallback,geolocationOptions]);
1. geolocationSuccessCallback: Get the callback after the current location is successful (required)
2. geolocationErrorCallback. Callback used when an error occurs (optional)
3. geolocationOptions. Geolocation options (optional)
Process location information
After the getCurrentPositon() method successfully obtains the current position, it will save the position information to a Position object, and then use this object as a parameter to execute the callback of geolocationSuccessCallback. In this callback function, you can arbitrarily handle the information contained in this object.
The Position object has two properties: timestamp and coords. The timestamp attribute represents the creation time of geolocation data, and the coords attribute represents geolocation information, and contains seven attributes:
.coords.latitude: Estimate latitude
. coords.longitude: Estimate longitude
.coords.altitude: Estimated height
. coords.accuracy: The accuracy of longitude and latitude estimates provided in meters
.coords.altitudeAccuracy: The accuracy of height estimates provided in meters
. coordinates.heading: The angular direction of the host device currently moving, calculated clockwise relative to the north direction
.coords.speed: The current ground speed of the device in meters per second
Generally, three of these properties are guaranteed: coords.latitude, coords.longitude, and coords.accuracy, and the rest return null; this depends on the capabilities of the device and the backend positioning server it uses. Moreover, heading and speed properties can be calculated based on the user's previous position.
Handling errorsIf an error occurs when executing the getCurrentPositon() method, the method passes a PositionError object to the geolocationErrorCallback callback.
Set geolocation optionsYou can set three properties of geolocationOptions:
enableHighAccuracy: If the device supports high precision, this option indicates whether high precision is enabled.
timeout: query timeout
maximumAge: The maximum number of times the cache is located, during which the cache can be used.
See the complete example below:
<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your position:</p>
<button onclick="getLocation()">Try It</button>
<div id="maholder"></div>
<script>
var x=document.getElementById("demo");
function getLocation() {
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{
x.innerHTML="Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
var latlon=position.coords.latitude+","+position.coords.longitude;
var img_url="http://maps.googleapis.com/maps/api/staticmap?center=" +
latlon + "&zoom=9&size=400x300&sensor=false";
document.getElementById("maholder").innerHTML="<img src='"+img_url+"' />";
}
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;
}
}
</script>
</body>
</html>
This example takes the geographic location of the current device and displays it in Google Maps. Of course you can use the static graph version in Baidu Maps API to transform this example. For Baidu Map API, please refer to the link in the practical reference later.
Turn on/cancel continuous positioningUse the watchPosition() method of navigation.geolocation to poll the user's location regularly to see if the user's location has changed. This method has three parameters: these three parameters are the same as the getCurrentPosition() method, a successful callback, a failed callback, and an option to get position information; this method has a return value watchID, which is used to cancel continuous positioning.
Use the clearWatch() method of navigation.geolocation to terminate the ongoing watchPosition(), which only takes one parameter watchID.
See the following example:
<!DOCTYPE html>
<html>
<head>
<title>Geolocation API Example: Listening for Location Updates</title>
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<script type="text/javascript">
function setText(val, e) {
document.getElementById(e).value = val;
}
var nav = null;
var watchID;
function listenForPositionUpdates() {
if (nav == null) {
nav = window.navigator;
}
if (nav != null) {
var geoloc = nav.geolocation;
if (geoloc != null) {
watchID = geoloc.watchPosition(successCallback);
}
else {
alert("geolocation not supported");
}
}
else {
alert("Navigator not found");
}
}
function clearWatch(watchID) {
window.navigator.geolocation.clearWatch(watchID);
}
function successCallback(position)
{
setText(position.coords.latitude, "latitude");
setText(position.coords.longitude, "longitude");
}
</script>
</head>
<body>
<label for="latitude">Latitude: </label><input id="latitude" />
<label for="longitude">Longitude: </label><input id="longitude" />
<input type="button" value="Watch Latitude and Longitude" onclick="listenForPositionUpdates()" />
<input type="button" value="Clear watch" onclick="clearWatch()" />
</body>
</html>
Practical reference:Official document: http://www.w3schools.com/html5/html5_geolocation.asp
Template worries: http://www.CuoXIn.com/w3school/html5/
Microsoft Help: http://msdn.microsoft.com/zh-cn/library/gg589502(v=vs.85)
Baidu Map API: http://dev.baidu.com/wiki/static/index.htm