移動端的H5頁面提供了定位的功能,那么如何實現一個最簡單的需求-----獲取用戶當前城市?
你可能搜一下就會找到N篇博客介紹,但是你會發現你看完大段代碼之后還是沒搞清楚,為了便於大家理解,我精簡了代碼,只保留了必要的部分。
1、在html頁面引入百度地圖API(文檔地址:http://developer.baidu.com/map/wiki/index.php?title=jspopular/guide/introduction)
<script src="http://api.map.baidu.com/api?ak=你的AK碼&v=2.0&services=false"></script>
2、js代碼使用h5的geolocation方法獲取坐標,然后使用百度api的getlocation方法翻譯成你想要得結果
1 navigator.geolocation.getCurrentPosition(function (position) { 2 var lat = position.coords.latitude; 3 var lon = position.coords.longitude; 4 var point = new BMap.Point(lon, lat); // 創建坐標點 5 // 根據坐標得到地址描述 6 var myGeo = new BMap.Geocoder(); 7 myGeo.getLocation(point, function (result) { 8 var city = result.addressComponents.city; 9 $('body').html(city); 10 }); 11 });
3、打開手機試一下吧
如果不需要精准的定位,還有一種通過IP地址獲取當前城市的方法,采用新浪的api接口。
<script src="http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js"></script> <script> var city = remote_ip_info['city']; alert(city) </script>