HTML5 Geolocation用来定位用户的位置。
定位用户的位置
HTMl5 Geolocation API用来得到用户的地理位置。
因为这个可能和个人隐私相关,除非用户允许否则不能使用。
浏览器支持
IE9,Firefox,Chrome,Opera和Safari 5都支持这个特性。
注意:如果使用带有GPS的设备,例如iphone,Geolocation将会更加准确。
HTML5 - 使用Geolocation
使用getCurrentPosition()方法得到用户的位置。
下面这个例子是一个简单的返回用户所在地点经纬度的例子:
在线演示
代码说明:
- 首先检查Geolocation是否支持
- 如果支持,运行getCurrentPosition()方法,如果不支持,显示给用户信息
- 如果getCurrentPosition()方法成功了,返回一个坐标的对象到参数指定的方法(showPosition)中
- showPosition()方法得到显示的经纬度
上面的例子是一个基本的Geolocation脚本,没有做错误处理。
处理错误和拒绝
getCurrentPosition()方法的第二个参数用来处理错误。指定一个方法当无法得到用户位置的时候来处理错误。
在线演示
错误代码如下:
- 权限拒绝:用户不需要执行Geolocation
- 位置不存在:无法得到用户位置
- 超时:操作超时
在Map中显示结果
为了在map中显示结果,你需要访问一个可以处理经纬度的地图服务,例如,GoogleMaps:
在上面的例子中,我们使用返回的经纬度来展示位置到Google地图中。如何使用脚本来展示一个互动的地图,带有标记,缩放和拖动功能。
在线演示
地理位置指定信息
这里我们演示了如何展示用户位置到地图上。然而,Geolocation也同样对于地理指定的信息非常有用。
例如:
- 最新的本地信息
- 展示用户周围的有趣地方
- 导航(GPS)
getCurrentPosition()方法 - 返回数据
如果成功getCurrentPosition()方法将返回一个对象。经纬度和准确的信息也会返回。其它属性如果存在也返回。
Property Description
coords.latitude The latitude as a decimal number
coords.longitude The longitude as a decimal number
coords.accuracy The accuracy of position
coords.altitude The altitude in meters above the mean sea level
coords.altitudeAccuracy The altitude accuracy of position
coords.heading The heading as degrees clockwise from North
coords.speed The speed in meters per second
timestamp The date/time of the response
Geolocation 对象 - 其它方法
watchPosition()方法 - 返回目前的用户位置并且当用户移动后继续返回更新的位置(例如车里的GPS)。
clearWatch()方法 - 停止watchPosition()方法
下面的代码展示了如何使用watchPositin()方法,注意你需要一个准确的GPS设备来测试(例如,iphone)