HTML5 JavaScript API Extension 2-geo-information services

Source: Internet
Author: User
Tags web database

In HTML5, a new geography API is added to identify and share geographic locations.

Privacy Statement
Privacy is a concern when you share a physical location with a remote Web server. Therefore, the Geography API requires users to provide permissions before the Web application can access location information. When you first access a Web page that requests geographic data, the browser displays a notification bar that prompts you for access to the user's location. Follow the browser's prompts to select the appropriate authorization.
If the user does not grant permissions, location information is not provided to the WEB application. Invoking the relevant APIs does not trigger a successful callback.

Check your browser's support
The Geolocation API is supported in the latest version of the mainstream browsers, but check it for compatibility with older browsers. If the geography API is not available, window.navigator.geolocation will be null, as follows:

The code is as follows Copy Code
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 attribute of the Navigator global object: Navigator.geolocation, which provides useful information about the visitor's browser and system. Geolocation information can be obtained by many means, such as base station, Web database, or GPS. The use of different methods to obtain the geolocation information accuracy is not the same, usually, the most accurate through GPS (mobile platform to use the most GPs, PC platform is based on the basic network data). Occasionally, in some places, you may not be able to get a clear geographic reading or a little bit of data to receive.

Locate Current Position
Use the Navigator.geolocation getcurrentposition () method to get the user's current position, which takes only one position of information. When the method is invoked by a script, the method attempts to obtain the current location of the host device asynchronously.


Method signature: GetCurrentPosition (geolocationsuccesscallback,[geolocationerrorcallback,geolocationoptions]);
Geolocationsuccesscallback: Gets the callback after the current position succeeds (required)
Geolocationerrorcallback. Callback to use when error occurs (optional)
Geolocationoptions. Geography Options (optional)

Process location Information

The Getcurrentpositon () method saves the location information to a position object after the current position succeeds, and then executes the object as a parameter to perform the Geolocationsuccesscallback callback. In this callback function, you can arbitrarily dispose of the information contained in this object.
The Position object has two properties: Timestamp and coords. The Timestamp property represents the creation time of the geographic data, and the Coords attribute represents the location information and contains seven properties:


Coords.latitude: Estimating Latitude
Coords.longitude: Estimating Longitude
Coords.altitude: Estimate height
Coords.accuracy: The accuracy of the estimate of longitude and latitude provided in meters
Coords.altitudeaccuracy: The accuracy of a height estimate provided in meters
Coords.heading: The angle direction at which the host device is currently moving, calculated clockwise relative to the north direction
Coords.speed: Current ground speed of equipment with meters per second
Generally, three of these attributes are guaranteed: Coords.latitude, Coords.longitude, and Coords.accuracy, and the remainder returns NULL, depending on the device's capabilities and the backend location server it uses. Also, the heading and speed properties can be computed based on the location of the user before.

Handling Errors

If an error occurs when the Getcurrentpositon () method is executed, the method passes a Positionerror object to the Geolocationerrorcallback callback.

Set geography options

You can set the three properties of Geolocationoptions:

Enablehighaccuracy: If the device supports high precision, this option indicates whether high precision is enabled.
Timeout: Query timeout time
Maximumage: The maximum number of times the cached location can be used during this time period. See the complete example below:

The code is as follows Copy Code

<! DOCTYPE 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 isn't 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 ("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>

This example gets to the location of the current device and displays it in Google Maps. Of course you can use the static chart in the Baidu Map API to transform this example. The Baidu Map API refers to the links in the practical references that follow.


Open/Cancel continuous positioning
Use the Navigator.geolocation watchposition () method to periodically poll the user's location to see if 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 to get the location information; This method has a return value Watchid to cancel the persistent positioning.

Use the Navigator.geolocation Clearwatch () method to terminate the Watchposition () that is in progress, which takes only one parameter watchid.

Look at the following example:

The code is as follows Copy Code

<! DOCTYPE html>
<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>
<body>
<label for= "Latitude" >latitude: </label><input id= "latitude"/> <br
<label for= "Longitude" >longitude: </label><input id= "Longitude"/> <br
<input type= "button" value= "Watch Latitude and longitude" onclick= "listenforpositionupdates ()"/>
<input type= "button" value= "Clear Watch" onclick= "Clearwatch ()"/>

</body>


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.