html5 geoLocation
1. 判断用户的浏览器是否支持html5定位, navigator.geolocation是否存在
2. navigator.geolocation有三个方法
=> void navigator.geolocation.getCurrentPosition(onSuccess, onError, options) 获取用户当前位置
=> int watchCurrentPosition(onSuccess,onError,options) 持续获取当前用户位置
=> void clearWatch(watchId) watchId 为watchCurrentPosition返回的值 取消监控
3. 例子+描述
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) ); }