to determine browser compatibility issues:ie9+ supports geolocation and the FF Chrome version supports geo-targeting
if (navigator.geolocation) { Alert (' Support geo-location '); } else { Alert (' geo-location not supported '); } |
get the latitude and longitude of your position
<script> var X=document.getelementbyid ("Wrap"); function GetLocation () { if (navigator.geolocation) { Navigator.geolocation.GetCurrentPosition(showposition); } else { Alert (' Don't support geo-targeting--HTML5 free! ‘); } } getLocation ();
function Showposition (position) { x.innerhtml = "Latitude:" +Position.coords.latitude+ "<br/> Longitude:" +Position.coords.longitude;
} </script> |
Handling Errors and rejections
getcurrentposition (parameter 1, parameter 2); The second parameter of the method is used to handle an error. It specifies the function that runs when the user location fails to get
Error code:
- Permission denied-user does not allow geo-location
- Position unavailable-Unable to get current position
- Timeout-operation timed out
/ * Display positioning error * / function ShowError (Error) { SwitchError.code) { Caseerror. Position_unavailable: X.innerhtml= "Cannot get the current location! "; Break Caseerror. Permission_denied: X.innerhtml= "Users are not allowed to geo-locate! "; Break Caseerror. TIMEOUT: X.innerhtml= "Operation timed out! "; Break Caseerror. Unknown_error: X.innerhtml= "Unknown Error! " ; Break } } |
watchPosition 使用方法跟getCurrenPosition方法类似 ,
watchposition returns the user's current location, which is the same as a GPS if the user moves back to the live location.
①navigator.geolocation.
watchposition (showposition);
②
Clearwatch ()-Stop Watchposition () method
? Baidu Map API Assistant http://developer.baidu.com/map/
/* latitude and longitude displayed on the map */
function Showonmap (position) { var latlon=position.coords.latitude+ "," +position.coords.longitude;< /c4> var img_url= "http://maps.googleapis.com/maps/api/staticmap?center=" +latlon+ "&ZOOM=14&A Mp;size=400x300&sensor=false "; document.getElementById ("Mapholder"). Innerhtml= " '; } |
Demo demo: display latitude longitude call Baidu Map API display map Information