Comments: In HTML5, a new geographic location API is added to determine and share geographical locations. This type of service is used by an enterprise to provide service information in a region near the coordinates of a certain point (such as the user's location), such as common map-related services. This article describes in detail, if you are interested, you may find that a type of service that is currently quite popular is location-based service (LBS ), this type of service is used by an enterprise to provide service information in a region near the coordinates of a certain point (such as the user's location), such as common map-related services. In HTML5, a new geographic location API is added to determine and share geographical locations.
Privacy Statement
Privacy is a concern when sharing physical locations with remote Web servers. Therefore, the geographic location API requires the user to provide permissions before the Web application can access location information. When you first access a webpage requesting geographical location data, the browser displays a notification bar prompting you to grant access permissions to the user's location. Follow the browser prompts and select related authorization.
If the user has not been granted permissions, the location information is not provided to the Web application. Successful callback is not triggered when related APIs are called.
Check browser support
The geographic location API is supported in the latest mainstream browsers, but to be compatible with the old browsers, check it. If the geographic location API is unavailable, window. navigator. geolocation is null, as shown below:
The Code is as follows:
Function show_islocationenabled ()
{
Var str = "No, geolocation is not supported .";
If (window. navigator. geolocation ){
Str = "Yes, geolocation is supported .";
}
Alert (str );
}
Geolocation API is based on a new property of the 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. In general, Geolocation information obtained through GPS is the most accurate (most GPS is used on mobile platforms, on the PC platform, network data is basically used ). By accident, in some locations, you may not be able to get a clear geographic location reading or a little data.
Locate the current location
Use the getCurrentPosition () method of navigator. geolocation to obtain the user's current location. This method only obtains the location information once. When this method is called by a script, the method asynchronously attempts to obtain the current location of the host device.
The Code is as follows:
Method Signature: getCurrentPosition (geolocationSuccessCallback, [geolocationErrorCallback, geolocationOptions]);
1. geolocationSuccessCallback: gets the callback after the current location is successful (required)
2. geolocationErrorCallback. Callback used when an error occurs (optional)
3. geolocationOptions. geographic location options (optional)
Processing Location Information
After the getCurrentPositon () method succeeds in obtaining the current Position, it will save the location information to a Position object and use this object as a parameter to execute the geolocationSuccessCallback callback. In this callback function, you can handle the information contained in this object at will.
The Position object has two attributes: timestamp and coords. The timestamp attribute indicates the creation time of the geographic location data, and the coords attribute indicates the geographic location information. It also contains seven attributes:
The Code is as follows:
. Coords. latitude: Estimated latitude
. Coords. longpolling: Estimated longitude
. Coords. altitude: Estimated height
. Coords. accuracy: accuracy of latitude and longitude estimates in meters
. Coords. altitudeAccuracy: accuracy of the provided height estimates in meters
. Coords. heading: The angle direction of the current movement of the host device, clockwise relative to the North
. Coords. speed: current local speed of a device in meters per second
Generally, three of these attributes are guaranteed: coords. latitude, coords. longpolling and coords. accuracy, And the rest return null; this depends on the capabilities of the device and the backend locating server used by the device. In addition, the heading and speed attributes can be calculated based on the user's previous locations.
Handling error
If an error occurs when the getCurrentPositon () method is executed, the method passes a PositionError object to the geolocationErrorCallback callback.
Set location options
You can set three attributes of geolocationOptions:
The Code is as follows:
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 this period, the cache can be used.
Let's take a look at the complete example below:
The Code is as follows:
<! DOCTYPE html>
<Html>
<Body>
<P id = "demo"> Click the button to get your position: </p>
<Button onclick = "getLocation ()"> Try It </button>
<Div id = "mapholder"> </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. longpolling;
Var img_url = "http://maps.googleapis.com/maps/api/staticmap? Center = "+
Latlon + "& zoom = 9 & size = 400x300 & sensor = false ";
Document. getElementById ("mapholder"). innerHTML = " ";
}
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>
In this example, the location of the current device is obtained and displayed on a Google Map. Of course, you can use the static graph version in Baidu map API to transform this example. For more information about the Baidu map API, see the link in the following practical reference.
Enable/disable continuous positioning
You can use the watchPosition () method of navigator. geolocation to regularly poll the user's location and check whether the user's location has changed. This method has three parameters: the three parameters are the same as the getCurrentPosition () method, a successful callback, a failed callback, and an option for obtaining location information; the returned value of this method is watchID, which is used to cancel the continuous positioning.
Use the clearWatch () method of navigator. geolocation to terminate ongoing watchPosition (). This method only includes one parameter watchID.
See the following example:
The Code is as follows:
<! 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. longpolling, "longpolling ");
}
</Script>
</Head>
<Body>
<Label for = "latitude"> Latitude: </label> <input id = "latitude"/>
<Label for = "longpolling"> longpolling: </label> <input id = "longpolling"/>
<Input type = "button" value = "Watch Latitude and longpolling" onclick = "listenForPositionUpdates ()"/>
<Input type = "button" value = "Clear watch" onclick = "clearWatch ()"/>
</Body>
</Html>
Practical reference:
Official documents: http://www.w3schools.com/html5/html5_geolocation.asp
Feet home: http://www.jb51.net/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