Determine the compatibility of the browser:IE9 + supports geographic positioning, and the new version of FF Chrome supports geographic positioning
If (Navigator. geolocation){ Alert ('support for geographic location '); } Else { Alert ('geographic positioning not supported '); } |
Obtain the longitude and latitude of your location
<Script> Var x = document. getElementById ("wrap "); Function getLocation (){ If (navigator. geolocation ){ Navigator. geolocation.GetCurrentPosition(ShowPosition ); } Else { Alert ('the geographic positioning is not supported-HTML5 freetier! '); } } GetLocation ();
Function showPosition (position ){ X. innerHTML = "latitude:" +Position. coords. latitude+ "<Br/> longitude:" +Position. coords. longpolling;
} </Script> |
Handle errors and reject
GetCurrentPosition (parameter 1, parameter 2 );MethodSecondParameters are used to handle errors. It specifies the function that runs when the user location fails to be obtained.
Error code:
- Permission denied
- Position unavailable-unable to get the current location
- Timeout-operation Timeout
/* Display Location Error */ Function showError (error ){ Switch (Error. code){ CaseError. POSITION_UNAVAILABLE: X. innerHTML = "unable to get the current location! "; Break; CaseError. PERMISSION_DENIED: X. innerHTML = "you are not allowed to locate the website! "; Break; CaseError. TIMEOUT: X. innerHTML = "Operation timeout! "; Break; CaseError. UNKNOWN_ERROR: X. innerHTML = "Unknown error! "; Break; } } |
The usage of watchPosition is similar to that of getCurrenPosition,
WatchPosition returns the current position of the user. If the user moves, the real-time location is returned, just like GPS.
① Navigator. geolocation.
WatchPosition(ShowPosition );
②
ClearWatch ()-Stop the watchPosition () method
Baidu map API assistant http://developer.baidu.com/map/
/* Display the longitude and latitude on the map */
Function showOnMap (position) {var latlon = position. coords. latitude + "," + position. coords. longpolling; var img_url = "http://maps.googleapis.com/maps/api/staticmap? Center = "+ latlon +" & zoom = 14 & size = 400x300 & sensor = false "; document. getElementById ("mapholder "). innerHTML = " ";} |
DEMO: display the latitude and longitude call Baidu map API to display map information