手機端H5獲取當前城市的方法

移動端的H5頁面提供了定位的功能,那麼如何實現一個最簡單的需求-----獲取用戶當前城市?php

你可能搜一下就會找到N篇博客介紹,可是你會發現你看完大段代碼以後仍是沒搞清楚,爲了便於你們理解,我精簡了代碼,只保留了必要的部分。html

 

一、在html頁面引入百度地圖API(文檔地址:http://developer.baidu.com/map/wiki/index.php?title=jspopular/guide/introductiongit

<script src="http://api.map.baidu.com/api?ak=你的AK碼&v=2.0&services=false"></script>

 

二、js代碼使用h5的geolocation方法獲取座標,而後使用百度api的getlocation方法翻譯成你想要得結果api

複製代碼
 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 });
複製代碼

 

三、打開手機試一下吧jsp

 

若是不須要精準的定位,還有一種經過IP地址獲取當前城市的方法,採用新浪的api接口。ide

<script src="http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js"></script> <script> var city = remote_ip_info['city']; alert(city) </script>
相關文章
相關標籤/搜索