Geolocation
- 6. Geolocation API
检测浏览器是否支持地理位置API
方法1: 检测检测 全局对象navigator是否具有geolocation属性
方法2: 使用Modernizr提供的方法 检测检测
安博中程在线
<script type='text/javascript'>
function supports_geolocation() {
return !!navigator.geolocation;
}
</script>
JAVASCRIPT
<script type='text/javascript'>
function find_my_location() {
if (Modernizr.geolocation) {
navigator.geolocation.getCurrentPosition(show_map);
} else {
// 浏览器没有提供原生支持,使用回退方案
}
}
</script>
JAVASCRIPT
6/14
- 7. Geolocation API
getCurrentPosition()
使用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>
JAVASCRIPT
7/14
- 10. PositionError对象
属性 类型 备注
code short 可枚举
message DOMString 与终端用户无关
其中code属性具有以下属性值:
安博中程在线
PERMISSION_DENIED(1): 用户不同意被获取位置信息。
POSITION_UNAVAILABLE(2): 网络不可用或者无法连接到获取位置信息的卫星。
TIMEOUT(3): 网络可用但是花了太长时间的计算用户的位置上。
UNKNOWN_ERROR(0): 发生其他未知错误。
·
·
·
·
10/14