I. Introduction
HTML5 provides the geolocation attribute for window. navigator to obtain the geographic location of the current user based on the browser.
Window. Navigator. geolocation provides three methods:
Void getcurrentposition (onsuccess, onerror, options );
// Obtain the current user location
Int watchcurrentposition (onsuccess, onerror, options );
// Continuously obtain the current user location
Void clearwatch (watchid );
// Watchid is the value returned by watchcurrentposition
// Cancel monitoring
Options = {
Enablehighaccuracy, // Boolean whether high-precision geographic information is required
Timeout, // timeout limit for getting information
Maximumage // The time when the geographical information is cached
}
// Options can be left empty, which is the default value.
Ii. Position object
When the location information is obtained successfully, the onsuccess method returns the position object, which can be used to obtain information about the location, including:
Position object attributes:
Latitude, // latitude
Longpolling, // longitude
Altitude, // altitude
Accuracy, // obtain the latitude or Longitude precision
Altitudeaccurancy, // accuracy of altitude
Heading, // The foreground direction of the device. Clockwise rotation angle in the north direction
Speed, // the forward speed of the device.
Timestamp, // The time when the geographic location information is obtained
3. Google map-based example
View the Code directly:
<! Doctype HTML>
<HTML lang = "en">
<Head>
<Meta charset = "UTF-8">
<Title> Google map example on the page </title>
</Head>
<Body onload = 'init () '>
<Div id = "map" style = 'width: 800px; Height: 800px; '> </div>
<SCRIPT type = "text/JavaScript" src = 'HTTP: // maps.google.com/maps/api/js? Sensor = false'> </SCRIPT>
<SCRIPT type = "text/JavaScript">
Function Init (){
If (navigator. geolocation ){
Navigator. geolocation. getcurrentposition (function (POS ){
VaR coords = pos. coords;
VaR latlng = new Google. Maps. latlng (coords. Latitude, coords. longpolling );
VaR Options = {ZOOM: 14, center: latlng, maptypeid: Google. Maps. maptypeid. Roadmap };
VaR map1;
Map1 = new Google. Maps. Map (document. getelementbyid ('map'), options );
VaR marker = new Google. Maps. Marker ({
Position: latlng,
Map: map1
});
VaR infowindow = new Google. Maps. infowindow ({
Content: 'Current location! '
});
Infowindow. Open (map1, marker );
});
}
}
</SCRIPT>
</Body>
</Html>