html5获取用户地理位置

html5获取用户地理位置 w3c的获取不了 。
怎么能像饿了么 美团那样获取用户所在的城市区域呢

阅读 2.7k
2 个回答

可以通过H5的内置程序获得:

if (navigator.geolocation) {
  var timeoutVal = 10 * 1000 * 1000;
  navigator.geolocation.getCurrentPosition(
    displayPosition, 
    displayError,
    { enableHighAccuracy: true, timeout: timeoutVal, maximumAge: 0 }
  );
}
else {
  alert("Geolocation is not supported by this browser");
}

function displayPosition(position) {
  alert("Latitude: " + position.coords.latitude + ", Longitude: " + position.coords.longitude);
}

function displayError(error) {
  var errors = { 
    1: '申请拒绝',
    2: '无法精确匹配地址',
    3: '请求超时'
  };
  alert("错误: " + errors[error.code]);
}

浏览器支持:

  • Firefox 3.5+
  • Chrome 5.0+
  • Safari 5.0+
  • Opera 10.60+
  • Internet Explorer 9.0+

手机支持:

  • Android 2.0+
  • iPhone 3.0+
  • Opera Mobile 10.1+
  • Symbian (S60 3rd & 5th generation)
  • Blackberry OS 6

H5 只会提供坐标值给你,如果想要获取精确的省市区位置,可以使用百度、高德的 api 去获取。注意浏览器权限,原生的 geolocation 是无法在 http 下生效的,只能在 https 有效果。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题