- Geolocation工作原理
- Geolocation API
- getCurrentPosition方法
- Geolocation数据
- Handling Errors
- PositionOptions对象
- watchPosition()方法和clearWatch()方法
- Example
- 扩展阅读
识别地理位置的主要方法:
调用Geolocation API从全局navigator对象的geolocation属性开始:navigator.geolocation
<script type='text/javascript'> // 最简单的使用方式:没有做任何的检测,错误处理,也没有选项参数 function find_my_location() { navigator.geolocation.getCurrentPosition(show_map); } </script>
方法1: 全局对象navigator是否具有geolocation属性
<script type='text/javascript'> function supports_geolocation() { return !!navigator.geolocation; } </script>
方法2: 使用Modernizr提供的方法
<script type='text/javascript'> function find_my_location() { if (Modernizr.geolocation) { navigator.geolocation.getCurrentPosition(show_map); } else { // 浏览器没有提供原生支持,使用回退方案 } } </script>
使用getCurrentPosition()方法 .
<script type='text/javascript'> function find_my_location() { if (Modernizr.geolocation) { navigator.geolocation.getCurrentPosition(show_map); } else { // 其他方案 } } function show_map(position) { var latitude = position.coords.latitude; var longitude = position.coords.longitude; alert('Lat: ' + latitude + ' Lon: ' + longitude); } </script>
成功的回调函数的参数是一个Position对象,包括coords和timestamp两个属性。
属性 | 类型 | 备注 |
---|---|---|
coords.latitude | double | 纬度(度) |
coords.longitude | double | 经度(度) |
coords.accuracy | double | 精度(米) |
coords.altitude | double或null | 海拔(米) |
coords.altitudeAccuracy | double或null | 海拔精度(米) |
coords.heading | double或null | 度(顺时针,以正北为基准) |
coords.speed | double或null | 米/秒 |
timestamp | DOMTimeStamp | 可以转成Date对象 |
getCurrentPosition()的第二个参数(可选)——容错处理的回调函数:
<script type='text/javascript'> function find_my_location() { if (Modernizr.geolocation) { navigator.geolocation.getCurrentPosition(show_map, handle_error); } else { // 其他方案 } } function handle_error(err) { if (err.code == 1) { // 用户说不! } } </script>
在获取地理位置过程中有任何错误,都会调用该回调函数,并且会传入一个PositionError对象作为参数。
属性 | 类型 | 备注 |
---|---|---|
code | short | 可枚举 |
message | DOMString | 与终端用户无关 |
其中code属性具有以下属性值:
属性 | 类型 | 默认值 | 备注 |
---|---|---|---|
enableHighAccuracy | boolean | false | 设成true可能会使得获取位置的速度变慢 |
timeout | long | 没有默认值 | 单位:毫秒 |
maximumAge | long | 0 | 单位:毫秒 |
navigator.geolocation.getCurrentPosition(function(position) { var latLng = new google.maps.LatLng( position.coords.latitude, position.coords.longitude); var marker = new google.maps.Marker({position: latLng, map: map}); map.setCenter(latLng); }