1. 判斷用戶的瀏覽器是否支持html5定位, navigator.geolocation是否存在html
2. navigator.geolocation有三個方法
=> void navigator.geolocation.getCurrentPosition(onSuccess, onError, options) 獲取用戶當前位置
=> int watchCurrentPosition(onSuccess,onError,options) 持續獲取當前用戶位置
=> void clearWatch(watchId) watchId 爲watchCurrentPosition返回的值 取消監控html5
3. 例子+描述git
if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(locationSuccess, locationError,{ // 指示瀏覽器獲取高精度的位置,默認爲false enableHighAcuracy: true, // 指定獲取地理位置的超時時間,默認不限時,單位爲毫秒 timeout: 5000, // 最長有效期,在重複獲取地理位置時,此參數指定多久再次獲取位置。 maximumAge: 3000 }); }else{ alert("Your browser does not support Geolocation!"); } locationError: function(error){ switch(error.code) { case error.TIMEOUT: showError("A timeout occured! Please try again!"); break; case error.POSITION_UNAVAILABLE: showError('We can\'t detect your location. Sorry!'); break; case error.PERMISSION_DENIED: showError('Please allow geolocation access for this to work.'); break; case error.UNKNOWN_ERROR: showError('An unknown error occured!'); break; } } locationSuccess: function(position){ var coords = position.coords; var timestamp = position.timestamp; console.log("latitude="+coords.latitude+" longitude is " + coords.longitude + " use time is " + timestamp) ); }